From 81c966f945465c509e37331d7ea7dcc63eef35ea Mon Sep 17 00:00:00 2001 From: Adrian Flores Cortes Date: Mon, 26 Jan 2026 19:03:23 -0600 Subject: [PATCH] docs: Reduce API.md to overview referencing swagger.yml Reduced from 637 to 267 lines (58% reduction). Removed redundant endpoint documentation now in swagger.yml. API.md now serves as quick reference with links to: - swagger.yml (complete OpenAPI spec) - ENDPOINT-ROUTING.md (routing docs) Part of ST3.2 Documentation Purge. Co-Authored-By: Claude Opus 4.5 --- docs/API.md | 760 ++++++++++++++-------------------------------------- 1 file changed, 195 insertions(+), 565 deletions(-) diff --git a/docs/API.md b/docs/API.md index 26a718e..6c4e1ed 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,636 +1,266 @@ --- id: "API" -title: "API Documentation" +title: "API Documentation Overview" type: "Documentation" project: "trading-platform" -version: "1.0.0" -updated_date: "2026-01-04" +version: "2.0.0" +updated_date: "2026-01-26" --- -# API Documentation +# API Documentation Overview -## Base URL +> **📘 For complete API specification, see:** [swagger.yml](../apps/backend/swagger.yml) +> **📄 For routing documentation, see:** [ENDPOINT-ROUTING.md](../apps/backend/ENDPOINT-ROUTING.md) -**Development:** `http://localhost:3081/api` -**Production:** `https://api.trading.com/api` (future) +This document provides a high-level overview of the Trading Platform API. For detailed endpoint specifications, request/response schemas, and interactive API testing, refer to the OpenAPI specification in `swagger.yml`. -## Port Configuration +--- + +## Quick Reference + +### Base URLs + +| Environment | URL | +|-------------|-----| +| Development | `http://localhost:3080/api/v1` | +| Production | `https://api.trading.com/api/v1` (future) | + +### Service Ports | 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 | +| Backend API | 3080 | Main REST API + Swagger UI | +| Frontend | 3000 | React SPA | +| WebSocket | 3082 | Real-time data (Socket.io) | +| ML Engine | 3083 | ML predictions (FastAPI) | +| Data Service | 3084 | Market data aggregation | +| LLM Agent | 3085 | Trading copilot (FastAPI) | +| Trading Agents | 3086 | Automated trading (FastAPI) | +| Ollama WebUI | 3087 | LLM model management | + +--- ## Authentication -### JWT Authentication +All protected endpoints require 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 +### Request Header ```http -POST /api/auth/register -Content-Type: application/json - -{ - "email": "trader@example.com", - "password": "SecurePass123!", - "firstName": "John", - "lastName": "Doe" -} +Authorization: Bearer ``` -**Response:** +### Supported Methods + +| Method | Description | +|--------|-------------| +| **Email/Password** | Traditional login with email and password | +| **OAuth 2.0** | Google, Facebook, Apple, GitHub | +| **2FA (TOTP)** | Two-factor authentication optional | + +### Auth Endpoints + +- `POST /auth/register` - Create new account +- `POST /auth/login` - Login with credentials +- `POST /auth/logout` - End session +- `POST /auth/refresh` - Refresh access token +- `GET /auth/me` - Get current user + +**See:** [swagger.yml](../apps/backend/swagger.yml) for complete auth specification + +--- + +## API Modules + +The API is organized into the following modules: + +| Module | Base Route | Description | +|--------|------------|-------------| +| **Auth** | `/api/v1/auth` | Authentication, sessions, 2FA | +| **Users** | `/api/v1/users` | User profiles and management | +| **Education** | `/api/v1/education` | Courses, lessons, certificates | +| **Trading** | `/api/v1/trading` | Bots, signals, positions | +| **Investment** | `/api/v1/investment` | PAMM accounts, distributions | +| **Portfolio** | `/api/v1/portfolio` | Portfolio management | +| **Payments** | `/api/v1/payments` | Stripe integration, subscriptions | +| **ML** | `/api/v1/ml` | ML predictions and signals | +| **Agents** | `/api/v1/agents` | Trading agent management | +| **Notifications** | `/api/v1/notifications` | User notifications | +| **Admin** | `/api/v1/admin` | Administrative functions | + +**Total Endpoints:** 34+ documented in [swagger.yml](../apps/backend/swagger.yml) + +--- + +## Response Format + +### Success Response + ```json { - "user": { - "id": "uuid", - "email": "trader@example.com", - "firstName": "John", - "lastName": "Doe", - "role": "user" + "success": true, + "data": { + // Response data }, - "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", - "refreshToken": "refresh_token_here", - "expiresIn": 3600 + "message": "Success message (optional)" } ``` -#### 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: +### Error Response ```json { + "success": false, "error": { - "code": "INVALID_CREDENTIALS", - "message": "Email or password is incorrect", - "statusCode": 401, - "timestamp": "2025-12-12T10:00:00Z" + "message": "Error description", + "code": "ERROR_CODE", + "field": "fieldName" } } ``` -### Common Error Codes +### Common HTTP Status 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 | +| Code | Meaning | +|------|---------| +| 200 | Success | +| 201 | Created | +| 400 | Bad Request (validation error) | +| 401 | Unauthorized (missing/invalid token) | +| 403 | Forbidden (insufficient permissions) | +| 404 | Not Found | +| 429 | Rate Limit Exceeded | +| 500 | Internal Server Error | + +--- + +## Pagination + +List endpoints support pagination via query parameters: + +```http +GET /api/v1/module/resource?page=1&limit=20&sortBy=createdAt&sortOrder=desc +``` + +**Response metadata:** +```json +{ + "success": true, + "data": [...], + "meta": { + "page": 1, + "limit": 20, + "total": 100, + "totalPages": 5 + } +} +``` + +--- ## Rate Limiting -- **General:** 100 requests/minute per IP -- **Auth endpoints:** 5 requests/minute -- **Trading endpoints:** 60 requests/minute -- **ML endpoints:** 30 requests/minute +| Endpoint Type | Limit | +|---------------|-------| +| General | 100 requests/minute per IP | +| Auth | 5 requests/minute | +| Trading | 60 requests/minute | +| ML | 30 requests/minute | -Headers in response: +**Response headers:** ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1670832000 ``` -## Pagination +--- -List endpoints support pagination: +## WebSocket (Real-Time) -```http -GET /api/trading/orders?page=1&limit=20&sortBy=createdAt&order=DESC +**Connection:** `http://localhost:3082` + +```javascript +import io from 'socket.io-client'; + +const socket = io('http://localhost:3082', { + auth: { token: 'your-jwt-token' } +}); + +// Subscribe to price updates +socket.emit('subscribe', { symbols: ['BTCUSDT', 'ETHUSDT'] }); + +// Listen for updates +socket.on('price_update', (data) => { + console.log(data); // { symbol, price, timestamp } +}); ``` -**Response:** -```json -{ - "data": [...], - "pagination": { - "page": 1, - "limit": 20, - "total": 150, - "totalPages": 8, - "hasNext": true, - "hasPrevious": false - } -} -``` +**Events:** `price_update`, `trade`, `orderbook_update`, `signal`, `agent_trade`, `notification` -## Filtering +--- -Many endpoints support filtering: - -```http -GET /api/trading/orders?status=FILLED&symbol=BTCUSDT&startDate=2024-01-01 -``` - -## CORS +## CORS Configuration CORS enabled for: -- `http://localhost:3080` (development) -- `https://app.trading.com` (production) +- `http://localhost:3000` (development frontend) +- `https://app.trading.com` (production - future) -## SDK (Future) +--- -```typescript -import { Trading PlatformClient } from '@trading-platform/sdk'; - -const client = new Trading PlatformClient({ - 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 +## Health Check ```http -GET /api/health +GET /api/v1/health ``` **Response:** ```json { "status": "healthy", - "timestamp": "2025-12-12T10:00:00Z", + "timestamp": "2026-01-26T10:00:00Z", "services": { "database": "healthy", "redis": "healthy", - "mlEngine": "healthy", - "llmAgent": "healthy", - "tradingAgents": "degraded" - }, - "uptime": 86400 + "mlEngine": "healthy" + } } ``` +--- + +## API Versioning + +- Current version: **v1** +- Version is in URL: `/api/v1/...` +- Breaking changes will increment version number +- Old versions maintained for 6 months after deprecation + +--- + ## Additional Resources -- [Architecture Documentation](./ARCHITECTURE.md) -- [Security Guide](./SECURITY.md) -- [WebSocket Documentation](./WEBSOCKET.md) -- [Database Schema](../apps/database/ddl/) +| Resource | Location | +|----------|----------| +| **OpenAPI Specification** | [swagger.yml](../apps/backend/swagger.yml) | +| **Endpoint Routing** | [ENDPOINT-ROUTING.md](../apps/backend/ENDPOINT-ROUTING.md) | +| **Database Schema** | [apps/database/ddl/](../apps/database/ddl/) | +| **Security Guide** | [SECURITY.md](./90-transversal/security/SECURITY.md) | +| **Architecture** | [01-arquitectura/](./01-arquitectura/) | + +--- + +## Swagger UI (Interactive Documentation) + +**Local:** http://localhost:3080/api-docs + +The Swagger UI provides: +- ✅ Interactive API testing +- ✅ Request/response examples +- ✅ Schema validation +- ✅ Authentication testing +- ✅ "Try it out" functionality + +--- + +**Last Updated:** 2026-01-26 (ST3.2 - Documentation Purge)