- FASE-0: Diagnostic audit of 500+ files, 33 findings cataloged (7P0/8P1/12P2/6P3) - FASE-1: Resolved 7 P0 critical conflicts (ports, paths, dedup OQI-010/ADR-002, orphan schemas) - FASE-2: Resolved 8 P1 issues (traces, README/CLAUDE.md, DEPENDENCY-GRAPH v2.0, DDL drift, stack versions, DoR/DoD) - FASE-3: Resolved 12 P2 issues (archived tasks indexed, RNFs created, OQI-010 US/RF/ET, AGENTS v2.0) - FASE-4: Purged 3 obsolete docs to _archive/, fixed MODELO-NEGOCIO.md broken ref - FASE-5: Cross-layer validation (DDL→OQI 66%, OQI→BE 72%, BE→FE 78%, Inventories 95%) - FASE-6: INFORME-FINAL, SA-INDEX (18 subagents), METADATA COMPLETED 27/33 findings resolved (82%), 6 P3 deferred to backlog. 18 new files created, 40+ modified, 4 archived. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
418 lines
12 KiB
Markdown
418 lines
12 KiB
Markdown
---
|
|
id: "ADR-002-MVP-OPERATIVO-TRADING"
|
|
title: "MVP Operativo Trading - Arquitectura e Implementación"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# ADR-002: MVP Operativo Trading - Arquitectura e Implementación
|
|
|
|
**Estado:** Propuesto
|
|
**Fecha:** 2025-12-12
|
|
**Autor:** Architecture-Analyst
|
|
**Contexto:** Gate Phase V - Validación Pre-Implementación
|
|
|
|
---
|
|
|
|
## Resumen Ejecutivo
|
|
|
|
Este ADR documenta la arquitectura y plan de implementación para el MVP operativo de trading que incluye:
|
|
- Modelos ML funcionando con predicciones en tiempo real
|
|
- Visualización de predicciones para admin
|
|
- Integración con Polygon/Massive para datos
|
|
- Ejecución directa de operaciones en MT4
|
|
- Gestión de cuenta 200-1000 USD
|
|
- Agente LLM con capacidades de trading
|
|
|
|
---
|
|
|
|
## Contexto del Problema
|
|
|
|
El sistema actual tiene el ML Engine en un 70% de implementación con modelos entrenados (RangePredictor 85.9%, TPSLClassifier 0.94 AUC), pero carece de:
|
|
1. Pipeline completo de datos en tiempo real
|
|
2. Capacidad de ejecución en broker real (MT4)
|
|
3. Dashboard de administración para monitoreo
|
|
4. Integración del agente LLM para asistencia/ejecución
|
|
|
|
---
|
|
|
|
## Decisión Arquitectónica
|
|
|
|
### Componentes Prioritarios (Orden de Implementación)
|
|
|
|
#### FASE 1: Data Pipeline (Sprint 1-2)
|
|
**Prioridad:** P0 - Bloqueante
|
|
|
|
| Componente | Descripción | Estimación |
|
|
|------------|-------------|------------|
|
|
| Polygon API Integration | Conexión real con API key, sync 5m | 3 días |
|
|
| Data Sync Service | Cronjob para actualización OHLCV | 2 días |
|
|
| Redis Cache | Cache de datos para ML Engine | 1 día |
|
|
| Health Monitoring | Alertas de sync fallido | 1 día |
|
|
|
|
**Pares iniciales:**
|
|
- XAUUSD (C:XAUUSD)
|
|
- EURUSD (C:EURUSD)
|
|
- GBPUSD (C:GBPUSD)
|
|
- USDJPY (C:USDJPY)
|
|
|
|
#### FASE 2: MT4 Execution (Sprint 2-3)
|
|
**Prioridad:** P0 - Crítico
|
|
|
|
| Componente | Descripción | Estimación |
|
|
|------------|-------------|------------|
|
|
| MetaAPI Account Setup | Cuenta demo configurada | 1 día |
|
|
| MT4 Client Implementation | Conexión real + tests | 3 días |
|
|
| Risk Manager | Validación pre-trade | 2 días |
|
|
| Position Sizing | Cálculo de lots según cuenta | 1 día |
|
|
| Trade Execution Service | Service completo con logging | 2 días |
|
|
|
|
**Configuración de Riesgo:**
|
|
```yaml
|
|
account_200_usd:
|
|
max_risk_per_trade: 1% # $2
|
|
max_positions: 1
|
|
max_daily_loss: 5% # $10
|
|
allowed_pairs: [XAUUSD]
|
|
lot_size: 0.01
|
|
|
|
account_1000_usd:
|
|
max_risk_per_trade: 2% # $20
|
|
max_positions: 3
|
|
max_daily_loss: 5% # $50
|
|
allowed_pairs: [XAUUSD, EURUSD, GBPUSD, USDJPY]
|
|
lot_size_range: [0.01, 0.10]
|
|
```
|
|
|
|
#### FASE 3: Admin Dashboard (Sprint 3-4)
|
|
**Prioridad:** P0 - Crítico
|
|
|
|
| Componente | Descripción | Estimación |
|
|
|------------|-------------|------------|
|
|
| Signals Panel | Visualización de señales activas | 2 días |
|
|
| Chart Component | TradingView con overlay ML | 3 días |
|
|
| Trade History | Historial de operaciones | 1 día |
|
|
| Performance Metrics | P&L, win rate, drawdown | 1 día |
|
|
| Account Status | Balance, equity, margin | 1 día |
|
|
|
|
#### FASE 4: ML Pipeline Real-time (Sprint 4-5)
|
|
**Prioridad:** P0 - Crítico
|
|
|
|
| Componente | Descripción | Estimación |
|
|
|------------|-------------|------------|
|
|
| Signal Generator API | Endpoint /api/signals/{symbol} | 2 días |
|
|
| WebSocket Server | Push de señales en tiempo real | 2 días |
|
|
| AMD Phase Detection | Integración AMDDetector | 1 día |
|
|
| Prediction Caching | Redis para predicciones | 1 día |
|
|
|
|
#### FASE 5: LLM Agent (Sprint 5-6)
|
|
**Prioridad:** P1 - Importante
|
|
|
|
| Componente | Descripción | Estimación |
|
|
|------------|-------------|------------|
|
|
| Agent Service | FastAPI service para LLM | 3 días |
|
|
| Tool Functions | get_signal, execute_trade, etc. | 2 días |
|
|
| RAG Context | Trading strategies + historico | 2 días |
|
|
| Chat Interface | Frontend component | 2 días |
|
|
| Modes (Passive/Advisory/Auto) | Configuración de autonomía | 1 día |
|
|
|
|
---
|
|
|
|
## Flujo de Ejecución de Trade
|
|
|
|
```
|
|
[Market Data] → [ML Engine] → [Signal Generation] → [Risk Validation]
|
|
↓ ↓
|
|
[Admin Dashboard] [Risk Manager]
|
|
↓ ↓
|
|
[Manual Confirm] [Auto Execute]
|
|
↓ ↓
|
|
└────────┬────────────┘
|
|
↓
|
|
[MT4 Execution]
|
|
↓
|
|
[Trade Logging]
|
|
↓
|
|
[Performance Update]
|
|
```
|
|
|
|
---
|
|
|
|
## Gestión de Cuenta por Tamaño
|
|
|
|
### Cuenta Starter: $200-$500
|
|
|
|
```python
|
|
class StarterAccountConfig:
|
|
MIN_BALANCE = 200
|
|
MAX_BALANCE = 500
|
|
|
|
# Risk Management
|
|
MAX_RISK_PER_TRADE = 0.01 # 1%
|
|
MAX_DAILY_LOSS = 0.05 # 5%
|
|
MAX_WEEKLY_LOSS = 0.10 # 10%
|
|
MAX_OPEN_POSITIONS = 1
|
|
|
|
# Position Sizing
|
|
DEFAULT_LOT_SIZE = 0.01
|
|
MAX_LOT_SIZE = 0.02
|
|
|
|
# Pairs
|
|
ALLOWED_PAIRS = ["XAUUSD"] # Solo oro, menos posiciones
|
|
|
|
# Trading Hours
|
|
PREFERRED_SESSIONS = ["london", "newyork", "overlap"]
|
|
AVOID_NEWS = True
|
|
|
|
# Targets
|
|
MIN_RR_RATIO = 2.0 # Mínimo 2:1
|
|
MIN_CONFIDENCE = 0.70 # 70% confidence
|
|
```
|
|
|
|
### Cuenta Standard: $500-$1000
|
|
|
|
```python
|
|
class StandardAccountConfig:
|
|
MIN_BALANCE = 500
|
|
MAX_BALANCE = 1000
|
|
|
|
MAX_RISK_PER_TRADE = 0.015 # 1.5%
|
|
MAX_DAILY_LOSS = 0.05
|
|
MAX_OPEN_POSITIONS = 2
|
|
|
|
DEFAULT_LOT_SIZE = 0.02
|
|
MAX_LOT_SIZE = 0.05
|
|
|
|
ALLOWED_PAIRS = ["XAUUSD", "EURUSD"]
|
|
|
|
MIN_RR_RATIO = 2.0
|
|
MIN_CONFIDENCE = 0.65
|
|
```
|
|
|
|
### Cuenta Optimal: $1000+
|
|
|
|
```python
|
|
class OptimalAccountConfig:
|
|
MIN_BALANCE = 1000
|
|
MAX_BALANCE = 10000
|
|
|
|
MAX_RISK_PER_TRADE = 0.02 # 2%
|
|
MAX_DAILY_LOSS = 0.05
|
|
MAX_OPEN_POSITIONS = 3
|
|
|
|
DEFAULT_LOT_SIZE = 0.05
|
|
MAX_LOT_SIZE = 0.10
|
|
|
|
ALLOWED_PAIRS = ["XAUUSD", "EURUSD", "GBPUSD", "USDJPY"]
|
|
|
|
MIN_RR_RATIO = 1.5 # Puede tomar trades con menor R:R
|
|
MIN_CONFIDENCE = 0.60
|
|
```
|
|
|
|
---
|
|
|
|
## API Endpoints Nuevos
|
|
|
|
### ML Engine (FastAPI - Puerto 8000)
|
|
|
|
```yaml
|
|
endpoints:
|
|
# Predicciones
|
|
GET /api/v1/predictions/{symbol}:
|
|
description: "Obtiene predicción actual para símbolo"
|
|
response:
|
|
phase: "accumulation"
|
|
direction: "bullish"
|
|
confidence: 0.78
|
|
entry_price: 2645.50
|
|
stop_loss: 2640.00
|
|
take_profit: 2660.00
|
|
rr_ratio: 3.0
|
|
|
|
GET /api/v1/signals:
|
|
description: "Lista todas las señales activas"
|
|
params:
|
|
symbols: ["XAUUSD", "EURUSD"]
|
|
min_confidence: 0.60
|
|
|
|
POST /api/v1/validate-trade:
|
|
description: "Valida trade contra risk manager"
|
|
body:
|
|
symbol: "XAUUSD"
|
|
action: "buy"
|
|
lots: 0.02
|
|
sl: 2640.00
|
|
tp: 2660.00
|
|
|
|
# WebSocket
|
|
WS /ws/signals:
|
|
description: "Stream de señales en tiempo real"
|
|
events: ["new_signal", "signal_update", "signal_closed"]
|
|
```
|
|
|
|
### Backend Express (Puerto 3001)
|
|
|
|
```yaml
|
|
endpoints:
|
|
# Trading
|
|
POST /api/trading/execute:
|
|
description: "Ejecuta trade en MT4"
|
|
body:
|
|
symbol: "XAUUSD"
|
|
action: "buy"
|
|
lots: 0.02
|
|
sl: 2640.00
|
|
tp: 2660.00
|
|
requires: admin_role
|
|
|
|
GET /api/trading/positions:
|
|
description: "Lista posiciones abiertas"
|
|
|
|
DELETE /api/trading/positions/{ticket}:
|
|
description: "Cierra posición específica"
|
|
|
|
# Admin Dashboard
|
|
GET /api/admin/performance:
|
|
description: "Métricas de performance"
|
|
|
|
GET /api/admin/signals/history:
|
|
description: "Historial de señales"
|
|
```
|
|
|
|
---
|
|
|
|
## Archivos a Crear/Modificar
|
|
|
|
### Nuevos Archivos
|
|
|
|
```
|
|
apps/
|
|
├── ml-engine/
|
|
│ ├── src/
|
|
│ │ ├── api/
|
|
│ │ │ ├── routes/
|
|
│ │ │ │ ├── predictions.py # NEW
|
|
│ │ │ │ ├── signals.py # NEW
|
|
│ │ │ │ └── websocket.py # NEW
|
|
│ │ │ └── main.py # MODIFY
|
|
│ │ ├── services/
|
|
│ │ │ ├── signal_generator.py # MODIFY
|
|
│ │ │ └── real_time_predictor.py # NEW
|
|
│ │ └── execution/
|
|
│ │ ├── mt4_executor.py # NEW
|
|
│ │ ├── risk_manager.py # NEW
|
|
│ │ └── position_sizer.py # NEW
|
|
│
|
|
├── backend/
|
|
│ ├── src/
|
|
│ │ ├── modules/
|
|
│ │ │ ├── trading/
|
|
│ │ │ │ ├── trading.controller.ts # NEW
|
|
│ │ │ │ ├── trading.service.ts # NEW
|
|
│ │ │ │ └── trading.routes.ts # NEW
|
|
│ │ │ └── admin/
|
|
│ │ │ ├── admin.controller.ts # NEW
|
|
│ │ │ ├── admin.service.ts # NEW
|
|
│ │ │ └── admin.routes.ts # NEW
|
|
│
|
|
├── frontend/
|
|
│ ├── src/
|
|
│ │ ├── pages/
|
|
│ │ │ └── admin/
|
|
│ │ │ ├── Dashboard.tsx # NEW
|
|
│ │ │ ├── Signals.tsx # NEW
|
|
│ │ │ ├── Trades.tsx # NEW
|
|
│ │ │ └── Agent.tsx # NEW
|
|
│ │ ├── components/
|
|
│ │ │ └── admin/
|
|
│ │ │ ├── SignalCard.tsx # NEW
|
|
│ │ │ ├── TradingChart.tsx # NEW
|
|
│ │ │ ├── PerformanceMetrics.tsx # NEW
|
|
│ │ │ └── AgentChat.tsx # NEW
|
|
│
|
|
├── data-service/
|
|
│ ├── src/
|
|
│ │ ├── providers/
|
|
│ │ │ ├── polygon_client.py # MODIFY
|
|
│ │ │ └── metaapi_client.py # NEW
|
|
│ │ └── services/
|
|
│ │ ├── sync_service.py # MODIFY
|
|
│ │ └── spread_tracker.py # MODIFY
|
|
```
|
|
|
|
---
|
|
|
|
## Métricas de Éxito
|
|
|
|
| Métrica | Target MVP | Target Producción |
|
|
|---------|------------|-------------------|
|
|
| Signal Accuracy | >65% | >70% |
|
|
| Win Rate | >55% | >60% |
|
|
| Profit Factor | >1.5 | >2.0 |
|
|
| Max Drawdown | <15% | <10% |
|
|
| Latency (signal) | <1s | <500ms |
|
|
| Uptime | 95% | 99.5% |
|
|
| Trades/día | 1-3 | 3-5 |
|
|
|
|
---
|
|
|
|
## Riesgos y Mitigaciones
|
|
|
|
| Riesgo | Probabilidad | Impacto | Mitigación |
|
|
|--------|--------------|---------|------------|
|
|
| Pérdida de capital inicial | Alta | Alto | Risk manager estricto, cuenta demo primero |
|
|
| Diferencia precios Polygon vs MT4 | Media | Alto | Modelo de ajuste de spread |
|
|
| API downtime | Baja | Alto | Fallback a cache, alertas |
|
|
| Overfitting modelos | Media | Alto | Validación temporal, walk-forward |
|
|
| Ejecución lenta | Media | Medio | MetaAPI cloud, no terminal local |
|
|
|
|
---
|
|
|
|
## Timeline Estimado
|
|
|
|
```
|
|
Semana 1-2: FASE 1 (Data Pipeline)
|
|
└── Polygon integration + sync service
|
|
|
|
Semana 2-3: FASE 2 (MT4 Execution)
|
|
└── MetaAPI client + risk manager
|
|
|
|
Semana 3-4: FASE 3 (Admin Dashboard)
|
|
└── Signals panel + charts + trades
|
|
|
|
Semana 4-5: FASE 4 (ML Real-time)
|
|
└── WebSocket + signal generation
|
|
|
|
Semana 5-6: FASE 5 (LLM Agent)
|
|
└── Agent service + tools + chat
|
|
|
|
─────────────────────────────────────────
|
|
Total: 6 semanas para MVP operativo
|
|
```
|
|
|
|
---
|
|
|
|
## Próximos Pasos Inmediatos
|
|
|
|
1. **Hoy:** Obtener API key de Polygon.io (gratis)
|
|
2. **Hoy:** Crear cuenta demo en MetaAPI.cloud
|
|
3. **Día 1-2:** Implementar conexión real Polygon
|
|
4. **Día 3-4:** Implementar MT4 client con MetaAPI
|
|
5. **Día 5:** Tests de integración end-to-end
|
|
|
|
---
|
|
|
|
## Referencias
|
|
|
|
- [CONTEXTO-PROYECTO.md](../../orchestration/00-guidelines/CONTEXTO-PROYECTO.md)
|
|
- [ARQUITECTURA-UNIFICADA.md](../01-arquitectura/ARQUITECTURA-UNIFICADA.md)
|
|
- [MODELOS-ML-DEFINICION.md](../02-definicion-modulos/OQI-006-ml-signals/estrategias/MODELOS-ML-DEFINICION.md)
|
|
- [INT-DATA-001-data-service.md](../90-transversal/integraciones/INT-DATA-001-data-service.md)
|
|
|
|
---
|
|
|
|
**Validado por:** Architecture-Analyst
|
|
**Sistema:** NEXUS + SIMCO v2.2.0
|