Compare commits

...

3 Commits

Author SHA1 Message Date
Adrian Flores Cortes
bae221db5f docs: Move SECURITY.md to transversal location
Moved docs/SECURITY.md to docs/90-transversal/security/SECURITY.md
to organize security documentation with other transversal docs.

Part of ST3.2 Documentation Purge.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 19:03:25 -06:00
Adrian Flores Cortes
81c966f945 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 <noreply@anthropic.com>
2026-01-26 19:03:23 -06:00
Adrian Flores Cortes
e6cd88b6ce docs: Remove redundant ARCHITECTURE.md
Content already covered by:
- docs/00-vision-general/STACK-TECNOLOGICO.md (tech stack)
- docs/00-vision-general/ARQUITECTURA-GENERAL.md (high-level view)
- docs/01-arquitectura/ (specialized architectures)

Part of ST3.2 Documentation Purge.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 19:00:58 -06:00
3 changed files with 195 additions and 1141 deletions

View File

@ -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 <jwt_token>
```
### 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 <jwt_access_token>
```
**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 <token>
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 <token>
```
**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 <token>
```
**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 <token>
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 <token>
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 <token>
```
**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)

View File

@ -1,576 +0,0 @@
---
id: "ARCHITECTURE"
title: "Architecture"
type: "Documentation"
project: "trading-platform"
version: "1.0.0"
updated_date: "2026-01-04"
---
# Architecture
## Overview
**Trading Platform** es una plataforma integral de gestión de inversiones asistida por inteligencia artificial que combina money management automatizado, educación en trading, visualización de mercados y un sistema SaaS completo.
La arquitectura es de microservicios heterogéneos con servicios Node.js (backend/frontend) y Python (ML, LLM, trading agents, data) comunicándose vía REST APIs y WebSockets.
## Tech Stack
### Backend & Frontend
- **Backend API:** Express.js 5 + TypeScript + Node.js 20
- **Frontend:** React 18 + TypeScript + Tailwind CSS + Vite
- **WebSocket:** Socket.io (real-time charts, notifications)
- **Database:** PostgreSQL 16 (trading_platform)
- **Cache:** Redis 7
- **Auth:** JWT + Passport.js (local, OAuth2)
### AI/ML Services (Python)
- **ML Engine:** FastAPI + PyTorch + XGBoost + scikit-learn
- **LLM Agent:** FastAPI + Ollama (Llama 3.1, Qwen 2.5)
- **Trading Agents:** FastAPI + CCXT (exchange integration)
- **Data Service:** FastAPI + pandas + numpy
### External Services
- **Payments:** Stripe
- **Exchanges:** Binance, Bybit, OKX (via CCXT)
- **LLM Models:** Ollama (local deployment)
## Module Structure
```
trading-platform/
├── apps/
│ ├── backend/ # Express.js API (TypeScript)
│ │ └── src/
│ │ ├── modules/ # Feature modules
│ │ │ ├── auth/ # Authentication (JWT, OAuth2)
│ │ │ ├── users/ # User management
│ │ │ ├── trading/ # Trading operations
│ │ │ ├── portfolio/ # Portfolio management
│ │ │ ├── investment/ # PAMM products
│ │ │ ├── education/ # Courses & gamification
│ │ │ ├── payments/ # Stripe integration
│ │ │ ├── ml/ # ML integration
│ │ │ ├── llm/ # LLM integration
│ │ │ ├── agents/ # Trading agents management
│ │ │ └── admin/ # Admin dashboard
│ │ ├── shared/ # Shared utilities
│ │ ├── config/ # Configuration
│ │ └── core/ # Core services
│ │
│ ├── frontend/ # React SPA
│ │ └── src/
│ │ ├── modules/ # Feature modules
│ │ │ ├── auth/ # Login, register
│ │ │ ├── dashboard/ # Main dashboard
│ │ │ ├── trading/ # Trading interface
│ │ │ ├── charts/ # TradingView-like charts
│ │ │ ├── portfolio/ # Portfolio view
│ │ │ ├── education/ # Courses
│ │ │ ├── agents/ # Agent monitoring
│ │ │ └── admin/ # Admin panel
│ │ ├── shared/ # Shared components
│ │ └── lib/ # Utilities
│ │
│ ├── ml-engine/ # Python ML Service
│ │ └── src/
│ │ ├── models/ # ML models
│ │ │ ├── amd_detector/ # Smart Money detector (CNN+LSTM+XGBoost)
│ │ │ ├── range_predictor/ # Price range prediction
│ │ │ └── signal_generator/ # Trading signals
│ │ ├── pipelines/ # Training pipelines
│ │ ├── backtesting/ # Backtesting engine
│ │ ├── features/ # Feature engineering
│ │ └── api/ # FastAPI endpoints
│ │
│ ├── llm-agent/ # Python LLM Service (Copilot)
│ │ └── src/
│ │ ├── core/ # LLM core (Ollama client)
│ │ ├── tools/ # 12 trading tools
│ │ │ ├── market_analysis.py
│ │ │ ├── technical_indicators.py
│ │ │ ├── sentiment_analysis.py
│ │ │ └── ...
│ │ ├── prompts/ # System prompts
│ │ └── api/ # FastAPI endpoints
│ │
│ ├── trading-agents/ # Python Trading Agents (Atlas, Orion, Nova)
│ │ └── src/
│ │ ├── agents/ # Agent implementations
│ │ │ ├── atlas/ # Conservador (3-5% mensual)
│ │ │ ├── orion/ # Moderado (5-10% mensual)
│ │ │ └── nova/ # Agresivo (10%+ mensual)
│ │ ├── strategies/ # Trading strategies
│ │ │ ├── mean_reversion.py
│ │ │ ├── trend_following.py
│ │ │ ├── breakout.py
│ │ │ └── ...
│ │ ├── exchange/ # Exchange integration (CCXT)
│ │ └── risk/ # Risk management
│ │
│ ├── data-service/ # Python Data Service (⚠️ 20% completo)
│ │ └── src/
│ │ ├── providers/ # Data providers
│ │ │ ├── binance.py
│ │ │ ├── yahoo_finance.py
│ │ │ └── ...
│ │ ├── aggregation/ # Data aggregation
│ │ └── api/ # FastAPI endpoints
│ │
│ └── database/ # PostgreSQL
│ └── ddl/
│ └── schemas/ # 8 schemas, 98 tables
│ ├── auth/
│ ├── trading/
│ ├── investment/
│ ├── financial/
│ ├── education/
│ ├── llm/
│ ├── ml/
│ └── audit/
├── packages/ # Shared code
│ ├── sdk-typescript/ # SDK for Node.js
│ ├── sdk-python/ # SDK for Python services
│ ├── config/ # Shared configuration
│ └── types/ # Shared types
├── docker/ # Docker configurations
├── docs/ # Documentation
└── orchestration/ # NEXUS agent system
```
## Database Schemas (8 schemas, 98 tables)
| Schema | Purpose | Tables | Key Entities |
|--------|---------|--------|--------------|
| **auth** | Authentication & Users | 10 | users, sessions, oauth_accounts, roles |
| **trading** | Trading Operations | 10 | orders, positions, symbols, trades |
| **investment** | PAMM Products | 7 | pamm_accounts, investors, performance |
| **financial** | Payments & Wallets | 10 | wallets, transactions, stripe_payments |
| **education** | Courses & Gamification | 14 | courses, lessons, quizzes, achievements |
| **llm** | LLM Conversations | 5 | conversations, messages, tools_usage |
| **ml** | ML Models & Predictions | 5 | models, predictions, backtests |
| **audit** | Logs & Auditing | 7 | api_logs, user_activity, system_events |
## Data Flow Architecture
```
┌──────────────┐
│ Frontend │ (React SPA - Port 3080)
│ (Browser) │
└──────┬───────┘
│ HTTP/WebSocket
┌─────────────────────────────────────────────┐
│ Backend API (Express.js) │
│ Port 3081 │
│ ┌─────────────────────────────────────┐ │
│ │ REST Controllers │ │
│ └──────┬─────────────────────┬────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Services │ │ Services │ │
│ │ (Auth, │ │ (Trading, │ │
│ │ Users) │ │ Payments) │ │
│ └─────┬───────┘ └──────┬──────┘ │
│ │ │ │
└────────┼─────────────────────┼──────────────┘
│ │
│ ┌─────────────────┼──────────────┐
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────────┐ ┌──────────────┐ ┌──────────────┐
│ PostgreSQL │ │ ML Engine │ │ LLM Agent │
│ (Database) │ │ (Python) │ │ (Python) │
│ │ │ Port 3083 │ │ Port 3085 │
└─────────────────┘ └──────┬───────┘ └──────┬───────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Data Service │ │ Ollama │
│ (Python) │ │ WebUI │
│ Port 3084 │ │ Port 3087 │
└──────────────┘ └──────────────┘
```
### Service Communication
```
Frontend (3080)
↓ HTTP/WS
Backend API (3081)
↓ HTTP
├─→ ML Engine (3083) [Price predictions, AMD detection]
├─→ LLM Agent (3085) [Trading copilot, analysis]
├─→ Trading Agents (3086) [Automated trading]
└─→ Data Service (3084) [Market data]
Trading Agents (3086)
↓ CCXT
└─→ Exchanges (Binance, Bybit, OKX)
LLM Agent (3085)
↓ HTTP
└─→ Ollama (8000) [Local LLM inference]
```
### Real-time Data Flow
```
Exchange WebSocket (Binance)
Data Service (3084)
↓ Process & Normalize
Backend API (3081)
↓ WebSocket
Frontend (3080)
↓ Render
TradingView-like Charts
```
## Key Design Decisions
### 1. Microservices Architecture (Heterogeneous)
**Decision:** Separar servicios por lenguaje según especialización.
**Rationale:**
- Node.js para API y web (mejor I/O async)
- Python para ML/AI (ecosistema superior: PyTorch, scikit-learn, CCXT)
- Escalabilidad independiente por servicio
- Equipos especializados por stack
**Trade-offs:**
- Mayor complejidad operacional
- Necesita orquestación (Docker Compose)
- Múltiples runtimes (Node.js + Python)
### 2. Multi-Agent Trading System (Atlas, Orion, Nova)
**Decision:** 3 agentes con perfiles de riesgo diferenciados.
**Rationale:**
- Diversificación de estrategias
- Atractivo para diferentes tipos de inversionistas
- Competencia interna mejora algoritmos
**Profiles:**
- **Atlas (Conservador):** Target 3-5% mensual, max drawdown 5%
- **Orion (Moderado):** Target 5-10% mensual, max drawdown 10%
- **Nova (Agresivo):** Target 10%+ mensual, max drawdown 20%
### 3. Ensemble ML Models (CNN + LSTM + XGBoost)
**Decision:** Combinar múltiples modelos para detección AMD (Smart Money).
**Rationale:**
- CNN detecta patrones visuales en charts
- LSTM captura series temporales
- XGBoost para features tabulares
- Ensemble reduce overfitting
**Accuracy:** ~75% en backtesting (2020-2024)
### 4. Local LLM with Ollama
**Decision:** Usar Ollama para deployment local de LLMs (Llama 3.1, Qwen 2.5).
**Rationale:**
- Privacidad (no enviar datos a APIs externas)
- Costos predecibles (no pagar por token)
- Latencia baja
- Control total sobre modelos
**Trade-off:** Requiere GPU para inference rápida
### 5. PAMM (Percentage Allocation Management Module)
**Decision:** Implementar sistema PAMM para inversión colectiva.
**Rationale:**
- Permite a usuarios sin conocimiento invertir con los agentes
- Comisiones por performance (incentiva buenos resultados)
- Escalabilidad del modelo de negocio
**Status:** 60% implementado
### 6. Gamified Education Platform
**Decision:** Gamificar cursos de trading con puntos, logros y rankings.
**Rationale:**
- Aumenta engagement
- Acelera aprendizaje
- Atrae usuarios jóvenes
- Diferenciador vs competencia
### 7. PostgreSQL with Schema-based Multi-tenancy
**Decision:** Usar schemas PostgreSQL para separación lógica.
**Rationale:**
- Aislamiento claro por dominio
- Facilita migraciones por schema
- Mejor organización que tablas planas
- RLS (Row-Level Security) para multi-tenancy futuro
## Dependencies
### Critical External Dependencies
| Dependency | Purpose | Criticality | Replacement |
|------------|---------|-------------|-------------|
| **PostgreSQL 16** | Database | CRITICAL | MySQL, MongoDB |
| **Redis 7** | Caching, sessions | HIGH | Memcached |
| **Stripe** | Payments | CRITICAL | PayPal, Razorpay |
| **CCXT** | Exchange APIs | CRITICAL | Custom integration |
| **Ollama** | Local LLM | HIGH | OpenAI API, Claude |
| **Binance API** | Market data | CRITICAL | Yahoo Finance, Alpha Vantage |
### Internal Service Dependencies
```
Backend API depends on:
├─ PostgreSQL (database)
├─ Redis (cache)
├─ ML Engine (predictions)
├─ LLM Agent (copilot)
└─ Trading Agents (automated trading)
ML Engine depends on:
├─ PostgreSQL (model storage)
└─ Data Service (market data)
LLM Agent depends on:
├─ Ollama (LLM inference)
└─ Backend API (user context)
Trading Agents depend on:
├─ PostgreSQL (orders, positions)
├─ ML Engine (signals)
└─ Exchanges (CCXT)
```
## Security Considerations
Ver documentación completa: [SECURITY.md](./SECURITY.md)
**Highlights:**
- JWT authentication con refresh tokens
- OAuth2 (Google, Facebook, Apple, GitHub)
- 2FA con TOTP (Speakeasy)
- API rate limiting (express-rate-limit)
- Helmet.js para headers de seguridad
- Password hashing con bcrypt
- Input validation con Zod
- SQL injection protection (parameterized queries)
- CORS configurado por entorno
- Stripe webhooks con signature verification
- API keys para servicios internos
## Performance Optimizations
### Backend
- Redis caching para queries frecuentes
- Connection pooling (PostgreSQL)
- Compression middleware
- Response pagination
- WebSocket para real-time (evita polling)
### ML Engine
- Model caching (evita reload)
- Batch predictions
- Feature pre-computation
- GPU acceleration (PyTorch CUDA)
### Frontend
- Code splitting (React lazy)
- Image optimization
- Service Worker (PWA)
- Debouncing en inputs
- Virtual scrolling para listas largas
### Database
- Indexes en columnas frecuentes
- Partitioning en tablas grandes
- EXPLAIN ANALYZE para optimización
- Connection pooling
## Deployment Strategy
**Current:** Development environment con Docker Compose
**Puertos:**
- Frontend: 3080
- Backend: 3081
- WebSocket: 3082
- ML Engine: 3083
- Data Service: 3084
- LLM Agent: 3085
- Trading Agents: 3086
- Ollama WebUI: 3087
**Future Production:**
- Kubernetes para orquestación
- Load balancer (Nginx/Traefik)
- Auto-scaling por servicio
- Multi-region deployment
## Monitoring & Observability
**Implemented:**
- Winston logging (Backend)
- Python logging (ML services)
- Health check endpoints
**Planned:**
- Prometheus + Grafana
- Sentry error tracking
- Datadog APM
- Custom dashboards por agente de trading
## ML Models Overview
### 1. AMD Detector (Accumulation-Manipulation-Distribution)
**Purpose:** Detectar fases de Smart Money en el mercado
**Architecture:**
- CNN: Detecta patrones en candlestick charts (imágenes)
- LSTM: Series temporales de precio/volumen
- XGBoost: Features técnicos (RSI, MACD, etc.)
- Ensemble: Voting classifier
**Input:**
- Historical OHLCV (200 candles)
- Technical indicators (20+)
- Volume profile
**Output:**
- Phase: Accumulation | Manipulation | Distribution | Re-accumulation
- Confidence: 0.0 - 1.0
**Training:** Supervised learning con datos etiquetados manualmente (2020-2024)
### 2. Range Predictor
**Purpose:** Predecir rango de precio futuro (soporte/resistencia)
**Algorithm:** XGBoost Regressor
**Features:**
- Fibonacci levels
- Previous support/resistance
- Volume at price
- Market structure
**Output:**
- Support level (precio)
- Resistance level (precio)
- Probability distribution
### 3. Signal Generator
**Purpose:** Generar señales de compra/venta
**Architecture:** Neural Network + Technical Analysis
**Inputs:**
- AMD phase
- Predicted range
- Technical indicators
- Sentiment analysis
**Output:**
- Signal: BUY | SELL | HOLD
- Strength: 0-100
- Entry/Stop/Target prices
## Trading Agents Strategies
### Atlas (Conservador)
**Strategies:**
- Mean Reversion en rangos
- Grid Trading en lateralización
- High probability setups only
**Risk Management:**
- Max 2% por trade
- Stop loss estricto
- Daily drawdown limit: 1%
### Orion (Moderado)
**Strategies:**
- Trend Following
- Breakout trading
- Swing trading
**Risk Management:**
- Max 3% por trade
- Trailing stops
- Weekly drawdown limit: 5%
### Nova (Agresivo)
**Strategies:**
- Momentum scalping
- High frequency entries
- Leverage (2x-5x)
**Risk Management:**
- Max 5% por trade
- Wide stops
- Monthly drawdown limit: 15%
## LLM Agent (Copilot) Tools
El copiloto tiene 12 herramientas especializadas:
1. **market_analysis** - Análisis técnico completo
2. **technical_indicators** - Cálculo de indicadores
3. **sentiment_analysis** - Sentiment de noticias/social
4. **price_prediction** - Predicciones ML
5. **risk_calculator** - Cálculo de riesgo/recompensa
6. **portfolio_optimizer** - Optimización de portafolio
7. **backtest_strategy** - Backtesting de estrategias
8. **news_fetcher** - Noticias relevantes
9. **correlation_matrix** - Correlación entre activos
10. **volatility_analyzer** - Análisis de volatilidad
11. **order_book_analyzer** - Análisis de order book
12. **whale_tracker** - Tracking de movimientos grandes
## Future Improvements
### Short-term (Q1 2025)
- [ ] Completar data-service (actualmente 20%)
- [ ] Implementar tests unitarios (Jest, Pytest)
- [ ] Agregar retry/circuit breaker entre servicios
- [ ] Documentar APIs con OpenAPI/Swagger
### Medium-term (Q2-Q3 2025)
- [ ] Implementar KYC/AML compliance
- [ ] Agregar más exchanges (Kraken, Coinbase)
- [ ] Mobile app (React Native)
- [ ] Notificaciones push
- [ ] Sistema de referidos
### Long-term (Q4 2025+)
- [ ] Copy trading entre usuarios
- [ ] Social trading features
- [ ] Marketplace de estrategias
- [ ] API pública para terceros
- [ ] White-label solution
## References
- [API Documentation](./API.md)
- [Security Guide](./SECURITY.md)
- [Services Overview](../SERVICES.md)
- [Database Schema](../apps/database/ddl/)
- [ML Models Documentation](../apps/ml-engine/docs/)
- [Trading Agents Documentation](../apps/trading-agents/docs/)