--- id: "API" title: "API Documentation" type: "Documentation" project: "trading-platform" version: "1.0.0" updated_date: "2026-01-04" --- # API Documentation ## Base URL **Development:** `http://localhost:3081/api` **Production:** `https://api.orbiquant.com/api` (future) ## Port Configuration | Service | Port | Description | |---------|------|-------------| | Frontend | 3080 | React SPA | | Backend API | 3081 | Main REST API | | WebSocket | 3082 | Real-time data | | ML Engine | 3083 | ML predictions | | Data Service | 3084 | Market data | | LLM Agent | 3085 | Trading copilot | | Trading Agents | 3086 | Automated trading | | Ollama WebUI | 3087 | LLM management | ## Authentication ### JWT Authentication All protected endpoints require a JWT token in the header: ``` Authorization: Bearer ``` ### OAuth2 Providers Supported: Google, Facebook, Apple, GitHub ### 2FA (Two-Factor Authentication) TOTP-based using Speakeasy library. ## Core Endpoints ### Authentication (`/api/auth`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/register` | Register new user | No | | POST | `/login` | Login with credentials | No | | POST | `/logout` | Logout current session | Yes | | POST | `/refresh` | Refresh JWT token | Yes (refresh token) | | GET | `/me` | Get current user profile | Yes | | POST | `/oauth/google` | Login with Google | No | | POST | `/oauth/facebook` | Login with Facebook | No | | POST | `/oauth/apple` | Login with Apple | No | | POST | `/oauth/github` | Login with GitHub | No | #### Register User ```http POST /api/auth/register Content-Type: application/json { "email": "trader@example.com", "password": "SecurePass123!", "firstName": "John", "lastName": "Doe" } ``` **Response:** ```json { "user": { "id": "uuid", "email": "trader@example.com", "firstName": "John", "lastName": "Doe", "role": "user" }, "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refreshToken": "refresh_token_here", "expiresIn": 3600 } ``` #### Login ```http POST /api/auth/login Content-Type: application/json { "email": "trader@example.com", "password": "SecurePass123!", "totpCode": "123456" // Optional, if 2FA enabled } ``` ### Users (`/api/users`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/me` | Get current user | Yes | | PATCH | `/me` | Update profile | Yes | | POST | `/me/avatar` | Upload avatar | Yes | | GET | `/:userId` | Get user by ID | Yes (Admin) | ### Trading (`/api/trading`) #### Market Data | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/market/klines/:symbol` | Get candlestick data | Yes | | GET | `/market/price/:symbol` | Current price | Yes | | GET | `/market/prices` | Multiple prices | Yes | | GET | `/market/ticker/:symbol` | 24h ticker | Yes | | GET | `/market/tickers` | All tickers | Yes | | GET | `/market/orderbook/:symbol` | Order book | Yes | #### Orders | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/orders` | List user orders | Yes | | GET | `/orders/:orderId` | Get order details | Yes | | POST | `/orders` | Create order | Yes | | DELETE | `/orders/:orderId` | Cancel order | Yes | | GET | `/orders/active` | Active orders | Yes | | GET | `/orders/history` | Order history | Yes | #### Positions | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/positions` | List open positions | Yes | | GET | `/positions/:positionId` | Position details | Yes | | POST | `/positions/:positionId/close` | Close position | Yes | #### Create Order ```http POST /api/trading/orders Authorization: Bearer Content-Type: application/json { "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "quantity": 0.01, "price": 45000, "timeInForce": "GTC" } ``` **Response:** ```json { "order": { "id": "uuid", "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "quantity": 0.01, "price": 45000, "status": "NEW", "createdAt": "2025-12-12T10:00:00Z" } } ``` ### Portfolio (`/api/portfolio`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/` | Get user portfolio | Yes | | GET | `/balance` | Account balance | Yes | | GET | `/performance` | Performance metrics | Yes | | GET | `/pnl` | Profit & Loss | Yes | | GET | `/allocation` | Asset allocation | Yes | ### ML Predictions (`/api/ml`) #### Health & Status | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/health` | ML service health | No | | GET | `/connection` | Connection status | No | #### Signals & Predictions | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/signals/:symbol` | Get trading signal | Yes | | POST | `/signals/batch` | Batch signals | Yes | | GET | `/signals/:symbol/history` | Historical signals | Yes | | GET | `/predictions/:symbol` | Price prediction | Yes | | GET | `/amd/:symbol` | AMD phase detection | Yes | | GET | `/indicators/:symbol` | Technical indicators | Yes | #### Get Trading Signal ```http GET /api/ml/signals/BTCUSDT?timeframe=1h Authorization: Bearer ``` **Response:** ```json { "symbol": "BTCUSDT", "timeframe": "1h", "signal": "BUY", "strength": 85, "entry": 45000, "stopLoss": 44500, "takeProfit": 46500, "confidence": 0.87, "amdPhase": "ACCUMULATION", "indicators": { "rsi": 45, "macd": "bullish", "ema": "above" }, "timestamp": "2025-12-12T10:00:00Z" } ``` #### Get AMD Phase ```http GET /api/ml/amd/BTCUSDT Authorization: Bearer ``` **Response:** ```json { "symbol": "BTCUSDT", "phase": "ACCUMULATION", "confidence": 0.82, "description": "Smart Money está acumulando posición", "recommendation": "Comprar en zonas de soporte", "supportLevel": 44800, "resistanceLevel": 46200, "nextPhaseEstimate": "MANIPULATION", "timestamp": "2025-12-12T10:00:00Z" } ``` #### Backtesting | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/backtest` | Run backtest | Yes | ```http POST /api/ml/backtest Authorization: Bearer Content-Type: application/json { "symbol": "BTCUSDT", "strategy": "MEAN_REVERSION", "startDate": "2024-01-01", "endDate": "2024-12-31", "initialCapital": 10000, "parameters": { "rsiPeriod": 14, "overbought": 70, "oversold": 30 } } ``` **Response:** ```json { "results": { "totalTrades": 145, "winRate": 0.62, "profitFactor": 1.85, "totalReturn": 0.35, "maxDrawdown": 0.12, "sharpeRatio": 1.45, "equity": [...], "trades": [...] } } ``` #### Model Management | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/models` | List ML models | Yes (Admin) | | POST | `/models/retrain` | Trigger retraining | Yes (Admin) | | GET | `/models/retrain/:jobId` | Retraining status | Yes (Admin) | #### Chart Overlays | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/overlays/:symbol` | Chart overlay data | Yes | | POST | `/overlays/batch` | Batch overlays | Yes | | GET | `/overlays/:symbol/levels` | Price levels | Yes | | GET | `/overlays/:symbol/signals` | Signal markers | Yes | | GET | `/overlays/:symbol/amd` | AMD overlay | Yes | | GET | `/overlays/:symbol/predictions` | Prediction bands | Yes | ### LLM Copilot (`/api/llm`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/chat` | Chat with copilot | Yes | | GET | `/conversations` | List conversations | Yes | | GET | `/conversations/:id` | Get conversation | Yes | | DELETE | `/conversations/:id` | Delete conversation | Yes | | GET | `/health` | LLM service health | No | #### Chat with Copilot ```http POST /api/llm/chat Authorization: Bearer Content-Type: application/json { "message": "Analiza el BTC en este momento", "conversationId": "uuid", // Optional, para continuar conversación "context": { "symbol": "BTCUSDT", "timeframe": "1h" } } ``` **Response:** ```json { "conversationId": "uuid", "message": { "id": "msg-uuid", "role": "assistant", "content": "Analizando BTC/USDT en 1h...\n\nEl Bitcoin está en fase de ACUMULACIÓN según el modelo AMD (confianza 82%). Indicadores técnicos muestran:\n- RSI: 45 (neutral, espacio para subir)\n- MACD: Cruce alcista reciente\n- EMA 20/50: Precio sobre EMAs\n\nRecomendación: COMPRAR en zona 44,800-45,000 con stop en 44,500 y target en 46,500.", "toolsCalled": [ "market_analysis", "technical_indicators", "amd_detector" ], "timestamp": "2025-12-12T10:00:00Z" } } ``` ### Investment (PAMM) (`/api/investment`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/pamm/accounts` | List PAMM accounts | Yes | | GET | `/pamm/:accountId` | PAMM details | Yes | | POST | `/pamm/:accountId/invest` | Invest in PAMM | Yes | | POST | `/pamm/:accountId/withdraw` | Withdraw from PAMM | Yes | | GET | `/pamm/:accountId/performance` | Performance history | Yes | | GET | `/my/investments` | My investments | Yes | ### Education (`/api/education`) #### Public Endpoints | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/categories` | Course categories | No | | GET | `/courses` | List courses | No | | GET | `/courses/popular` | Popular courses | No | | GET | `/courses/new` | New courses | No | | GET | `/courses/:courseId` | Course details | No | | GET | `/courses/:courseId/modules` | Course modules | No | #### Student Endpoints | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/my/enrollments` | My enrolled courses | Yes | | GET | `/my/stats` | Learning statistics | Yes | | POST | `/courses/:courseId/enroll` | Enroll in course | Yes | | GET | `/courses/:courseId/enrollment` | Enrollment status | Yes | | POST | `/lessons/:lessonId/progress` | Update progress | Yes | | POST | `/lessons/:lessonId/complete` | Mark complete | Yes | #### Admin Endpoints | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/categories` | Create category | Yes (Admin) | | POST | `/courses` | Create course | Yes (Admin) | | PATCH | `/courses/:courseId` | Update course | Yes (Admin) | | DELETE | `/courses/:courseId` | Delete course | Yes (Admin) | | POST | `/courses/:courseId/publish` | Publish course | Yes (Admin) | ### Payments (`/api/payments`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/stripe/create-checkout` | Create Stripe checkout | Yes | | POST | `/stripe/webhook` | Stripe webhook | No (verified) | | GET | `/subscriptions` | User subscriptions | Yes | | POST | `/subscriptions/:id/cancel` | Cancel subscription | Yes | ### Agents (`/api/agents`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/` | List trading agents | Yes | | GET | `/:agentId` | Agent details | Yes | | GET | `/:agentId/performance` | Agent performance | Yes | | GET | `/:agentId/trades` | Agent trades | Yes | | POST | `/:agentId/subscribe` | Subscribe to agent | Yes | | DELETE | `/:agentId/unsubscribe` | Unsubscribe | Yes | #### Get Agent Performance ```http GET /api/agents/atlas/performance?period=30d Authorization: Bearer ``` **Response:** ```json { "agent": "atlas", "profile": "CONSERVADOR", "period": "30d", "metrics": { "totalReturn": 0.045, "monthlyReturn": 0.045, "winRate": 0.68, "profitFactor": 2.1, "sharpeRatio": 1.85, "maxDrawdown": 0.032, "totalTrades": 45, "avgHoldingTime": "4.5h" }, "equity": [...], "recentTrades": [...] } ``` ### Admin (`/api/admin`) | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/stats` | System statistics | Yes (Admin) | | GET | `/users` | List users | Yes (Admin) | | PATCH | `/users/:userId` | Update user | Yes (Admin) | | DELETE | `/users/:userId` | Delete user | Yes (Admin) | | GET | `/logs` | System logs | Yes (Admin) | ## WebSocket Events ### Connection ```javascript import io from 'socket.io-client'; const socket = io('http://localhost:3082', { auth: { token: 'your-jwt-token' } }); ``` ### Events from Server | Event | Data | Description | |-------|------|-------------| | `price_update` | `{symbol, price, timestamp}` | Real-time price | | `trade` | `{symbol, price, quantity, side}` | Market trade | | `orderbook_update` | `{symbol, bids, asks}` | Order book | | `signal` | `{symbol, signal, strength}` | ML signal | | `agent_trade` | `{agent, trade}` | Agent trade notification | | `notification` | `{message, type}` | User notification | ### Events to Server | Event | Data | Description | |-------|------|-------------| | `subscribe` | `{symbols: ['BTCUSDT']}` | Subscribe to symbols | | `unsubscribe` | `{symbols: ['BTCUSDT']}` | Unsubscribe | | `ping` | `{}` | Heartbeat | ## Error Responses Standard error format: ```json { "error": { "code": "INVALID_CREDENTIALS", "message": "Email or password is incorrect", "statusCode": 401, "timestamp": "2025-12-12T10:00:00Z" } } ``` ### Common Error Codes | Code | Status | Description | |------|--------|-------------| | `INVALID_CREDENTIALS` | 401 | Wrong email/password | | `UNAUTHORIZED` | 401 | Missing or invalid token | | `FORBIDDEN` | 403 | Insufficient permissions | | `NOT_FOUND` | 404 | Resource not found | | `VALIDATION_ERROR` | 422 | Invalid input data | | `RATE_LIMIT_EXCEEDED` | 429 | Too many requests | | `INTERNAL_ERROR` | 500 | Server error | | `SERVICE_UNAVAILABLE` | 503 | Service down | ## Rate Limiting - **General:** 100 requests/minute per IP - **Auth endpoints:** 5 requests/minute - **Trading endpoints:** 60 requests/minute - **ML endpoints:** 30 requests/minute Headers in response: ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1670832000 ``` ## Pagination List endpoints support pagination: ```http GET /api/trading/orders?page=1&limit=20&sortBy=createdAt&order=DESC ``` **Response:** ```json { "data": [...], "pagination": { "page": 1, "limit": 20, "total": 150, "totalPages": 8, "hasNext": true, "hasPrevious": false } } ``` ## Filtering Many endpoints support filtering: ```http GET /api/trading/orders?status=FILLED&symbol=BTCUSDT&startDate=2024-01-01 ``` ## CORS CORS enabled for: - `http://localhost:3080` (development) - `https://app.orbiquant.com` (production) ## SDK (Future) ```typescript import { OrbiQuantClient } from '@orbiquant/sdk'; const client = new OrbiQuantClient({ apiKey: 'your-api-key', baseUrl: 'http://localhost:3081/api' }); // Login await client.auth.login({ email, password }); // Get signal const signal = await client.ml.getSignal('BTCUSDT'); // Place order const order = await client.trading.createOrder({ symbol: 'BTCUSDT', side: 'BUY', type: 'MARKET', quantity: 0.01 }); // Chat with copilot const response = await client.llm.chat('¿Debo comprar BTC ahora?'); ``` ## Health Checks ```http GET /api/health ``` **Response:** ```json { "status": "healthy", "timestamp": "2025-12-12T10:00:00Z", "services": { "database": "healthy", "redis": "healthy", "mlEngine": "healthy", "llmAgent": "healthy", "tradingAgents": "degraded" }, "uptime": 86400 } ``` ## Additional Resources - [Architecture Documentation](./ARCHITECTURE.md) - [Security Guide](./SECURITY.md) - [WebSocket Documentation](./WEBSOCKET.md) - [Database Schema](../apps/database/ddl/)