# OrbiQuant IA - Service Integration Contracts ## Overview Este documento define los contratos de API entre los servicios de la plataforma OrbiQuant IA para uso personal con enfoque en ML. ## Architecture ``` ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Frontend │────▶│ Backend │────▶│ ML Engine │ │ (React/Vite) │ │ (Express.js) │ │ (FastAPI) │ │ Port: 5173 │ │ Port: 8000 │ │ Port: 8002 │ └─────────────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ ┌────────▼────────┐ ┌────────▼────────┐ │ LLM Agent │ │ Data Service │ │ (FastAPI) │ │ (FastAPI) │ │ Port: 8003 │ │ Port: 8001 │ └─────────────────┘ └─────────────────┘ ``` ## Service Ports | Service | Port | Description | |---------|------|-------------| | Backend | 8000 | Main API Gateway (Express.js) | | Data Service | 8001 | Market data from Massive.com/Polygon | | ML Engine | 8002 | ML predictions and signals | | LLM Agent | 8003 | AI copilot and auto-trading | | Frontend | 5173 | React application (dev) | | Ollama | 11434 | Local LLM inference | | PostgreSQL | 5432 | Main database | | Redis | 6379 | Cache and sessions | --- ## Data Service API (Port 8001) Base URL: `http://localhost:8001` ### Health Check ``` GET /health Response: { status: "healthy", providers: [...], uptime: 123 } ``` ### Get OHLCV Data ``` GET /api/ohlcv Query Parameters: - symbol: string (required) - e.g., "XAUUSD" - timeframe: string (required) - "1m", "5m", "15m", "1h", "4h", "1d" - start: ISO datetime (optional) - end: ISO datetime (optional) - limit: number (optional, default: 1000) Response: { "bars": [ { "timestamp": "2025-12-08T12:00:00Z", "open": 2350.50, "high": 2355.00, "low": 2348.00, "close": 2352.75, "volume": 15000 } ], "symbol": "XAUUSD", "timeframe": "15m", "count": 100 } ``` ### Get Snapshot ``` GET /api/snapshot/{symbol} Response: { "symbol": "XAUUSD", "bid": 2350.25, "ask": 2350.75, "last_price": 2350.50, "timestamp": "2025-12-08T12:00:00Z", "daily_change": 5.50, "daily_change_pct": 0.23 } ``` ### Get Symbols ``` GET /api/symbols Response: { "symbols": ["XAUUSD", "EURUSD", "GBPUSD", "BTCUSD", "ETHUSD"] } ``` ### Sync Data ``` POST /api/sync/{symbol} Body: { "start_date": "2025-01-01T00:00:00Z", "end_date": "2025-12-08T00:00:00Z" } Response: { "status": "completed", "rows_synced": 50000 } ``` ### WebSocket Stream ``` WS /ws/stream Subscribe message: { "action": "subscribe", "channels": ["ticker", "candles"], "symbols": ["XAUUSD", "BTCUSD"] } ``` --- ## ML Engine API (Port 8002) Base URL: `http://localhost:8002` ### Health Check ``` GET /health Response: { "status": "healthy", "version": "0.1.0", "models_loaded": true, "timestamp": "2025-12-08T12:00:00Z" } ``` ### Get Active Signals (NEW - Primary endpoint for dashboard) ``` GET /api/signals/active Query Parameters: - symbols: string (optional) - Comma-separated, e.g., "XAUUSD,EURUSD" - timeframe: string (optional, default: "15m") - rr_config: string (optional, default: "rr_2_1") Response: { "signals": [ { "signal_id": "SIG-A1B2C3D4", "symbol": "XAUUSD", "direction": "long", "entry_price": 2350.50, "stop_loss": 2345.50, "take_profit": 2360.50, "risk_reward_ratio": 2.0, "prob_tp_first": 0.62, "confidence_score": 0.72, "amd_phase": "accumulation", "volatility_regime": "medium", "range_prediction": { "horizon": "15m", "delta_high": 12.5, "delta_low": 8.3, "confidence_high": 0.72, "confidence_low": 0.68 }, "timestamp": "2025-12-08T12:00:00Z", "valid_until": "2025-12-08T12:15:00Z" } ], "generated_at": "2025-12-08T12:00:00Z", "symbols_processed": ["XAUUSD", "EURUSD"], "errors": [] } ``` ### Generate Single Signal ``` POST /generate/signal Body: { "symbol": "XAUUSD", "timeframe": "15m" } Query: ?rr_config=rr_2_1 Response: SignalResponse (same as above, single object) ``` ### Detect AMD Phase ``` POST /api/amd/{symbol} Query Parameters: - timeframe: string (default: "15m") - lookback_periods: number (default: 100) Response: { "phase": "accumulation", "confidence": 0.72, "start_time": "2025-12-08T11:00:00Z", "characteristics": { "range_compression": 0.65, "volume_ratio": 0.8 }, "signals": ["range_compression", "low_volume"], "strength": 0.68, "trading_bias": { "direction": "long", "position_size": 0.7 } } ``` ### Predict Range ``` POST /predict/range Body: { "symbol": "XAUUSD", "timeframe": "15m" } Response: [ { "horizon": "15m", "delta_high": 12.5, "delta_low": 8.3, "confidence_high": 0.72, "confidence_low": 0.68 } ] ``` ### WebSocket Signals ``` WS /ws/signals Receive real-time signals as they are generated ``` --- ## LLM Agent API (Port 8003) Base URL: `http://localhost:8003` ### Health Check ``` GET /api/v1/health Response: { "status": "healthy", "llm_provider": "ollama", "model": "llama3:8b", "gpu_available": true } ``` ### Chat ``` POST /api/v1/chat Body: { "message": "What's the current outlook for XAUUSD?", "user_id": "user123", "conversation_id": "conv456", "stream": true } Response (SSE stream or JSON): { "response": "Based on current analysis...", "tool_calls": [...], "conversation_id": "conv456" } ``` ### Auto-Trade Configuration (NEW) ``` POST /api/v1/auto-trade/config Body: { "enabled": true, "symbols": ["XAUUSD", "BTCUSD"], "max_risk_per_trade": 0.02, "max_daily_trades": 5, "min_confidence": 0.6, "paper_trading": true, "require_confirmation": false } Response: { "status": "configured", "config": { ... } } ``` ### Get Auto-Trade Status ``` GET /api/v1/auto-trade/status Response: { "enabled": true, "mode": "paper", "trades_today": 3, "last_decision": { "symbol": "XAUUSD", "action": "BUY", "timestamp": "2025-12-08T12:00:00Z", "reasoning": "..." } } ``` ### Get Trade Decisions History ``` GET /api/v1/auto-trade/decisions Query: ?limit=50&symbol=XAUUSD Response: { "decisions": [ { "id": "dec123", "symbol": "XAUUSD", "action": "BUY", "confidence": 0.72, "reasoning": "AMD phase is accumulation...", "ml_signal": { ... }, "executed": true, "result": "pending", "timestamp": "2025-12-08T12:00:00Z" } ] } ``` ### MT4 Integration (NEW) #### Connect to MT4 ``` POST /api/v1/auto-trade/mt4/connect Body: { "account_id": "your-metaapi-account-id", "token": "optional-metaapi-token" } Response: { "success": true, "connected": true, "account": { "login": "12345678", "server": "Broker-Demo", "balance": 10000.0, "currency": "USD", "leverage": 100 } } ``` #### Get MT4 Status ``` GET /api/v1/auto-trade/mt4/status Response: { "connected": true, "account": { "id": "acc123", "login": "12345678", "server": "Broker-Demo", "platform": "mt4", "balance": 10000.0, "equity": 10150.0, "margin": 500.0, "free_margin": 9650.0, "profit": 150.0, "currency": "USD", "leverage": 100 } } ``` #### Get Open Positions ``` GET /api/v1/auto-trade/mt4/positions Response: { "success": true, "positions": [ { "id": "pos123", "symbol": "EURUSD", "type": "BUY", "volume": 0.1, "open_price": 1.1000, "current_price": 1.1050, "stop_loss": 1.0950, "take_profit": 1.1100, "profit": 50.0, "swap": -0.5, "open_time": "2025-12-08T10:00:00Z" } ] } ``` #### Close Position ``` POST /api/v1/auto-trade/mt4/positions/close Body: { "position_id": "pos123", "volume": null // null = close all } Response: { "success": true, "position_id": "pos123" } ``` #### Disconnect from MT4 ``` POST /api/v1/auto-trade/mt4/disconnect Response: { "success": true, "connected": false } ``` --- ## Data Service MT4 API (Port 8001) Base URL: `http://localhost:8001/api/mt4` ### Connect to MT4 Account ``` POST /api/mt4/connect Body: { "account_id": "metaapi-account-id", "token": "optional-metaapi-token" } Response: { "connected": true, "account_id": "acc123", "login": "12345678", "server": "Broker-Demo", "platform": "mt4", "balance": 10000.0, "currency": "USD" } ``` ### Get Real-Time Tick ``` GET /api/mt4/tick/{symbol} Response: { "symbol": "EURUSD", "bid": 1.0998, "ask": 1.1002, "spread": 0.0004, "timestamp": "2025-12-08T12:00:00Z" } ``` ### Get Historical Candles ``` GET /api/mt4/candles/{symbol}?timeframe=1h&limit=100 Response: [ { "time": "2025-12-08T11:00:00Z", "open": 1.0990, "high": 1.1010, "low": 1.0985, "close": 1.1000, "volume": 1250 } ] ``` ### Open Trade ``` POST /api/mt4/trade Body: { "symbol": "EURUSD", "action": "BUY", // BUY, SELL, BUY_LIMIT, SELL_LIMIT, BUY_STOP, SELL_STOP "volume": 0.1, "price": null, // null for market orders "stop_loss": 1.0950, "take_profit": 1.1100, "comment": "OrbiQuant AI" } Response: { "success": true, "order_id": "ord123", "position_id": "pos456" } ``` ### Close Position ``` POST /api/mt4/positions/{position_id}/close?volume=0.05 Response: { "success": true, "position_id": "pos456" } ``` --- ## Backend API (Port 8000) Base URL: `http://localhost:8000` ### Proxy to ML Engine ``` GET /api/ml/signals/active -> ML Engine /api/signals/active POST /api/ml/amd/{symbol} -> ML Engine /api/amd/{symbol} ``` ### Proxy to LLM Agent ``` POST /api/chat -> LLM Agent /api/v1/chat GET /api/auto-trade/status -> LLM Agent /api/v1/auto-trade/status ``` ### Portfolio Management ``` GET /api/portfolio POST /api/portfolio/positions GET /api/portfolio/history ``` --- ## Frontend API Consumption ### Services Configuration (Frontend) ```typescript // src/config/services.ts export const SERVICES = { BACKEND: import.meta.env.VITE_BACKEND_URL || 'http://localhost:8000', ML_ENGINE: import.meta.env.VITE_ML_ENGINE_URL || 'http://localhost:8002', DATA_SERVICE: import.meta.env.VITE_DATA_SERVICE_URL || 'http://localhost:8001', LLM_AGENT: import.meta.env.VITE_LLM_AGENT_URL || 'http://localhost:8003', }; ``` ### API Hooks (React Query) ```typescript // Example: useActiveSignals hook export function useActiveSignals(symbols?: string[]) { return useQuery({ queryKey: ['signals', 'active', symbols], queryFn: () => fetch(`${SERVICES.ML_ENGINE}/api/signals/active?symbols=${symbols?.join(',')}`), refetchInterval: 60000, // Refresh every minute }); } ``` --- ## Error Responses All services use consistent error format: ```json { "error": "Error type", "detail": "Detailed error message", "timestamp": "2025-12-08T12:00:00Z" } ``` HTTP Status Codes: - 200: Success - 400: Bad Request (invalid parameters) - 401: Unauthorized - 404: Not Found - 500: Internal Server Error - 503: Service Unavailable (models not loaded, etc.) --- ## WebSocket Events ### Data Service WebSocket ```javascript // Events received { type: "ticker", data: { symbol, price, timestamp } } { type: "candle", data: { symbol, ohlcv, timeframe } } { type: "orderbook", data: { symbol, bids, asks } } ``` ### ML Engine WebSocket ```javascript // Events received { type: "signal", data: SignalResponse } { type: "amd_change", data: { symbol, old_phase, new_phase } } ``` --- *Document Version: 1.0.0* *Last Updated: 2025-12-08*