# @neuronetiq/contracts v0.17.0

🎯 **DOMAIN-SEPARATED SSOT** - Clean schemas with pandas-ta integration, manual investments, and IG trading

## 📦 **QUICK INSTALL**

```bash
# Install latest version (recommended)
pnpm add @neuronetiq/contracts@0.17.0
```

## 🧪 **THREE ONE-LINER VALIDATORS**

### **1. Production Health Check**
```bash
curl -s https://infra.neuronetiq.ai/api/health | jq .
```

### **2. Manual Investment Validation**
```bash
node -e "const {ManualInvestment} = require('@neuronetiq/contracts'); const test = {id:'550e8400-e29b-41d4-a716-446655440000',owner:'pacey999',asset_type:'stock',symbol:'AAPL',quantity:100,cost_basis:150,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}; console.log('Investment valid:', ManualInvestment.safeParse(test).success)"
```

### **3. ML Signal Validation**
```bash
node -e "const {Signal,makeSignal} = require('@neuronetiq/contracts'); const result = makeSignal({owner:'pacey999',model_id:'test',symbol:'EURUSD',timeframe:'5m',bar_ts:new Date().toISOString(),decision:'BUY',confidence:0.6}); console.log('Signal valid:', result.ok)"
```

## 🏗️ **DOMAIN ARCHITECTURE**

### **Portfolio Domain (Static Wealth)**
```typescript
import { ManualInvestment, PortfolioSnapshot, ROUTES } from '@neuronetiq/contracts';

// Track manual investments
const investment = ManualInvestment.parse({
  id: "uuid",
  owner: "pacey999",
  asset_type: "stock",
  symbol: "AAPL",
  quantity: 100,
  cost_basis: 150.50,
  created_at: new Date().toISOString(),
  updated_at: new Date().toISOString()
});

// Portfolio snapshots
const snapshot = PortfolioSnapshot.parse({
  id: "uuid", 
  owner: "pacey999",
  snapshot_date: "2024-09-04",
  total_value: 16500.00,
  total_pl: 1450.00,
  currency: "USD",
  accounts: [{ source: "manual", account_name: "Stocks", value: 16500, cost: 15050, pl: 1450 }],
  created_at: new Date().toISOString()
});

// API endpoints
fetch(ROUTES.PORTFOLIO.MANUAL_ADD, { method: 'POST', body: JSON.stringify(investment) });
```

### **Market Domain (OHLCV + Technical Indicators)**
```typescript
import { OHLCVBar, TAIndicatorValue, ROUTES, taParamsHash } from '@neuronetiq/contracts';

// OHLCV market data
const bar = OHLCVBar.parse({
  bar_id: "uuid",
  symbol: "EURUSD",
  timeframe: "5m",
  bar_ts: "2024-09-04T14:05:00Z",
  open: 1.1045, high: 1.1050, low: 1.1040, close: 1.1048
});

// Technical indicators (pandas-ta integration)
const rsi = TAIndicatorValue.parse({
  bar_id: bar.bar_id,
  symbol: "EURUSD",
  timeframe: "5m", 
  bar_ts: bar.bar_ts,
  name: "rsi",
  provider: "pandas_ta",
  params: { length: 14, source: "close" },
  params_hash: taParamsHash({ length: 14, source: "close" }),
  values: { rsi: 54.2 },
  computed_at: new Date().toISOString()
});

// API endpoints
fetch(ROUTES.MARKET.OHLCV + "?symbol=EURUSD&timeframe=5m");
fetch(ROUTES.MARKET.INDICATORS_STORE, { method: 'POST', body: JSON.stringify({ items: [rsi] }) });
```

### **ML Domain (Signals & Consensus)**
```typescript
import { Signal, makeSignal, buildSignalDedupKey, ROUTES } from '@neuronetiq/contracts';

// Create ML signal with helper
const result = makeSignal({
  owner: "pacey999",
  model_id: "baseline-rsi", 
  symbol: "EURUSD",
  timeframe: "5m",
  bar_ts: "2024-09-04T14:05:00Z",
  decision: "BUY",
  confidence: 0.62,
  model_version: "v1.2.3",
  features_used: ["rsi_14", "sma_20"],
  bar_id: "uuid",
  ta_fingerprint: "abc123"
});

if (result.ok) {
  // Store signal via API
  fetch(ROUTES.ML.SIGNALS_STORE, { 
    method: 'POST', 
    body: JSON.stringify(result.data),
    headers: { 'X-Idempotency-Key': result.data.dedup_key }
  });
}

// Read latest signals
fetch(ROUTES.ML.SIGNALS_LATEST + "?symbol=EURUSD&timeframe=5m");
```

