ML Engine Updates: - Updated BTCUSD with Polygon API data (2024-2025): 215,699 new records - Re-trained all ML models: Attention (R²: 0.223), Base, Metamodel (87.3% confidence) - Backtest results: +176.71R profit with aggressive_filter strategy Documentation Consolidation: - Created docs/99-analisis/_MAP.md index with 13 new analysis documents - Consolidated inventories: removed duplicates from orchestration/inventarios/ - Updated ML_INVENTORY.yml with BTCUSD metrics and training results - Added execution reports: FASE11-BTCUSD, correction issues, alignment validation Architecture & Integration: - Updated all module documentation with NEXUS v3.4 frontmatter - Fixed _MAP.md indexes across all folders - Updated orchestration plans and traces Files: 229 changed, 5064 insertions(+), 1872 deletions(-) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
483 lines
18 KiB
Markdown
483 lines
18 KiB
Markdown
---
|
|
id: "ALCANCES-FASE-1-PRIORIZADOS"
|
|
title: "Alcances Fase 1 - Primera Entrega Priorizada"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# Alcances Fase 1 - Primera Entrega Priorizada
|
|
|
|
**Version:** 1.0.0
|
|
**Fecha:** 2025-12-08
|
|
**Proyecto:** Trading Platform
|
|
**Autor:** Requirements Analyst / Trading Strategist
|
|
|
|
---
|
|
|
|
## Objetivo de Fase 1
|
|
|
|
Entregar un **agente personal de trading funcional** que integre:
|
|
1. Modelos de ML entrenados y validados
|
|
2. Visualizacion de resultados y predicciones
|
|
3. Integracion con LLM local para analisis
|
|
4. Conexion con MetaTrader4 para operaciones
|
|
5. Pipeline de datos con API Massive
|
|
|
|
---
|
|
|
|
## Prioridades de Entrega
|
|
|
|
### P0 - Must Have (Critico)
|
|
|
|
| ID | Componente | Descripcion | Criterio de Exito |
|
|
|----|------------|-------------|-------------------|
|
|
| P0-01 | **AMDDetector** | Modelo de deteccion de fases | Accuracy >70%, F1 >0.65 |
|
|
| P0-02 | **RangePredictor** | Predictor de delta high/low | MAE <0.003, Dir Acc >90% |
|
|
| P0-03 | **TPSLClassifier** | Clasificador TP vs SL | AUC >0.85, Acc >80% |
|
|
| P0-04 | **Pipeline de Features** | Extraccion de 103 features | Sin errores, <500ms |
|
|
| P0-05 | **StrategyOrchestrator** | Meta-modelo para senales | EV positivo en backtest |
|
|
| P0-06 | **Dashboard Validacion** | Visualizacion de predicciones | Graficas interactivas |
|
|
| P0-07 | **Integracion LLM** | chatgpt-oss para analisis | Response <3s, Tools funcionales |
|
|
| P0-08 | **Integracion MT4** | Conexion via MetaAPI | CRUD de ordenes funcional |
|
|
| P0-09 | **Pipeline Datos** | API Massive + actualizacion | Datos sincronizados |
|
|
|
|
### P1 - Should Have (Importante)
|
|
|
|
| ID | Componente | Descripcion | Criterio de Exito |
|
|
|----|------------|-------------|-------------------|
|
|
| P1-01 | **LiquidityHunter** | Detector de stop hunts | Precision >70% |
|
|
| P1-02 | **ICTContextModel** | Scoring de contexto ICT | Score calibrado |
|
|
| P1-03 | **Backtesting Engine** | Validacion historica | Metricas completas |
|
|
| P1-04 | **Alertas** | Notificaciones de senales | Push notifications |
|
|
| P1-05 | **Trade Journal** | Log de operaciones | Registro completo |
|
|
|
|
### P2 - Nice to Have (Deseable)
|
|
|
|
| ID | Componente | Descripcion | Criterio de Exito |
|
|
|----|------------|-------------|-------------------|
|
|
| P2-01 | **OrderFlowModel** | LSTM para order flow | Score significativo |
|
|
| P2-02 | **Multi-Symbol** | Soporte EURUSD, GBPUSD | Modelos por simbolo |
|
|
| P2-03 | **Auto-Retraining** | Reentrenamiento automatico | Weekly schedule |
|
|
| P2-04 | **Risk Dashboard** | Metricas de riesgo | DD, Sharpe, etc. |
|
|
|
|
---
|
|
|
|
## Detalle de Componentes P0
|
|
|
|
### P0-01: AMDDetector
|
|
|
|
**Objetivo:** Clasificar la fase actual del mercado (Accumulation, Manipulation, Distribution, Neutral)
|
|
|
|
**Especificaciones:**
|
|
- **Modelo:** XGBoost Multiclass
|
|
- **Input:** 50 features (Price Action, Volume, Structure, Order Flow)
|
|
- **Output:** 4 probabilidades + fase predicha
|
|
- **Dataset:** 10 anos XAUUSD (~660K registros)
|
|
|
|
**Metricas Target:**
|
|
| Metrica | Target | Minimo Aceptable |
|
|
|---------|--------|------------------|
|
|
| Overall Accuracy | >70% | 65% |
|
|
| Macro F1 | >0.65 | 0.60 |
|
|
| Accumulation Precision | >70% | 60% |
|
|
| Manipulation Precision | >65% | 55% |
|
|
| Distribution Precision | >70% | 60% |
|
|
|
|
**Entregables:**
|
|
- [ ] Modelo entrenado (`amd_detector.pkl`)
|
|
- [ ] Pipeline de features (`amd_features.py`)
|
|
- [ ] Script de entrenamiento (`train_amd.py`)
|
|
- [ ] Evaluacion en test set (`amd_evaluation.ipynb`)
|
|
- [ ] Documentacion de features
|
|
|
|
### P0-02: RangePredictor
|
|
|
|
**Objetivo:** Predecir el movimiento maximo hacia arriba (delta_high) y abajo (delta_low) del precio
|
|
|
|
**Especificaciones:**
|
|
- **Modelo:** XGBoost Regressor + Classifier (bins)
|
|
- **Input:** 115 features (base + AMD outputs)
|
|
- **Output:** delta_high, delta_low para 15m y 1h
|
|
- **Stacking:** Usa outputs de AMDDetector
|
|
|
|
**Metricas Target:**
|
|
| Horizonte | MAE High | MAE Low | Dir Acc High | Dir Acc Low |
|
|
|-----------|----------|---------|--------------|-------------|
|
|
| 15m | <0.003 | <0.003 | >95% | >50% |
|
|
| 1h | <0.005 | <0.005 | >90% | >50% |
|
|
|
|
**Entregables:**
|
|
- [ ] Modelo entrenado (`range_predictor.pkl`)
|
|
- [ ] Feature augmentation pipeline
|
|
- [ ] Script de entrenamiento (`train_range.py`)
|
|
- [ ] Evaluacion (`range_evaluation.ipynb`)
|
|
|
|
### P0-03: TPSLClassifier
|
|
|
|
**Objetivo:** Predecir probabilidad de que TP sea alcanzado antes que SL
|
|
|
|
**Especificaciones:**
|
|
- **Modelo:** XGBoost Binary + Isotonic Calibration
|
|
- **Input:** 123 features (base + AMD + Range outputs)
|
|
- **Output:** P(TP first) para multiples R:R configs
|
|
- **Stacking:** Usa outputs de AMD + Range
|
|
|
|
**Metricas Target:**
|
|
| Config | Accuracy | AUC | Precision | Recall |
|
|
|--------|----------|-----|-----------|--------|
|
|
| R:R 2:1 | >80% | >0.85 | >75% | >75% |
|
|
| R:R 3:1 | >75% | >0.80 | >70% | >70% |
|
|
|
|
**Entregables:**
|
|
- [ ] Modelo entrenado (`tpsl_classifier.pkl`)
|
|
- [ ] Calibrador de probabilidades (`calibrator.pkl`)
|
|
- [ ] Script de entrenamiento (`train_tpsl.py`)
|
|
- [ ] Evaluacion (`tpsl_evaluation.ipynb`)
|
|
|
|
### P0-04: Pipeline de Features
|
|
|
|
**Objetivo:** Extraer y transformar las 103 features de manera consistente
|
|
|
|
**Especificaciones:**
|
|
- **Categorias:** Price Action(12), Volume(10), Volatility(8), Trend(10), Structure(12), OrderFlow(10), Liquidity(8), ICT(15), SMC(12), Time(6)
|
|
- **Scaler:** RobustScaler (robusto a outliers)
|
|
- **Performance:** <500ms para extraccion completa
|
|
|
|
**Entregables:**
|
|
- [ ] `FeatureEngineeringPipeline` class
|
|
- [ ] Funciones de extraccion por categoria
|
|
- [ ] Scaler serializado (`scaler.pkl`)
|
|
- [ ] Tests unitarios
|
|
- [ ] Documentacion de cada feature
|
|
|
|
### P0-05: StrategyOrchestrator
|
|
|
|
**Objetivo:** Combinar todos los modelos para generar senal final de trading
|
|
|
|
**Especificaciones:**
|
|
- **Tipo:** Ensemble weighted + reglas
|
|
- **Input:** Outputs de todos los modelos
|
|
- **Output:** Signal (LONG/SHORT/HOLD), confidence, SL, TP, position size
|
|
- **Threshold:** Confidence minimo 60%
|
|
|
|
**Decision Logic:**
|
|
1. AMD phase filter (solo accumulation/distribution)
|
|
2. ICT context alignment
|
|
3. Range prediction bias
|
|
4. TPSL probability check (>55%)
|
|
5. Liquidity risk assessment
|
|
6. Confidence aggregation
|
|
|
|
**Entregables:**
|
|
- [ ] `StrategyOrchestrator` class
|
|
- [ ] Configuration file (`orchestrator_config.yaml`)
|
|
- [ ] Backtest validation
|
|
- [ ] Signal logging
|
|
|
|
### P0-06: Dashboard de Validacion
|
|
|
|
**Objetivo:** Visualizar predicciones y validar efectividad de modelos
|
|
|
|
**Componentes:**
|
|
1. **Grafica de Senales:** Candlestick + senales superpuestas
|
|
2. **AMD Phase Timeline:** Fases detectadas en el tiempo
|
|
3. **Predicciones vs Real:** Comparacion delta_high/low
|
|
4. **Metricas en Vivo:** Accuracy, precision rolling
|
|
5. **Confusion Matrix:** Por modelo
|
|
6. **Feature Importance:** Top 20 features
|
|
|
|
**Stack:**
|
|
- FastAPI backend
|
|
- Plotly/Dash frontend
|
|
- WebSocket para updates
|
|
|
|
**Entregables:**
|
|
- [ ] API endpoints (`/api/visualization/*`)
|
|
- [ ] Dashboard interactivo
|
|
- [ ] Export de reportes (PDF/HTML)
|
|
|
|
### P0-07: Integracion LLM Local
|
|
|
|
**Objetivo:** Integrar chatgpt-oss (16GB) para analisis y decisiones
|
|
|
|
**Especificaciones:**
|
|
- **Modelo:** chatgpt-oss (compatible con NVIDIA RTX 5060 Ti 16GB)
|
|
- **API:** Compatible con OpenAI API format
|
|
- **Hosting:** Local via Ollama o similar
|
|
- **Latencia:** <3s response time
|
|
|
|
**Tools disponibles:**
|
|
```python
|
|
tools = [
|
|
{
|
|
"name": "get_ml_signal",
|
|
"description": "Obtiene senal ML actual",
|
|
"parameters": ["symbol", "timeframe"]
|
|
},
|
|
{
|
|
"name": "analyze_market",
|
|
"description": "Analiza estado del mercado",
|
|
"parameters": ["symbol"]
|
|
},
|
|
{
|
|
"name": "explain_signal",
|
|
"description": "Explica una senal",
|
|
"parameters": ["signal"]
|
|
},
|
|
{
|
|
"name": "execute_trade",
|
|
"description": "Ejecuta operacion",
|
|
"parameters": ["symbol", "action", "size", "sl", "tp"]
|
|
},
|
|
{
|
|
"name": "get_portfolio",
|
|
"description": "Estado del portfolio",
|
|
"parameters": []
|
|
}
|
|
]
|
|
```
|
|
|
|
**Entregables:**
|
|
- [ ] LLM service (`llm_service.py`)
|
|
- [ ] Trading tools implementation
|
|
- [ ] System prompt optimizado
|
|
- [ ] Context management (Redis)
|
|
|
|
### P0-08: Integracion MetaTrader4
|
|
|
|
**Objetivo:** Gestionar cuentas y operaciones via MetaAPI
|
|
|
|
**Especificaciones:**
|
|
- **Provider:** MetaAPI (cloud connection to MT4)
|
|
- **Accounts:** Multiple account support
|
|
- **Operations:** Open, Modify, Close positions
|
|
|
|
**API Endpoints:**
|
|
```
|
|
POST /api/mt4/accounts/{id}/connect
|
|
GET /api/mt4/accounts/{id}/positions
|
|
POST /api/mt4/accounts/{id}/trade
|
|
PUT /api/mt4/accounts/{id}/trade/{ticket}
|
|
DELETE /api/mt4/accounts/{id}/trade/{ticket}
|
|
GET /api/mt4/accounts/{id}/history
|
|
```
|
|
|
|
**Manejo de Variaciones de Precio:**
|
|
- Configuracion de slippage maximo por broker
|
|
- Requotes handling
|
|
- Price adjustment basado en diferencias broker
|
|
|
|
**Entregables:**
|
|
- [ ] MetaAPI client wrapper
|
|
- [ ] Account management service
|
|
- [ ] Trade execution service
|
|
- [ ] Price adjustment logic
|
|
- [ ] Error handling y retry logic
|
|
|
|
### P0-09: Pipeline de Datos
|
|
|
|
**Objetivo:** Mantener datos actualizados via API Massive
|
|
|
|
**Especificaciones:**
|
|
- **Provider:** API Massive
|
|
- **Symbols:** XAUUSD, EURUSD, GBPUSD, USDJPY
|
|
- **Timeframe:** 5 minutos
|
|
- **Storage:** PostgreSQL
|
|
|
|
**Pipeline:**
|
|
```
|
|
API Massive --> Data Fetcher --> Validator --> PostgreSQL
|
|
|
|
|
v
|
|
Gap Detection
|
|
|
|
|
v
|
|
Gap Filling
|
|
```
|
|
|
|
**Schedule:**
|
|
- Full sync: 1x/dia (04:00 UTC)
|
|
- Incremental: Cada 5 minutos
|
|
|
|
**Entregables:**
|
|
- [ ] API Massive client
|
|
- [ ] Data fetcher service
|
|
- [ ] Gap detection algorithm
|
|
- [ ] PostgreSQL schema
|
|
- [ ] Scheduler (cron/celery)
|
|
|
|
---
|
|
|
|
## Arquitectura de Fase 1
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────────────────────┐
|
|
│ FASE 1 ARCHITECTURE │
|
|
├─────────────────────────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
|
|
│ │ Data Layer │ │ ML Layer │ │ Integration │ │
|
|
│ │ │ │ │ │ Layer │ │
|
|
│ │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │
|
|
│ │ │PostgreSQL │ │ │ │AMDDetector│ │ │ │LLM Agent │ │ │
|
|
│ │ │ (data) │ │◄───▶│ └───────────┘ │◄───▶│ │(chatgpt) │ │ │
|
|
│ │ └───────────┘ │ │ ┌───────────┐ │ │ └───────────┘ │ │
|
|
│ │ ┌───────────┐ │ │ │Range │ │ │ ┌───────────┐ │ │
|
|
│ │ │API Massive│──┼────▶│ │Predictor │ │◄───▶│ │MetaTrader │ │ │
|
|
│ │ │ (source) │ │ │ └───────────┘ │ │ │ (MT4) │ │ │
|
|
│ │ └───────────┘ │ │ ┌───────────┐ │ │ └───────────┘ │ │
|
|
│ │ │ │ │TPSL │ │ │ │ │
|
|
│ │ │ │ │Classifier │ │ │ │ │
|
|
│ │ │ │ └───────────┘ │ │ │ │
|
|
│ │ │ │ ┌───────────┐ │ │ │ │
|
|
│ │ │ │ │Orchestratr│ │ │ │ │
|
|
│ │ │ │ └───────────┘ │ │ │ │
|
|
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
|
|
│ │ │ │ │
|
|
│ │ │ │ │
|
|
│ └──────────────────────┼──────────────────────┘ │
|
|
│ │ │
|
|
│ ▼ │
|
|
│ ┌─────────────────────────┐ │
|
|
│ │ Visualization │ │
|
|
│ │ Dashboard │ │
|
|
│ │ │ │
|
|
│ │ - Signal Visualization │ │
|
|
│ │ - Model Validation │ │
|
|
│ │ - Performance Metrics │ │
|
|
│ │ - Backtest Reports │ │
|
|
│ └─────────────────────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## Plan de Implementacion
|
|
|
|
### Sprint 1: ML Core (Semana 1-2)
|
|
|
|
| Dia | Tareas |
|
|
|-----|--------|
|
|
| 1-2 | Setup entorno, migrar datos historicos |
|
|
| 3-4 | Implementar Feature Engineering Pipeline |
|
|
| 5-6 | Entrenar AMDDetector, evaluar |
|
|
| 7-8 | Entrenar RangePredictor con stacking |
|
|
| 9-10 | Entrenar TPSLClassifier |
|
|
| 11-12 | Implementar StrategyOrchestrator |
|
|
| 13-14 | Testing end-to-end, ajustes |
|
|
|
|
### Sprint 2: Integraciones (Semana 3-4)
|
|
|
|
| Dia | Tareas |
|
|
|-----|--------|
|
|
| 1-2 | Setup LLM local (chatgpt-oss) |
|
|
| 3-4 | Implementar trading tools para LLM |
|
|
| 5-6 | Integracion MetaAPI |
|
|
| 7-8 | Trade execution service |
|
|
| 9-10 | Pipeline de datos (API Massive) |
|
|
| 11-12 | Price adjustment por broker |
|
|
| 13-14 | Testing integraciones |
|
|
|
|
### Sprint 3: Visualizacion y Validacion (Semana 5)
|
|
|
|
| Dia | Tareas |
|
|
|-----|--------|
|
|
| 1-2 | Dashboard de senales |
|
|
| 3-4 | Metricas y graficas de validacion |
|
|
| 5-6 | Backtesting completo |
|
|
| 7 | Documentacion final |
|
|
|
|
---
|
|
|
|
## Criterios de Aceptacion Final
|
|
|
|
### Funcionalidad
|
|
|
|
- [ ] AMDDetector predice fases con accuracy >70%
|
|
- [ ] RangePredictor predice movimientos con MAE <0.003
|
|
- [ ] TPSLClassifier tiene AUC >0.85
|
|
- [ ] StrategyOrchestrator genera senales coherentes
|
|
- [ ] LLM responde consultas en <3s
|
|
- [ ] MT4 ejecuta ordenes correctamente
|
|
- [ ] Datos se actualizan automaticamente
|
|
|
|
### Calidad
|
|
|
|
- [ ] Cobertura de tests >80%
|
|
- [ ] Documentacion completa
|
|
- [ ] Codigo revisado (code review)
|
|
- [ ] Sin vulnerabilidades criticas
|
|
|
|
### Performance
|
|
|
|
- [ ] Inferencia completa <2s
|
|
- [ ] Dashboard carga <3s
|
|
- [ ] API response time <500ms
|
|
|
|
### Validacion
|
|
|
|
- [ ] Backtest con EV positivo
|
|
- [ ] Paper trading 1 semana exitoso
|
|
- [ ] User acceptance testing aprobado
|
|
|
|
---
|
|
|
|
## Riesgos y Mitigacion
|
|
|
|
| Riesgo | Probabilidad | Impacto | Mitigacion |
|
|
|--------|--------------|---------|------------|
|
|
| Accuracy ML insuficiente | Media | Alto | Mas datos, feature engineering |
|
|
| LLM no cabe en GPU | Baja | Alto | Usar modelo mas pequeno |
|
|
| MetaAPI rate limits | Media | Medio | Caching, throttling |
|
|
| API Massive downtime | Baja | Medio | Datos backup locales |
|
|
| Overfitting modelos | Media | Alto | Walk-forward validation |
|
|
|
|
---
|
|
|
|
## Recursos Requeridos
|
|
|
|
### Hardware
|
|
- **GPU:** NVIDIA RTX 5060 Ti 16GB (disponible)
|
|
- **RAM:** 32GB+ recomendado
|
|
- **Storage:** 100GB+ SSD
|
|
|
|
### Software
|
|
- Python 3.11+
|
|
- XGBoost con CUDA
|
|
- PostgreSQL 15+ (instancia compartida del workspace)
|
|
- Redis 7+
|
|
- Docker
|
|
|
|
### APIs
|
|
- MetaAPI subscription
|
|
- API Massive subscription
|
|
|
|
### Configuracion de Puertos (DEVENV-PORTS Policy)
|
|
|
|
Segun la politica de puertos del workspace, trading-platform usa el rango **3600**:
|
|
|
|
| Servicio | Puerto | Descripcion |
|
|
|----------|--------|-------------|
|
|
| Backend/API | 3600 | API principal FastAPI |
|
|
| ML Engine | 3601 | Servicio de modelos ML |
|
|
| LLM Service | 3602 | chatgpt-oss via Ollama |
|
|
| Trading Service | 3603 | MetaAPI bridge |
|
|
| Data Service | 3604 | API Massive pipeline |
|
|
| Frontend | 5179 | Dashboard Plotly/Dash |
|
|
| Database | 5438 | PostgreSQL compartido |
|
|
| Redis | 6385 | Cache y pub/sub |
|
|
|
|
> **Referencia:** `/home/isem/workspace/core/devtools/environment/DEVENV-PORTS.md`
|
|
|
|
### Tiempo Estimado
|
|
- **Total:** 5 semanas
|
|
- **Dedicacion:** Full-time
|
|
|
|
---
|
|
|
|
**Documento Generado:** 2025-12-08
|
|
**Requirements Analyst / Trading Strategist - Trading Platform**
|