--- id: "README" title: "Trading y Charts" type: "Documentation" project: "trading-platform" version: "1.0.0" updated_date: "2026-02-06" --- # OQI-003: Trading y Charts ## Resumen Ejecutivo La épica OQI-003 implementa la plataforma de trading con charts profesionales, indicadores técnicos, watchlists personalizables y sistema de paper trading para simulación sin riesgo. --- ## Metadata | Campo | Valor | |-------|-------| | **ID** | OQI-003 | | **Nombre** | Trading y Charts | | **Módulo** | trading | | **Fase** | Fase 1 - MVP | | **Prioridad** | P1 | | **Estado** | Pendiente | | **Story Points** | 55 SP | | **Sprint(s)** | Sprint 3-4 | --- ## Objetivo Proporcionar una plataforma de trading completa que permita a los usuarios: 1. Visualizar charts profesionales con múltiples timeframes 2. Aplicar indicadores técnicos para análisis 3. Crear y gestionar watchlists personalizadas 4. Practicar trading con paper trading (simulación) 5. Revisar historial de operaciones y métricas de rendimiento --- ## Alcance ### Incluido | Feature | Descripción | |---------|-------------| | Charts | Gráficos de velas con Lightweight Charts (TradingView clone) | | Timeframes | 1m, 5m, 15m, 1h, 4h, 1D, 1W | | Indicadores Técnicos | SMA, EMA, RSI, MACD, Bollinger Bands | | **ML Overlay** | Indicadores predictivos del modelo ML superpuestos en chart | | **Señales ML** | Visualización de señales de entrada/salida del modelo | | **AMD Zones** | Zonas de Acumulación/Manipulación/Distribución | | Watchlists | Listas personalizables de activos | | Paper Trading | Simulación de operaciones sin dinero real | | Historial | Registro completo de operaciones | | Métricas | Win rate, P&L, Sharpe ratio básico | | **Alertas ML** | Notificaciones cuando el modelo genera señales | ### ML Overlay Features | Indicador ML | Visualización | Fuente | |--------------|---------------|--------| | RangePredictor | Bandas de predicción (ΔHigh/ΔLow) | TradingAgent | | TPSLClassifier | Colores TP (verde) / SL (rojo) | TradingAgent | | AMDDetector | Zonas coloreadas (Acc/Manip/Dist) | TradingAgent | | SignalGenerator | Flechas de entrada (▲ compra, ▼ venta) | TradingAgent | | Confidence | Opacidad según confianza del modelo | TradingAgent | ### Excluido | Feature | Razón | Fase | |---------|-------|------| | Trading real | Requiere broker integration | Vía Agentes | | Order book | Complejidad | Backlog | | Depth charts | Nicho avanzado | Backlog | | Screener avanzado | Post-MVP | Fase 2 | --- ## Arquitectura ``` ┌─────────────────────────────────────────────────────────────────┐ │ FRONTEND │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Trading │ │ Watchlist │ │ Paper │ │ │ │ Charts │ │ Manager │ │ Trading │ │ │ │ + ML Overlay│ │ │ │ │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────┼────────────────┼────────────────┼─────────────────────┘ │ │ │ └────────────────┼────────────────┘ │ HTTPS / WebSocket ▼ ┌─────────────────────────────────────────────────────────────────┐ │ BACKEND API │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ TRADING CONTROLLER │ │ │ │ GET /trading/candles GET /trading/indicators │ │ │ │ POST /trading/orders GET /trading/watchlists │ │ │ │ GET /trading/positions GET /trading/history │ │ │ │ GET /trading/ml/overlay GET /trading/ml/signals │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │ │ Market │ │ Order │ │ Position │ │ Watchlist │ │ │ │ Service │ │ Service │ │ Service │ │ Service │ │ │ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ ML OVERLAY SERVICE │ │ │ │ - Fetch predictions from ML Engine │ │ │ │ - Transform to chart overlay format │ │ │ │ - Cache signals for performance │ │ │ └─────────────────────────────────────────────────────────┘ │ └────────┼──────────────┼──────────────┼──────────────┼───────────┘ │ │ │ │ ▼ ▼ ▼ ▼ ┌─────────────┐ ┌─────────────────────────┐ ┌─────────────────┐ │ Binance │ │ ML ENGINE │ │ PostgreSQL │ │ API │ │ (TradingAgent) │ │ trading schema │ │ │ │ - RangePredictor │ │ │ │ - Candles │ │ - TPSLClassifier │ │ - orders │ │ - Prices │ │ - AMDDetector │ │ - positions │ │ - Stream │ │ - SignalGenerator │ │ - watchlists │ └─────────────┘ └─────────────────────────┘ └─────────────────┘ ``` ### Flujo de ML Overlay ``` Usuario solicita chart XAUUSD 1H │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 1. Frontend: GET /trading/candles/XAUUSD?interval=1h │ │ 2. Frontend: GET /trading/ml/overlay/XAUUSD?interval=1h │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Backend: ML Overlay Service │ │ │ │ 1. Check Redis cache for recent predictions │ │ 2. If miss: Call ML Engine API │ │ - POST /predict {symbol, interval, candles} │ │ 3. Transform response to overlay format │ │ 4. Cache for 5 minutes │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Response: ML Overlay Data │ │ { │ │ "rangePrediction": { "high": [...], "low": [...] }, │ │ "tpslClassification": [{ "index": 50, "type": "tp" }], │ │ "amdZones": [{ "start": 10, "end": 25, "phase": "acc" }], │ │ "signals": [{ "index": 50, "type": "buy", "conf": 0.85 }] │ │ } │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Frontend: Render Chart with Overlay │ │ │ │ - Draw candles (standard) │ │ - Draw range bands (prediction envelope) │ │ - Color background zones (AMD phases) │ │ - Draw signal markers (arrows with confidence opacity) │ └─────────────────────────────────────────────────────────────────┘ ``` --- ## Flujos Principales ### 1. Visualización de Chart ``` Usuario Frontend Backend Binance │ │ │ │ │─── Selecciona BTCUSDT ──▶│ │ │ │ │─── GET /trading/candles ─▶│ │ │ │ │─── GET klines ────────▶│ │ │ │◀── OHLCV data ─────────│ │ │◀── Candles + indicators ─│ │ │◀── Render chart ─────────│ │ │ │ │ │ │ │ │─── WS connect ───────────▶│ │ │◀── Real-time updates ────│◀── Stream updates ───────│◀── WebSocket ─────────│ ``` ### 2. Paper Trading Order ``` Usuario Frontend Backend DB │ │ │ │ │─── Click BUY BTCUSDT ───▶│ │ │ │ │─── POST /trading/orders ─▶│ │ │ │ │─── Validate balance ──▶│ │ │ │◀── OK ─────────────────│ │ │ │─── Get current price ──│ │ │ │─── INSERT order ───────▶│ │ │ │─── UPDATE positions ───▶│ │ │◀── Order executed ───────│ │ │◀── Success notification ─│ │ │ ``` ### 3. Gestión de Watchlist ``` Usuario Frontend Backend DB │ │ │ │ │─── Add to watchlist ────▶│ │ │ │ │─── POST /watchlists/:id/symbols ─▶│ │ │ │ │─── INSERT symbol ─────▶│ │ │◀── Updated watchlist ────│ │ │◀── Symbol added ─────────│ │ │ ``` --- ## Modelo de Datos ### Tablas Principales ```sql -- Watchlists del usuario CREATE TABLE trading.watchlists ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES public.users(id), name VARCHAR(100) NOT NULL, description TEXT, is_default BOOLEAN DEFAULT FALSE, sort_order INTEGER DEFAULT 0, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Símbolos en watchlists CREATE TABLE trading.watchlist_symbols ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), watchlist_id UUID REFERENCES trading.watchlists(id) ON DELETE CASCADE, symbol VARCHAR(20) NOT NULL, notes TEXT, alert_price_above DECIMAL(20,8), alert_price_below DECIMAL(20,8), sort_order INTEGER DEFAULT 0, added_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(watchlist_id, symbol) ); -- Órdenes de paper trading CREATE TABLE trading.paper_orders ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES public.users(id), symbol VARCHAR(20) NOT NULL, side order_side_enum NOT NULL, -- buy | sell type order_type_enum NOT NULL, -- market | limit | stop_limit status order_status_enum DEFAULT 'pending', quantity DECIMAL(20,8) NOT NULL, price DECIMAL(20,8), -- null for market orders stop_price DECIMAL(20,8), filled_quantity DECIMAL(20,8) DEFAULT 0, filled_price DECIMAL(20,8), take_profit DECIMAL(20,8), stop_loss DECIMAL(20,8), created_at TIMESTAMPTZ DEFAULT NOW(), filled_at TIMESTAMPTZ, cancelled_at TIMESTAMPTZ ); -- Posiciones abiertas CREATE TABLE trading.paper_positions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES public.users(id), symbol VARCHAR(20) NOT NULL, side position_side_enum NOT NULL, -- long | short quantity DECIMAL(20,8) NOT NULL, entry_price DECIMAL(20,8) NOT NULL, current_price DECIMAL(20,8), unrealized_pnl DECIMAL(20,8) DEFAULT 0, realized_pnl DECIMAL(20,8) DEFAULT 0, take_profit DECIMAL(20,8), stop_loss DECIMAL(20,8), opened_at TIMESTAMPTZ DEFAULT NOW(), closed_at TIMESTAMPTZ, UNIQUE(user_id, symbol) -- Una posición por símbolo ); -- Balance virtual de paper trading CREATE TABLE trading.paper_balances ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES public.users(id) UNIQUE, balance DECIMAL(20,8) DEFAULT 10000.00, -- $10,000 inicial equity DECIMAL(20,8) DEFAULT 10000.00, margin_used DECIMAL(20,8) DEFAULT 0, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Historial de trades cerrados CREATE TABLE trading.paper_trades ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID REFERENCES public.users(id), symbol VARCHAR(20) NOT NULL, side position_side_enum NOT NULL, entry_price DECIMAL(20,8) NOT NULL, exit_price DECIMAL(20,8) NOT NULL, quantity DECIMAL(20,8) NOT NULL, pnl DECIMAL(20,8) NOT NULL, pnl_percent DECIMAL(10,4) NOT NULL, duration_minutes INTEGER, opened_at TIMESTAMPTZ NOT NULL, closed_at TIMESTAMPTZ NOT NULL ); ``` --- ## API Endpoints ### Market Data | Method | Endpoint | Descripción | |--------|----------|-------------| | GET | `/trading/symbols` | Lista de símbolos disponibles | | GET | `/trading/candles/:symbol` | Velas OHLCV | | GET | `/trading/ticker/:symbol` | Precio actual | | GET | `/trading/indicators/:symbol` | Indicadores técnicos | | WS | `/trading/stream/:symbol` | Stream de precios | ### Watchlists | Method | Endpoint | Descripción | |--------|----------|-------------| | GET | `/trading/watchlists` | Listar watchlists | | POST | `/trading/watchlists` | Crear watchlist | | PATCH | `/trading/watchlists/:id` | Actualizar watchlist | | DELETE | `/trading/watchlists/:id` | Eliminar watchlist | | POST | `/trading/watchlists/:id/symbols` | Agregar símbolo | | DELETE | `/trading/watchlists/:id/symbols/:symbol` | Quitar símbolo | ### Paper Trading | Method | Endpoint | Descripción | |--------|----------|-------------| | GET | `/trading/paper/balance` | Balance virtual | | POST | `/trading/paper/balance/reset` | Reiniciar a $10,000 | | GET | `/trading/paper/positions` | Posiciones abiertas | | POST | `/trading/paper/orders` | Crear orden | | DELETE | `/trading/paper/orders/:id` | Cancelar orden | | GET | `/trading/paper/orders` | Historial de órdenes | | GET | `/trading/paper/trades` | Historial de trades | | GET | `/trading/paper/stats` | Estadísticas de rendimiento | ### ML Overlay (Integración con TradingAgent) | Method | Endpoint | Descripción | |--------|----------|-------------| | GET | `/trading/ml/overlay/:symbol` | Overlay completo para chart | | GET | `/trading/ml/signals/:symbol` | Señales de entrada/salida | | GET | `/trading/ml/prediction/:symbol` | Predicción de rango | | GET | `/trading/ml/amd/:symbol` | Zonas AMD detectadas | | GET | `/trading/ml/confidence/:symbol` | Confianza del modelo | | WS | `/trading/ml/stream/:symbol` | Stream de predicciones | #### Ejemplo Response ML Overlay ```json { "symbol": "XAUUSD", "interval": "1h", "timestamp": "2025-12-05T12:00:00Z", "overlay": { "rangePrediction": { "deltaHigh": [0.15, 0.18, 0.22, ...], "deltaLow": [-0.12, -0.10, -0.14, ...] }, "signals": [ { "index": 95, "type": "buy", "confidence": 0.85, "entry": 2045.50, "tp": 2065.00, "sl": 2035.00 } ], "amdZones": [ { "start": 50, "end": 65, "phase": "accumulation" }, { "start": 66, "end": 78, "phase": "manipulation" }, { "start": 79, "end": 95, "phase": "distribution" } ], "tpslProbability": { "tp": 0.72, "sl": 0.28 }, "modelConfidence": 0.85 } } ``` --- ## Indicadores Técnicos ### Indicadores Tradicionales | Indicador | Parámetros | Descripción | |-----------|------------|-------------| | SMA | period: 5, 10, 20, 50, 200 | Simple Moving Average | | EMA | period: 5, 10, 20, 50, 200 | Exponential Moving Average | | RSI | period: 14 | Relative Strength Index (0-100) | | MACD | fast: 12, slow: 26, signal: 9 | Moving Average Convergence Divergence | | BB | period: 20, stdDev: 2 | Bollinger Bands | | ATR | period: 14 | Average True Range | | Volume | - | Barras de volumen | ### Indicadores ML (TradingAgent) | Indicador | Visualización | Descripción | |-----------|---------------|-------------| | **ML Range** | Bandas semi-transparentes | Predicción de rango ΔHigh/ΔLow | | **ML Signal** | Flechas ▲/▼ con opacidad | Señales de entrada del modelo | | **AMD Zone** | Background coloreado | Fases de mercado detectadas | | **TP/SL Prob** | Indicador lateral | Probabilidad de TP vs SL | | **Confidence** | Barra inferior | Confianza del modelo 0-100% | ### Colores AMD | Fase | Color | Descripción | |------|-------|-------------| | Accumulation | Verde suave (#4CAF5020) | Acumulación institucional | | Manipulation | Amarillo (#FFC10720) | Manipulación de mercado | | Distribution | Rojo suave (#F4433620) | Distribución de posiciones | --- ## Timeframes Soportados | Timeframe | Label | Candles por defecto | |-----------|-------|---------------------| | 1m | 1 minuto | 500 | | 5m | 5 minutos | 300 | | 15m | 15 minutos | 200 | | 1h | 1 hora | 168 | | 4h | 4 horas | 100 | | 1D | 1 día | 100 | | 1W | 1 semana | 52 | --- ## Métricas de Paper Trading ```json { "stats": { "totalTrades": 45, "winningTrades": 28, "losingTrades": 17, "winRate": 62.22, "totalPnl": 2450.50, "totalPnlPercent": 24.51, "avgWin": 150.25, "avgLoss": -85.30, "profitFactor": 2.45, "maxDrawdown": -8.5, "sharpeRatio": 1.85, "avgTradeDuration": "4h 23m" } } ``` --- ## Seguridad ### Rate Limiting | Endpoint | Límite | Ventana | |----------|--------|---------| | `/trading/candles` | 30 | 1 min | | `/trading/stream` | 5 conexiones | - | | `/trading/paper/orders` | 20 | 1 min | | General API | 100 | 1 min | ### Validaciones - Balance suficiente para órdenes - Símbolos válidos de la lista soportada - Límites de posición por símbolo - Cantidad mínima por orden --- ## Entregables | Entregable | Ruta | Estado | |------------|------|--------| | Schema DB | `apps/database/schemas/03_trading_schema.sql` | ✅ | | Market Service | `apps/backend/src/modules/trading/services/market.service.ts` | Pendiente | | Order Service | `apps/backend/src/modules/trading/services/order.service.ts` | Pendiente | | Watchlist Service | `apps/backend/src/modules/trading/services/watchlist.service.ts` | Pendiente | | Trading Controller | `apps/backend/src/modules/trading/controllers/trading.controller.ts` | Pendiente | | Trading Page | `apps/frontend/src/modules/trading/pages/Trading.tsx` | Pendiente | | Chart Component | `apps/frontend/src/modules/trading/components/TradingChart.tsx` | Pendiente | | Order Panel | `apps/frontend/src/modules/trading/components/OrderPanel.tsx` | Pendiente | | Watchlist Panel | `apps/frontend/src/modules/trading/components/WatchlistPanel.tsx` | Pendiente | --- ## Schemas DDL Asignados Este modulo es owner de los siguientes schemas DDL: | Schema | Tablas | Descripcion | |--------|--------|-------------| | **trading** | 13 | Symbols, watchlists, bots, orders, positions, trades, signals, metrics, paper_balances, price_alerts, drawing_tools, drawing_templates | | **market_data** | 4 | Tickers, ohlcv_5m, ohlcv_15m, staging (datos de mercado ingestados) | **Total tablas:** 17 (13 trading + 4 market_data) **Nota:** market_data asignado a OQI-003 por TASK-2026-02-06 F1.7 (schema huerfano) --- ## Dependencias ### Esta épica depende de: | Épica/Módulo | Estado | Bloqueante | Razón | |--------------|--------|------------|-------| | OQI-001 Auth | ✅ Completado | Sí | Autenticación de usuarios | | OQI-006 ML Signals | Pendiente | Parcial | ML overlay requiere predicciones | ### Esta épica bloquea: | Épica/Módulo | Razón | |--------------|-------| | OQI-007 LLM Agent | El copiloto usa los charts para análisis | | OQI-008 Portfolio Manager | Dashboard muestra charts de rendimiento | ### Integración con TradingAgent Esta épica integra el motor ML existente ubicado en: `[LEGACY: apps/ml-engine - migrado desde TradingAgent]/` Ver documento de integración: `docs/01-arquitectura/INTEGRACION-TRADINGAGENT.md` --- ## Riesgos | Riesgo | Probabilidad | Impacto | Mitigación | |--------|--------------|---------|------------| | Rate limits Binance | Alta | Medio | Caché de datos, WebSocket | | Latencia en charts | Media | Alto | CDN para assets, lazy loading | | Cálculo de indicadores lento | Baja | Medio | Web Workers, caché | --- ## Referencias - [_MAP de la Épica](./_MAP.md) - [Requerimientos](./requerimientos/) - [Especificaciones](./especificaciones/) - [Historias de Usuario](./historias-usuario/) - [Lightweight Charts Docs](https://tradingview.github.io/lightweight-charts/)