### **Trading Domain (IG Execution)**
```typescript
import { TradingPosition, Trade, ROUTES } from '@neuronetiq/contracts';

// Track IG spread betting position
const position = TradingPosition.parse({
  id: "uuid",
  owner: "pacey999",
  ig_position_id: "DEAL123456",
  symbol: "EURUSD",
  direction: "BUY",
  size: 10.0,
  open_price: 1.1045,
  current_price: 1.1048,
  unrealized_pnl: 3.0,
  opened_at: "2024-09-04T14:05:00Z",
  updated_at: new Date().toISOString()
});

// Trade execution record
const trade = Trade.parse({
  id: "uuid",
  owner: "pacey999", 
  position_id: position.id,
  ig_deal_id: "DEAL789",
  action: "OPEN",
  symbol: "EURUSD",
  direction: "BUY",
  size: 10.0,
  price: 1.1045,
  executed_at: "2024-09-04T14:05:00Z",
  status: "executed"
});

// API endpoints
fetch(ROUTES.TRADING.POSITIONS + "?owner=pacey999");
```

## 🔧 **HELPER FUNCTIONS**

```typescript
import { 
  makeSignal, 
  buildSignalDedupKey, 
  taParamsHash, 
  buildTAFingerprint,
  successEnvelope,
  errorEnvelope 
} from '@neuronetiq/contracts';

// Create validated signals
const signalResult = makeSignal({
  owner: "pacey999",
  model_id: "baseline-rsi",
  symbol: "EURUSD", 
  timeframe: "5m",
  bar_ts: "2024-09-04T14:05:00Z",
  decision: "BUY",
  confidence: 0.62
});

// Generate stable hashes
const dedupKey = buildSignalDedupKey({symbol: "EURUSD", timeframe: "5m", bar_ts: "2024-09-04T14:05:00Z", model_id: "test"});
const paramsHash = taParamsHash({length: 14, source: "close"});
const taFingerprint = buildTAFingerprint([{name: "rsi", params_hash: paramsHash}]);

// API responses
const success = successEnvelope(data, "req_12345");
const error = errorEnvelope("VALIDATION_ERROR", "Invalid symbol", "req_12345");
```

## 📊 **OPTIMIZATION RESULTS**

- **Package Size**: 19.94 KB (vs 247KB) **-92% reduction** 🎉
- **TypeScript Declarations**: 60.48 KB (vs 1.05MB) **-94% reduction** 🎉  
- **Total Exports**: 55 (vs 449) **-88% reduction** 🎉
- **Schema Files**: 6 clean domain files (vs 32 duplicated files)
- **Test Coverage**: 194 tests with comprehensive drift guards

## 🔐 **VERSION & FINGERPRINT**

```typescript
import { CONTRACTS_VERSION, CONTRACTS_FINGERPRINT } from '@neuronetiq/contracts';

console.log('Version:', CONTRACTS_VERSION); // "0.17.0"
console.log('Fingerprint:', CONTRACTS_FINGERPRINT); // "0.17.0:fbac3098c0e2cf4222285cdb69fa5c32f991d11789e9a8113dbeb793548a3fa4"
```

## 🧪 **TESTING**

```bash
# Run all tests
pnpm test:all

# Run drift guards only  
pnpm test:drift-guards

# Validate before publishing
pnpm prepublishOnly
```

## 🚀 **INFRASTRUCTURE MIGRATION**

The package includes complete SSOT migration specifications for Infrastructure team:

- **`INFRASTRUCTURE_MIGRATION_v0.17.0.sql`** - Complete database migration
- **Domain-separated schemas**: `market.*`, `ml.*`, `trading.*`, `portfolio.*`
- **Compatibility views** - Zero-downtime migration
- **RLS policies** - Secure, role-based access

---

**🎯 v0.17.0 COMPLETE & READY FOR TEAM HANDOVER**