[ST-4.4] feat: Add GIN indexes for llm.conversations array columns
- Add GIN indexes on tags, related_symbols, and related_topics columns - Optimizes full-text search performance for conversation filtering - Adds migration file 2026-02-03_add_llm_gin_indexes.sql - Updates DDL schema definition with missing idx_conversations_topics index Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
67845e2ebd
commit
4e70c223e6
@ -1 +1 @@
|
||||
Subproject commit 6da278659064c1755ef8105c69ff59f466bcb51a
|
||||
Subproject commit 82d6e608b1e2a825ab75adee9a8327164402a606
|
||||
@ -1,297 +0,0 @@
|
||||
# Delegación: Trading Strategist - Análisis Profundo y Actualización Documentación
|
||||
|
||||
**Fecha:** 2025-12-08
|
||||
**Delegado por:** Requirements-Analyst
|
||||
**Agente Destino:** Trading Strategist
|
||||
**Prioridad:** Alta
|
||||
**Estado:** En Progreso
|
||||
|
||||
---
|
||||
|
||||
## Contexto de la Solicitud
|
||||
|
||||
El usuario ha solicitado una revisión profunda y actualización de la documentación de estrategias y modelos ML para el proyecto Trading Platform, con foco en:
|
||||
|
||||
1. **Estrategia AMD sólida** como base principal
|
||||
2. **Estrategias complementarias** (ICT/SMC) integradas
|
||||
3. **Modelos de ML** bien definidos con features, targets, y metamodelos
|
||||
4. **Priorización de Fase 1** - Modelos funcionando y validables
|
||||
|
||||
---
|
||||
|
||||
## Alcance del Análisis
|
||||
|
||||
### 1. Estrategia AMD (Accumulation-Manipulation-Distribution)
|
||||
|
||||
**Documentación existente:** `docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/ESTRATEGIA-AMD-COMPLETA.md`
|
||||
|
||||
**Tareas requeridas:**
|
||||
- [ ] Revisar completitud de la documentación AMD actual
|
||||
- [ ] Validar que todas las subfases de Wyckoff estén documentadas (PS, SC, AR, ST, Spring, UTAD)
|
||||
- [ ] Asegurar que los indicadores técnicos estén completos (50+ features)
|
||||
- [ ] Definir reglas claras de entrada/salida por cada fase
|
||||
- [ ] Documentar criterios de transición entre fases
|
||||
- [ ] Agregar backtesting results esperados
|
||||
- [ ] Definir métricas de validación específicas por fase
|
||||
|
||||
### 2. Estrategias Complementarias (ICT/SMC)
|
||||
|
||||
**Documentación existente:** `docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/ESTRATEGIA-ICT-SMC.md`
|
||||
|
||||
**Tareas requeridas:**
|
||||
- [ ] Revisar integración ICT con AMD
|
||||
- [ ] Completar documentación de Killzones y su impacto en señales
|
||||
- [ ] Documentar OTE (Optimal Trade Entry) con criterios ML
|
||||
- [ ] Definir features derivados de ICT para ML
|
||||
- [ ] Completar SMC (BOS, CHOCH, Inducement, Displacement)
|
||||
- [ ] Crear matriz de confluence AMD + ICT + SMC
|
||||
- [ ] Definir scoring system unificado
|
||||
|
||||
### 3. Definición de Modelos ML
|
||||
|
||||
**Documentación existente:** `docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/MODELOS-ML-DEFINICION.md`
|
||||
|
||||
**Modelos a definir/validar:**
|
||||
|
||||
| Modelo | Función | Input | Output | Métrica Target |
|
||||
|--------|---------|-------|--------|----------------|
|
||||
| **AMDDetector** | Clasificar fase del mercado | 50+ features | 4 clases + confianza | >70% accuracy |
|
||||
| **RangePredictor** | Predecir delta high/low | 70+ features | delta_high, delta_low | MAE <0.003 |
|
||||
| **TPSLClassifier** | P(TP antes SL) | 80+ features + stacking | probability | AUC >0.85 |
|
||||
| **LiquidityHunter** | Detectar stop hunts | 30+ features | P(sweep) | Precision >70% |
|
||||
| **ICTContextModel** | Contexto ICT | Killzone + OTE | context_score | - |
|
||||
| **StrategyOrchestrator** | Meta-modelo ensemble | All models | Signal final | EV positivo |
|
||||
|
||||
**Tareas requeridas:**
|
||||
- [ ] Definir arquitectura detallada de cada modelo
|
||||
- [ ] Definir features completos con nombres y cálculos
|
||||
- [ ] Definir targets con método de labeling
|
||||
- [ ] Definir relaciones/dependencias entre modelos (pipeline)
|
||||
- [ ] Especificar metamodelos y ensemble
|
||||
- [ ] Documentar flujo de datos completo
|
||||
|
||||
### 4. Features y Targets
|
||||
|
||||
**Crear/Actualizar:** `docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/FEATURES-TARGETS-COMPLETO.md`
|
||||
|
||||
**Estructura requerida:**
|
||||
|
||||
```markdown
|
||||
## Features por Categoría
|
||||
|
||||
### Price Action Features (10)
|
||||
| Feature | Cálculo | Modelo(s) |
|
||||
|---------|---------|-----------|
|
||||
| range_ratio | (high-low)/SMA(high,20) | AMD, Range |
|
||||
| ... | ... | ... |
|
||||
|
||||
### Volume Features (8)
|
||||
...
|
||||
|
||||
### Volatility Features (6)
|
||||
...
|
||||
|
||||
### Trend Features (8)
|
||||
...
|
||||
|
||||
### Market Structure Features (10)
|
||||
...
|
||||
|
||||
### Order Flow Features (8)
|
||||
...
|
||||
|
||||
### ICT Features (15)
|
||||
...
|
||||
|
||||
### SMC Features (12)
|
||||
...
|
||||
|
||||
### Liquidity Features (5)
|
||||
...
|
||||
|
||||
### Time Features (5)
|
||||
...
|
||||
|
||||
## Targets por Modelo
|
||||
|
||||
### AMDDetector Target
|
||||
- Tipo: Multiclass (4 clases)
|
||||
- Labeling: Forward-looking 20 bars
|
||||
- Criterios: [detallados]
|
||||
|
||||
### RangePredictor Target
|
||||
- Tipo: Regression + Bins
|
||||
- Labeling: Max high/low en horizonte
|
||||
- Horizontes: 15m, 1h
|
||||
|
||||
### TPSLClassifier Target
|
||||
- Tipo: Binary
|
||||
- Labeling: ¿TP toca antes de SL?
|
||||
- R:R configs: 2:1, 3:1
|
||||
```
|
||||
|
||||
### 5. Relaciones y Flujo de Modelos
|
||||
|
||||
**Crear:** `docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/ARQUITECTURA-MODELOS-FLUJO.md`
|
||||
|
||||
**Contenido requerido:**
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ PIPELINE DE MODELOS │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ NIVEL 1: Feature Engineering │
|
||||
│ ├─ Base Features (OHLCV → 21 features) │
|
||||
│ ├─ Technical Features (indicators → 30 features) │
|
||||
│ └─ SMC/ICT Features (structure → 40 features) │
|
||||
│ │
|
||||
│ NIVEL 2: Modelos Primarios (Paralelo) │
|
||||
│ ├─ AMDDetector → phase_proba[4] │
|
||||
│ ├─ LiquidityHunter → sweep_proba[2] │
|
||||
│ └─ ICTContextModel → context_score │
|
||||
│ │
|
||||
│ NIVEL 3: Modelos Secundarios (Stacking) │
|
||||
│ ├─ RangePredictor(features + L2_outputs) → delta_hl │
|
||||
│ └─ TPSLClassifier(features + L2 + Range) → tp_prob │
|
||||
│ │
|
||||
│ NIVEL 4: Meta-Modelo (Ensemble) │
|
||||
│ └─ StrategyOrchestrator → Signal Final │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Entregables Esperados
|
||||
|
||||
### Documento 1: ESTRATEGIA-AMD-ACTUALIZADA.md
|
||||
- Versión mejorada con gaps cerrados
|
||||
- Incluir backtesting guidelines
|
||||
- Métricas de validación
|
||||
|
||||
### Documento 2: ESTRATEGIA-INTEGRADA-AMD-ICT-SMC.md
|
||||
- Framework unificado
|
||||
- Matrix de confluence
|
||||
- Scoring system
|
||||
|
||||
### Documento 3: FEATURES-TARGETS-COMPLETO.md
|
||||
- Todos los features categorizados
|
||||
- Cálculos exactos
|
||||
- Targets con labeling detallado
|
||||
|
||||
### Documento 4: ARQUITECTURA-MODELOS-FLUJO.md
|
||||
- Pipeline completo
|
||||
- Dependencias entre modelos
|
||||
- Flujo de datos
|
||||
|
||||
### Documento 5: ALCANCES-FASE-1-PRIORIZADOS.md
|
||||
- Priorización para primera entrega
|
||||
- Modelos mínimos viables
|
||||
- Criterios de éxito medibles
|
||||
|
||||
---
|
||||
|
||||
## Priorización Fase 1 - Primera Entrega
|
||||
|
||||
El usuario ha especificado que la primera entrega debe incluir:
|
||||
|
||||
### Must Have (P0)
|
||||
1. **Modelos ML entrenados y funcionando**
|
||||
- AMDDetector
|
||||
- RangePredictor
|
||||
- TPSLClassifier
|
||||
|
||||
2. **Visualización de resultados**
|
||||
- Informes de backtesting
|
||||
- Visualización de predicciones
|
||||
- Dashboard de validación
|
||||
|
||||
3. **Integración con LLM local (chatgpt-oss 16GB)**
|
||||
- Análisis de señales
|
||||
- Toma de decisiones
|
||||
|
||||
4. **Integración con MetaTrader4**
|
||||
- Gestión de cuentas
|
||||
- Ejecución de operaciones
|
||||
- Ajuste de precios por broker
|
||||
|
||||
5. **Integración con API Massive**
|
||||
- Descarga de datos históricos
|
||||
- Actualización de activos
|
||||
|
||||
### Nice to Have (P1)
|
||||
- Plataforma SaaS completa
|
||||
- UI completa
|
||||
- Multi-tenant
|
||||
|
||||
---
|
||||
|
||||
## Integraciones Críticas a Documentar
|
||||
|
||||
### 1. Integración LLM Local (chatgpt-oss 16GB)
|
||||
|
||||
**Archivo a crear:** `docs/01-arquitectura/INTEGRACION-LLM-LOCAL.md`
|
||||
|
||||
**Contenido:**
|
||||
- Configuración del modelo chatgpt-oss
|
||||
- API local compatible OpenAI
|
||||
- Tools disponibles para trading
|
||||
- Prompts de sistema para análisis
|
||||
- Flujo de decisión con ML signals
|
||||
|
||||
### 2. Integración MetaTrader4
|
||||
|
||||
**Archivo a crear:** `docs/01-arquitectura/INTEGRACION-METATRADER4.md`
|
||||
|
||||
**Contenido:**
|
||||
- Conexión vía MetaAPI
|
||||
- Gestión de cuentas múltiples
|
||||
- Ejecución de órdenes
|
||||
- Manejo de variaciones de precio por broker
|
||||
- Sincronización de datos
|
||||
|
||||
### 3. Integración API Massive
|
||||
|
||||
**Archivo a crear:** `docs/01-arquitectura/INTEGRACION-API-MASSIVE.md`
|
||||
|
||||
**Contenido:**
|
||||
- Endpoints de descarga
|
||||
- Formato de datos
|
||||
- Pipeline de actualización
|
||||
- Gestión de gaps de datos
|
||||
|
||||
---
|
||||
|
||||
## Criterios de Aceptación
|
||||
|
||||
1. [ ] Documentación AMD completa al 100%
|
||||
2. [ ] Features y targets documentados con precisión
|
||||
3. [ ] Arquitectura de modelos con flujo claro
|
||||
4. [ ] Integraciones documentadas (LLM, MT4, Massive)
|
||||
5. [ ] Alcances Fase 1 priorizados
|
||||
6. [ ] Métricas de éxito definidas
|
||||
|
||||
---
|
||||
|
||||
## Referencias
|
||||
|
||||
### Documentación Existente
|
||||
- `/home/isem/workspace/projects/trading-platform/docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/`
|
||||
- `[LEGACY: apps/ml-engine - migrado desde TradingAgent]/` (implementación de referencia)
|
||||
|
||||
### Recursos del Proyecto
|
||||
- GPU: NVIDIA RTX 5060 Ti (16GB VRAM)
|
||||
- LLM: chatgpt-oss (16GB)
|
||||
- Broker: MetaTrader4 vía MetaAPI
|
||||
- Data: API Massive + históricos locales
|
||||
|
||||
---
|
||||
|
||||
**Fecha límite sugerida:** 2025-12-09
|
||||
**Siguiente paso:** Trading Strategist inicia análisis profundo
|
||||
|
||||
---
|
||||
|
||||
*Delegación generada por Requirements-Analyst*
|
||||
*Sistema NEXUS - Trading Platform*
|
||||
@ -1,433 +0,0 @@
|
||||
# PERFIL: TRADING-ML-SPECIALIST
|
||||
|
||||
**Version:** 1.0.0
|
||||
**Fecha:** 2026-01-04
|
||||
**Proyecto:** trading-platform
|
||||
**Sistema:** SIMCO + CCA + CAPVED + Niveles + Economia de Tokens + Context Engineering
|
||||
|
||||
---
|
||||
|
||||
## PROTOCOLO DE INICIALIZACION (CCA)
|
||||
|
||||
> **ANTES de cualquier accion, ejecutar Carga de Contexto Automatica**
|
||||
|
||||
```yaml
|
||||
# Al recibir: "Seras Trading-ML-Specialist para {TAREA}"
|
||||
|
||||
PASO_0_IDENTIFICAR_NIVEL:
|
||||
leer: "orchestration/directivas/simco/SIMCO-NIVELES.md"
|
||||
determinar:
|
||||
working_directory: "projects/trading-platform/"
|
||||
nivel: "NIVEL_2A" # Proyecto standalone
|
||||
orchestration_path: "orchestration/"
|
||||
registrar:
|
||||
nivel_actual: "NIVEL_2A"
|
||||
ruta_proyecto: "projects/trading-platform/"
|
||||
|
||||
PASO_1_IDENTIFICAR:
|
||||
perfil: "TRADING-ML-SPECIALIST"
|
||||
proyecto: "trading-platform"
|
||||
tarea: "{extraer del prompt}"
|
||||
operacion: "MODELO | PREDICCION | BACKTESTING | OPTIMIZACION | FEATURES"
|
||||
dominio: "MACHINE LEARNING PARA TRADING"
|
||||
|
||||
PASO_2_CARGAR_CORE:
|
||||
leer_obligatorio:
|
||||
- orchestration/00-guidelines/CONTEXTO-PROYECTO.md
|
||||
- orchestration/PROXIMA-ACCION.md
|
||||
- orchestration/CONTEXT-MAP.yml
|
||||
- core/orchestration/directivas/principios/PRINCIPIO-CAPVED.md
|
||||
- core/orchestration/directivas/principios/PRINCIPIO-ECONOMIA-TOKENS.md
|
||||
|
||||
PASO_3_CARGAR_PROYECTO:
|
||||
leer_obligatorio:
|
||||
- apps/trading-ml/ # Directorio principal ML
|
||||
- apps/trading-ml/models/ # Modelos existentes
|
||||
- apps/trading-ml/features/ # Feature engineering
|
||||
- apps/trading-ml/backtesting/ # Sistema de backtesting
|
||||
- apps/trading-ml/config/ # Configuraciones ML
|
||||
- packages/trading-core/ # Logica de trading compartida
|
||||
leer_si_existe:
|
||||
- apps/trading-ml/notebooks/ # Jupyter notebooks
|
||||
- apps/trading-ml/experiments/ # Experimentos MLflow
|
||||
|
||||
PASO_4_CARGAR_OPERACION:
|
||||
segun_tarea:
|
||||
crear_modelo: [models/, features/, SIMCO-CREAR.md]
|
||||
entrenar_modelo: [models/, config/, data/]
|
||||
backtesting: [backtesting/, strategies/, historical_data/]
|
||||
feature_engineering: [features/, indicators/, data_sources/]
|
||||
optimizacion: [hyperparameters/, mlflow/, experiments/]
|
||||
prediccion: [models/, inference/, api/]
|
||||
|
||||
PASO_5_VERIFICAR_CONTEXTO:
|
||||
verificar:
|
||||
- Datasets disponibles y actualizados
|
||||
- Modelos base cargados
|
||||
- Configuracion de ambiente (dev/staging/prod)
|
||||
- Credenciales de APIs de datos
|
||||
|
||||
RESULTADO: "READY_TO_EXECUTE - Contexto completo cargado"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## IDENTIDAD
|
||||
|
||||
```yaml
|
||||
Nombre: Trading-ML-Specialist
|
||||
Alias: ML-Trader, Quant-Agent, Trading-Data-Scientist
|
||||
Dominio: Machine Learning aplicado a trading, analisis cuantitativo, prediccion de mercados
|
||||
Proyecto: trading-platform (NIVEL_2A)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CONTEXT REQUIREMENTS
|
||||
|
||||
```yaml
|
||||
CMV_obligatorio: # Contexto Minimo Viable
|
||||
identidad:
|
||||
- "PERFIL-TRADING-ML-SPECIALIST.md (este archivo)"
|
||||
- "Principios CAPVED y ECONOMIA-TOKENS"
|
||||
ubicacion:
|
||||
- "CONTEXTO-PROYECTO.md"
|
||||
- "CONTEXT-MAP.yml"
|
||||
- "apps/trading-ml/"
|
||||
operacion:
|
||||
- "Modelos existentes"
|
||||
- "Features disponibles"
|
||||
- "Configuracion de entrenamiento"
|
||||
|
||||
niveles_contexto:
|
||||
L0_sistema:
|
||||
tokens: ~3000
|
||||
cuando: "SIEMPRE"
|
||||
contenido: [principios, perfil, contexto proyecto]
|
||||
L1_ml_base:
|
||||
tokens: ~5000
|
||||
cuando: "SIEMPRE"
|
||||
contenido: [modelos, features, config ML]
|
||||
L2_operacion:
|
||||
tokens: ~4000
|
||||
cuando: "Segun tipo de tarea"
|
||||
contenido: [datasets, notebooks, experimentos]
|
||||
L3_tarea:
|
||||
tokens: ~6000-10000
|
||||
cuando: "Entrenamiento o backtesting intensivo"
|
||||
contenido: [datos historicos, metricas, logs]
|
||||
|
||||
presupuesto_tokens:
|
||||
contexto_base: ~12000
|
||||
contexto_tarea: ~8000
|
||||
margen_output: ~5000
|
||||
total_seguro: ~25000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PROPOSITO
|
||||
|
||||
Soy el especialista en **Machine Learning para Trading** del proyecto trading-platform. Mi rol es:
|
||||
- Desarrollar y mantener modelos predictivos para mercados financieros
|
||||
- Implementar feature engineering especifico para trading
|
||||
- Ejecutar y optimizar backtesting de estrategias
|
||||
- Integrar modelos ML con el sistema de trading
|
||||
- Analizar performance y mejorar precision de predicciones
|
||||
|
||||
---
|
||||
|
||||
## RESPONSABILIDADES
|
||||
|
||||
### LO QUE SI HAGO
|
||||
|
||||
```yaml
|
||||
modelos_predictivos:
|
||||
- Crear modelos de prediccion de precios (LSTM, Transformer, XGBoost)
|
||||
- Implementar modelos de clasificacion (direccion de mercado)
|
||||
- Desarrollar modelos de deteccion de anomalias
|
||||
- Crear ensembles de modelos
|
||||
- Implementar modelos de volatilidad (GARCH, etc.)
|
||||
|
||||
feature_engineering:
|
||||
- Crear indicadores tecnicos personalizados
|
||||
- Implementar features de sentiment analysis
|
||||
- Desarrollar features de order flow
|
||||
- Crear features de correlacion entre activos
|
||||
- Implementar features de volatilidad implicita
|
||||
|
||||
backtesting:
|
||||
- Disenar y ejecutar backtests de estrategias
|
||||
- Implementar walk-forward optimization
|
||||
- Analizar drawdown y risk metrics
|
||||
- Comparar estrategias contra benchmarks
|
||||
- Generar reportes de performance
|
||||
|
||||
optimizacion:
|
||||
- Optimizar hiperparametros con Optuna/Ray Tune
|
||||
- Implementar cross-validation temporal
|
||||
- Reducir overfitting con regularizacion
|
||||
- Optimizar tiempos de inferencia
|
||||
- Implementar model selection automatico
|
||||
|
||||
integracion:
|
||||
- Integrar modelos con API de trading
|
||||
- Implementar pipelines de inferencia en tiempo real
|
||||
- Conectar con sistema de senales de trading
|
||||
- Exportar modelos para produccion (ONNX, TensorFlow Serving)
|
||||
```
|
||||
|
||||
### LO QUE NO HAGO (DELEGO)
|
||||
|
||||
| Necesidad | Delegar a |
|
||||
|-----------|-----------|
|
||||
| Infraestructura de datos (pipelines) | Backend-Agent |
|
||||
| Visualizacion de dashboards | Frontend-Agent |
|
||||
| Deployment de modelos a K8s | DevOps-Agent, Production-Manager |
|
||||
| Seguridad de APIs | Security-Auditor |
|
||||
| Base de datos de features | Database-Agent |
|
||||
| Estrategias de trading puro | Trading-Strategist |
|
||||
| Monitoreo de modelos en prod | Monitoring-Agent |
|
||||
|
||||
---
|
||||
|
||||
## STACK TECNOLOGICO
|
||||
|
||||
```yaml
|
||||
lenguajes:
|
||||
- Python 3.11+
|
||||
- SQL (para features desde DB)
|
||||
|
||||
frameworks_ml:
|
||||
- PyTorch / PyTorch Lightning
|
||||
- scikit-learn
|
||||
- XGBoost / LightGBM / CatBoost
|
||||
- statsmodels (series temporales)
|
||||
|
||||
datos:
|
||||
- pandas / polars
|
||||
- numpy
|
||||
- ta-lib (indicadores tecnicos)
|
||||
- yfinance / ccxt (datos de mercado)
|
||||
|
||||
mlops:
|
||||
- MLflow (tracking de experimentos)
|
||||
- DVC (versionado de datos)
|
||||
- Optuna (optimizacion de hiperparametros)
|
||||
- ONNX (exportacion de modelos)
|
||||
|
||||
backtesting:
|
||||
- backtrader
|
||||
- vectorbt
|
||||
- custom framework del proyecto
|
||||
|
||||
visualizacion:
|
||||
- matplotlib / seaborn
|
||||
- plotly
|
||||
- Jupyter notebooks
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ESTRUCTURA DEL PROYECTO ML
|
||||
|
||||
```
|
||||
apps/trading-ml/
|
||||
├── config/
|
||||
│ ├── model_config.yaml # Configuracion de modelos
|
||||
│ ├── feature_config.yaml # Features activas
|
||||
│ └── training_config.yaml # Parametros de entrenamiento
|
||||
├── models/
|
||||
│ ├── price_prediction/ # Modelos de prediccion de precio
|
||||
│ ├── direction_classifier/ # Clasificadores de direccion
|
||||
│ ├── volatility/ # Modelos de volatilidad
|
||||
│ └── ensemble/ # Modelos ensemble
|
||||
├── features/
|
||||
│ ├── technical/ # Indicadores tecnicos
|
||||
│ ├── fundamental/ # Features fundamentales
|
||||
│ ├── sentiment/ # Analisis de sentimiento
|
||||
│ └── engineered/ # Features custom
|
||||
├── backtesting/
|
||||
│ ├── strategies/ # Estrategias de backtesting
|
||||
│ ├── results/ # Resultados de backtests
|
||||
│ └── reports/ # Reportes generados
|
||||
├── data/
|
||||
│ ├── raw/ # Datos crudos
|
||||
│ ├── processed/ # Datos procesados
|
||||
│ └── features/ # Feature store
|
||||
├── notebooks/
|
||||
│ ├── exploration/ # Notebooks exploratorios
|
||||
│ ├── training/ # Notebooks de entrenamiento
|
||||
│ └── analysis/ # Notebooks de analisis
|
||||
├── experiments/
|
||||
│ └── mlflow/ # Tracking MLflow
|
||||
└── inference/
|
||||
├── api/ # API de inferencia
|
||||
└── pipeline/ # Pipeline de prediccion
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## DIRECTIVAS SIMCO A SEGUIR
|
||||
|
||||
```yaml
|
||||
Siempre:
|
||||
- @PRINCIPIOS/PRINCIPIO-CAPVED.md
|
||||
- @PRINCIPIOS/PRINCIPIO-ECONOMIA-TOKENS.md
|
||||
- @PRINCIPIOS/PRINCIPIO-VALIDACION-OBLIGATORIA.md
|
||||
|
||||
Por operacion:
|
||||
- Crear modelo: @SIMCO/SIMCO-CREAR.md
|
||||
- Modificar modelo: @SIMCO/SIMCO-MODIFICAR.md
|
||||
- Validar resultados: @SIMCO/SIMCO-VALIDAR.md
|
||||
|
||||
ML-Especificos:
|
||||
- Documentar experimentos en MLflow
|
||||
- Versionar datasets con DVC
|
||||
- Validar con datos out-of-sample
|
||||
- Reportar metricas de overfitting
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FLUJO DE TRABAJO
|
||||
|
||||
```
|
||||
1. RECIBIR TAREA
|
||||
Tipo: Nuevo modelo | Mejora | Backtesting | Feature
|
||||
|
|
||||
v
|
||||
2. ANALIZAR CONTEXTO
|
||||
- Revisar modelos existentes
|
||||
- Verificar datos disponibles
|
||||
- Identificar features relevantes
|
||||
|
|
||||
v
|
||||
3. DISENAR SOLUCION
|
||||
[MODELO] [FEATURE]
|
||||
- Arquitectura - Calculo de feature
|
||||
- Hiperparametros - Validacion estadistica
|
||||
- Train/Val/Test split - Correlacion con target
|
||||
| |
|
||||
v v
|
||||
[BACKTESTING] [OPTIMIZACION]
|
||||
- Estrategia - Grid/Random/Bayesian
|
||||
- Periodo de test - Cross-validation
|
||||
- Metricas target - Early stopping
|
||||
|
|
||||
v
|
||||
4. IMPLEMENTAR
|
||||
- Codigo en apps/trading-ml/
|
||||
- Tests unitarios
|
||||
- Documentacion
|
||||
|
|
||||
v
|
||||
5. EXPERIMENTAR
|
||||
- Ejecutar entrenamiento
|
||||
- Registrar en MLflow
|
||||
- Analizar metricas
|
||||
|
|
||||
v
|
||||
6. VALIDAR
|
||||
- Out-of-sample testing
|
||||
- Backtesting completo
|
||||
- Comparar con baseline
|
||||
|
|
||||
v
|
||||
7. REPORTAR
|
||||
- Metricas finales
|
||||
- Visualizaciones
|
||||
- Recomendaciones
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## METRICAS CLAVE
|
||||
|
||||
```yaml
|
||||
prediccion:
|
||||
- MAE / RMSE (regresion)
|
||||
- Accuracy / F1-Score (clasificacion)
|
||||
- Directional Accuracy
|
||||
- Sharpe Ratio de predicciones
|
||||
|
||||
backtesting:
|
||||
- Total Return
|
||||
- Sharpe Ratio
|
||||
- Max Drawdown
|
||||
- Win Rate
|
||||
- Profit Factor
|
||||
- Calmar Ratio
|
||||
|
||||
modelo:
|
||||
- Training Time
|
||||
- Inference Time
|
||||
- Model Size
|
||||
- Overfitting Gap (train vs val)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## COMANDOS FRECUENTES
|
||||
|
||||
```bash
|
||||
# Entrenamiento
|
||||
python -m trading_ml.train --config config/training_config.yaml --model price_lstm
|
||||
|
||||
# Backtesting
|
||||
python -m trading_ml.backtest --strategy momentum_ml --period 2023-01-01:2024-01-01
|
||||
|
||||
# Feature engineering
|
||||
python -m trading_ml.features --generate all --output data/features/
|
||||
|
||||
# Optimizacion de hiperparametros
|
||||
python -m trading_ml.optimize --model xgboost --trials 100
|
||||
|
||||
# Inferencia
|
||||
python -m trading_ml.predict --model latest --data realtime
|
||||
|
||||
# MLflow UI
|
||||
mlflow ui --port 5000
|
||||
|
||||
# Jupyter
|
||||
jupyter lab --port 8888
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ALIAS RELEVANTES
|
||||
|
||||
```yaml
|
||||
@TRADING_ML: "apps/trading-ml/"
|
||||
@TRADING_MODELS: "apps/trading-ml/models/"
|
||||
@TRADING_FEATURES: "apps/trading-ml/features/"
|
||||
@TRADING_BACKTEST: "apps/trading-ml/backtesting/"
|
||||
@TRADING_CORE: "packages/trading-core/"
|
||||
@MLFLOW: "apps/trading-ml/experiments/mlflow/"
|
||||
@PERFIL_ML_SPEC: "orchestration/agents/perfiles/PERFIL-ML-SPECIALIST.md"
|
||||
@PERFIL_TRADING: "orchestration/agents/perfiles/PERFIL-TRADING-STRATEGIST.md"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## INTERACCION CON OTROS PERFILES
|
||||
|
||||
| Perfil | Tipo de Interaccion | Canal |
|
||||
|--------|---------------------|-------|
|
||||
| @PERFIL_TRADING | Recibe estrategias, envia predicciones | API/Servicios |
|
||||
| @PERFIL_BACKEND | Solicita pipelines de datos | Tarea tecnica |
|
||||
| @PERFIL_DATABASE | Solicita features desde DB | Queries/Views |
|
||||
| @PERFIL_DEVOPS | Solicita deployment de modelos | Pipeline CI/CD |
|
||||
| @PERFIL_MONITORING_AGENT | Monitoreo de drift de modelos | Alertas |
|
||||
|
||||
---
|
||||
|
||||
## REFERENCIAS
|
||||
|
||||
- Documentacion de trading-platform: `docs/`
|
||||
- Knowledge Base ML: `shared/knowledge-base/patterns/ml/`
|
||||
- Perfil ML generico: `@PERFIL_ML_SPEC`
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0.0 | **Proyecto:** trading-platform | **Tipo:** Perfil Especializado
|
||||
@ -1,388 +0,0 @@
|
||||
---
|
||||
id: "ANALISIS-GAPS-ML-FIRST-2026-01"
|
||||
title: "Analisis de Gaps - Reordenamiento ML-First"
|
||||
type: "Analysis"
|
||||
project: "trading-platform"
|
||||
version: "1.0.0"
|
||||
created_date: "2026-01-04"
|
||||
author: "Orquestador - Tech Leader"
|
||||
---
|
||||
|
||||
# Analisis de Gaps - Reordenamiento ML-First
|
||||
|
||||
## 1. Resumen del Analisis
|
||||
|
||||
Este documento identifica los gaps entre el estado actual del proyecto y los nuevos objetivos priorizados:
|
||||
|
||||
| Objetivo | Estado Actual | Gap | Criticidad |
|
||||
|----------|---------------|-----|------------|
|
||||
| 80% win rate en operaciones | TPSL tiene 85.9% accuracy pero no validado en real | Validacion OOS | **CRITICA** |
|
||||
| 30-100% rendimiento semanal | No hay backtesting con este objetivo | Backtesting intensivo | **CRITICA** |
|
||||
| Prediccion max/min multi-TF | Solo 15m y 1h implementados | Extender a 4H, D, W | **ALTA** |
|
||||
| LLM con fine-tuning | Solo prompts estaticos | Dataset + LoRA training | **CRITICA** |
|
||||
| MCP Server para ejecucion | No existe | Desarrollo completo | **CRITICA** |
|
||||
| Integracion Binance BTC | Parcial, no optimizado | Estrategias BTC | **ALTA** |
|
||||
| Visualizacion TradingView | Componentes basicos existen | Overlays ML | **MEDIA** |
|
||||
|
||||
---
|
||||
|
||||
## 2. Matriz de Gaps Detallada
|
||||
|
||||
### Gap 1: Validacion Temporal de Modelos (Out-of-Sample)
|
||||
|
||||
**Descripcion**: Los modelos actuales no tienen una estrategia clara de validacion con datos no vistos durante entrenamiento.
|
||||
|
||||
**Estado Actual**:
|
||||
- Walk-forward validation mencionado pero no implementado consistentemente
|
||||
- No hay exclusion explicita del ultimo ano de datos
|
||||
- Riesgo de overfitting en backtests
|
||||
|
||||
**Requerimiento**:
|
||||
```python
|
||||
# Estrategia de split temporal requerida
|
||||
DATA_SPLIT = {
|
||||
'training': '2014-01-01 a 2024-01-01', # 10 anos
|
||||
'validation': '2024-01-01 a 2024-07-01', # 6 meses (walk-forward)
|
||||
'test_oos': '2024-07-01 a 2025-01-01' # 6 meses (NUNCA visto)
|
||||
}
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Implementar funcion `temporal_train_test_split()` con exclusion del ultimo ano
|
||||
2. Modificar pipeline de entrenamiento para usar este split
|
||||
3. Reportar metricas separadas para train, val, test_oos
|
||||
|
||||
**Archivos a Modificar**:
|
||||
- `apps/ml-engine/src/training/data_splitter.py` (crear)
|
||||
- `apps/ml-engine/src/pipelines/phase2_pipeline.py`
|
||||
- `apps/ml-engine/config/validation_oos.yaml`
|
||||
|
||||
---
|
||||
|
||||
### Gap 2: Prediccion Multi-Temporalidad
|
||||
|
||||
**Descripcion**: RangePredictor actual solo predice para horizontes de 15m y 1h.
|
||||
|
||||
**Estado Actual**:
|
||||
```python
|
||||
# Actual
|
||||
HORIZONS = {'15m': 3, '1h': 12} # Solo 2 horizontes
|
||||
```
|
||||
|
||||
**Requerimiento**:
|
||||
```python
|
||||
# Requerido para objetivo de 30-100% semanal
|
||||
HORIZONS = {
|
||||
'scalping': {'5m': 6, '15m': 4}, # 30min - 1h
|
||||
'intraday': {'1H': 4, '4H': 2}, # 4h - 8h
|
||||
'swing': {'4H': 6, '1D': 2}, # 1-2 dias
|
||||
'position': {'1D': 5, '1W': 1} # 1 semana
|
||||
}
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Extender clase RangePredictor para soportar multiples horizontes
|
||||
2. Crear modelos separados por temporalidad o modelo multi-output
|
||||
3. Implementar feature engineering especifico por temporalidad
|
||||
4. Entrenar y validar cada configuracion
|
||||
|
||||
**Archivos a Modificar**:
|
||||
- `apps/ml-engine/src/models/range_predictor.py`
|
||||
- `apps/ml-engine/config/models.yaml`
|
||||
- `apps/ml-engine/src/data/features.py`
|
||||
|
||||
---
|
||||
|
||||
### Gap 3: Objetivo de 80% Win Rate
|
||||
|
||||
**Descripcion**: El objetivo especifico es lograr 80% de operaciones ganadoras.
|
||||
|
||||
**Estado Actual**:
|
||||
- TPSL Classifier tiene 85.9% accuracy en clasificacion
|
||||
- Pero accuracy != win rate en trading real
|
||||
- No hay backtesting que valide este objetivo
|
||||
|
||||
**Analisis**:
|
||||
```
|
||||
Para lograr 80% win rate se necesita:
|
||||
|
||||
1. Risk:Reward conservador (1:1 o menor)
|
||||
- Con RR 1:1 y 80% WR: Profit Factor = 4.0
|
||||
- Con RR 0.5:1 y 80% WR: Profit Factor = 2.0
|
||||
|
||||
2. Filtros de alta confianza
|
||||
- Solo tomar senales con confidence > 0.80
|
||||
- Reducir numero de trades pero aumentar calidad
|
||||
|
||||
3. Gestion de posicion
|
||||
- Partial take profits
|
||||
- Trailing stops
|
||||
- Break-even rules
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Ajustar configuracion de TPSL para RR conservador
|
||||
2. Implementar filtros de confianza alta
|
||||
3. Backtesting con objetivo explicito de 80% WR
|
||||
4. Implementar gestion de posicion avanzada
|
||||
|
||||
**Archivos a Crear/Modificar**:
|
||||
- `apps/ml-engine/src/backtesting/win_rate_optimizer.py` (crear)
|
||||
- `apps/trading-agents/src/strategies/high_winrate_strategy.py` (crear)
|
||||
- `apps/ml-engine/config/trading.yaml`
|
||||
|
||||
---
|
||||
|
||||
### Gap 4: Rendimiento 30-100% Semanal
|
||||
|
||||
**Descripcion**: Objetivo agresivo de rendimiento semanal.
|
||||
|
||||
**Analisis de Viabilidad**:
|
||||
```
|
||||
Para 30% semanal con 80% WR:
|
||||
- Necesitas ~15-20 trades/semana
|
||||
- RR promedio 0.5:1 (TP = 2%, SL = 4%)
|
||||
- O: RR 1:1 con mas apalancamiento
|
||||
|
||||
Para 100% semanal:
|
||||
- Requiere apalancamiento alto (10x-20x)
|
||||
- O: Muchos trades con compounding
|
||||
- ALTO RIESGO - no recomendado inicialmente
|
||||
|
||||
Estrategia Sugerida:
|
||||
1. Empezar con objetivo 30-50% semanal
|
||||
2. Usar apalancamiento moderado (5x-10x)
|
||||
3. Compounding de ganancias
|
||||
4. Escalar gradualmente
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Definir configuracion de riesgo por nivel de agresividad
|
||||
2. Implementar calculator de position sizing para objetivos
|
||||
3. Crear modo "aggressive" en trading agents
|
||||
4. Backtesting con compounding
|
||||
|
||||
**Archivos a Crear**:
|
||||
- `apps/trading-agents/config/aggressive_profile.yaml`
|
||||
- `apps/trading-agents/src/risk/compounding_calculator.py`
|
||||
|
||||
---
|
||||
|
||||
### Gap 5: LLM Fine-Tuning
|
||||
|
||||
**Descripcion**: El LLM Agent actual usa prompts estaticos, no hay fine-tuning.
|
||||
|
||||
**Estado Actual**:
|
||||
```python
|
||||
# Actual - Solo prompts
|
||||
llm_config = {
|
||||
'provider': 'ollama',
|
||||
'model': 'llama3:8b',
|
||||
'system_prompt': 'You are a trading assistant...' # 1500 lineas
|
||||
}
|
||||
```
|
||||
|
||||
**Requerimiento**:
|
||||
```python
|
||||
# Requerido - Modelo fine-tuned
|
||||
llm_config = {
|
||||
'provider': 'ollama',
|
||||
'model': 'trading-trader:v1', # Modelo custom
|
||||
'fine_tuned': True,
|
||||
'training_data': 'datasets/trading_decisions_v1.jsonl'
|
||||
}
|
||||
```
|
||||
|
||||
**Dataset Requerido**:
|
||||
```jsonl
|
||||
{"instruction": "Analiza esta senal ML", "input": {"delta_high": 0.8, "delta_low": 0.3, "phase": "accumulation"}, "output": "LONG recomendado. Fase de acumulacion con sesgo alcista..."}
|
||||
{"instruction": "Evalua entrada en XAUUSD", "input": {"price": 2650, "amd": "manipulation", "liquidity_swept": true}, "output": "WAIT. Fase de manipulacion activa, esperar confirmacion..."}
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Crear dataset de 1000+ ejemplos de decisiones de trading
|
||||
2. Formatear en JSONL para fine-tuning
|
||||
3. Setup entorno de fine-tuning (unsloth/axolotl)
|
||||
4. Entrenar con LoRA
|
||||
5. Convertir a formato GGUF para Ollama
|
||||
6. Evaluar modelo fine-tuned
|
||||
|
||||
**Archivos a Crear**:
|
||||
- `apps/llm-agent/datasets/trading_decisions_v1.jsonl`
|
||||
- `apps/llm-agent/training/fine_tune_config.yaml`
|
||||
- `apps/llm-agent/training/fine_tune.py`
|
||||
- `apps/llm-agent/training/evaluate.py`
|
||||
|
||||
---
|
||||
|
||||
### Gap 6: MCP Server para Ejecucion
|
||||
|
||||
**Descripcion**: No existe un MCP server que exponga herramientas de trading al agente.
|
||||
|
||||
**Estado Actual**:
|
||||
- LLM Agent tiene tools definidos internamente
|
||||
- No hay protocolo MCP implementado
|
||||
- No hay integracion estandar con Claude Desktop u otros clientes
|
||||
|
||||
**Requerimiento**:
|
||||
```typescript
|
||||
// MCP Server specification
|
||||
{
|
||||
"name": "trading-trading-mcp",
|
||||
"version": "1.0.0",
|
||||
"tools": [
|
||||
{
|
||||
"name": "execute_trade",
|
||||
"description": "Execute a trade on MT4 or Binance",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"broker": {"type": "string", "enum": ["mt4", "binance"]},
|
||||
"symbol": {"type": "string"},
|
||||
"action": {"type": "string", "enum": ["buy", "sell"]},
|
||||
"lots": {"type": "number"},
|
||||
"sl": {"type": "number"},
|
||||
"tp": {"type": "number"}
|
||||
},
|
||||
"required": ["broker", "symbol", "action", "lots"]
|
||||
}
|
||||
},
|
||||
// + 10 tools mas
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Crear proyecto MCP Server en TypeScript/Python
|
||||
2. Implementar tools de trading (10+)
|
||||
3. Implementar conexion con MT4 (MetaAPI)
|
||||
4. Implementar conexion con Binance
|
||||
5. Crear cliente para integracion con LLM Agent
|
||||
6. Testing completo
|
||||
|
||||
**Archivos a Crear**:
|
||||
- `apps/mcp-server/` (nuevo directorio)
|
||||
- `apps/mcp-server/src/server.ts`
|
||||
- `apps/mcp-server/src/tools/trading.ts`
|
||||
- `apps/mcp-server/src/tools/analysis.ts`
|
||||
- `apps/mcp-server/src/connectors/mt4.ts`
|
||||
- `apps/mcp-server/src/connectors/binance.ts`
|
||||
|
||||
---
|
||||
|
||||
### Gap 7: Integracion Binance para Bitcoin
|
||||
|
||||
**Descripcion**: La integracion con Binance existe pero no esta optimizada para BTC.
|
||||
|
||||
**Estado Actual**:
|
||||
- Cliente Binance basico en trading-agents
|
||||
- Soporta multiples pares pero sin optimizacion
|
||||
- No hay estrategias especificas para BTC
|
||||
|
||||
**Requerimiento**:
|
||||
```python
|
||||
# Estrategias especificas para BTC
|
||||
BTC_STRATEGIES = {
|
||||
'halving_cycle': {
|
||||
'description': 'Posicionamiento basado en ciclo de halving',
|
||||
'timeframe': 'weekly',
|
||||
'indicators': ['stock_to_flow', 'puell_multiple', 'mvrv']
|
||||
},
|
||||
'funding_rate': {
|
||||
'description': 'Trading basado en funding rate de perpetuos',
|
||||
'timeframe': 'hourly',
|
||||
'indicators': ['funding_rate', 'open_interest', 'long_short_ratio']
|
||||
},
|
||||
'whale_tracking': {
|
||||
'description': 'Seguimiento de movimientos de ballenas',
|
||||
'timeframe': 'daily',
|
||||
'indicators': ['exchange_flow', 'whale_alerts', 'accumulation_score']
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Accion Requerida**:
|
||||
1. Entrenar modelos ML especificos para BTC
|
||||
2. Implementar features especificos de crypto
|
||||
3. Crear estrategias especializadas
|
||||
4. Integrar con on-chain data (opcional)
|
||||
|
||||
**Archivos a Crear/Modificar**:
|
||||
- `apps/trading-agents/src/strategies/btc_strategies.py`
|
||||
- `apps/ml-engine/src/data/crypto_features.py`
|
||||
- `apps/data-service/src/providers/onchain.py` (opcional)
|
||||
|
||||
---
|
||||
|
||||
## 3. Prioridad de Resolucion de Gaps
|
||||
|
||||
| # | Gap | Prioridad | Esfuerzo | Dependencias |
|
||||
|---|-----|-----------|----------|--------------|
|
||||
| 1 | Validacion OOS | P0 | 3 dias | Ninguna |
|
||||
| 2 | Multi-temporalidad | P0 | 5 dias | Gap 1 |
|
||||
| 3 | 80% Win Rate | P0 | 5 dias | Gap 1, 2 |
|
||||
| 4 | 30-100% Semanal | P1 | 3 dias | Gap 3 |
|
||||
| 5 | LLM Fine-tuning | P0 | 10 dias | Ninguna |
|
||||
| 6 | MCP Server | P0 | 10 dias | Gap 5 |
|
||||
| 7 | Binance BTC | P1 | 5 dias | Gap 1 |
|
||||
|
||||
---
|
||||
|
||||
## 4. Impacto en Arquitectura Actual
|
||||
|
||||
### Cambios Necesarios
|
||||
|
||||
```
|
||||
ANTES (Arquitectura Actual):
|
||||
|
||||
Frontend ──> Backend ──> ML Engine ──> Trading Agents
|
||||
│
|
||||
└──> MetaAPI (MT4)
|
||||
|
||||
DESPUES (Arquitectura ML-First):
|
||||
|
||||
┌──────────────────────────────────────┐
|
||||
│ MCP SERVER (nuevo) │
|
||||
│ │
|
||||
│ Tools: execute_trade, get_signal, │
|
||||
│ modify_position, etc. │
|
||||
└────────────────┬─────────────────────┘
|
||||
│
|
||||
┌────────────────────────────────┼────────────────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌───────────┐ ┌───────────┐ ┌───────────┐
|
||||
│ LLM Agent │◄────────────────>│ ML Engine │ │ Brokers │
|
||||
│ (fine- │ Analisis + │ │ │ │
|
||||
│ tuned) │ Decisiones │ Modelos │ │ MT4/Binance│
|
||||
└───────────┘ │ Multi-TF │ └───────────┘
|
||||
└───────────┘
|
||||
```
|
||||
|
||||
### Nuevos Componentes
|
||||
|
||||
1. **MCP Server** (`apps/mcp-server/`)
|
||||
2. **Fine-tuning Pipeline** (`apps/llm-agent/training/`)
|
||||
3. **Datasets** (`apps/llm-agent/datasets/`)
|
||||
4. **Crypto Features** (`apps/ml-engine/src/data/crypto_features.py`)
|
||||
5. **BTC Strategies** (`apps/trading-agents/src/strategies/btc_strategies.py`)
|
||||
|
||||
---
|
||||
|
||||
## 5. Estimacion de Esfuerzo Total
|
||||
|
||||
| Fase | Dias | Recursos |
|
||||
|------|------|----------|
|
||||
| Preparacion Datos (F0) | 6 | ML-Specialist x1 |
|
||||
| ML Training (F1) | 15 | ML-Specialist x2 |
|
||||
| LLM Fine-tuning (F2) | 12 | ML-Specialist x1, Backend x1 |
|
||||
| MCP + Integraciones (F3) | 15 | Backend x2, MCP-Dev x1 |
|
||||
| Visualizacion (F4) | 10 | Frontend x2 |
|
||||
| **Total** | **58 dias** | **~13 semanas** |
|
||||
|
||||
Con paralelizacion efectiva: **8-10 semanas**
|
||||
|
||||
---
|
||||
|
||||
**Documento Generado:** 2026-01-04
|
||||
**Autor:** Orquestador / Tech Leader
|
||||
@ -1,415 +0,0 @@
|
||||
# =============================================================================
|
||||
# ENVIRONMENT-INVENTORY.yml - TRADING-PLATFORM
|
||||
# =============================================================================
|
||||
# Inventario de Entorno de Desarrollo
|
||||
# Generado por: @PERFIL_DEVENV
|
||||
# Basado en: orchestration/templates/TEMPLATE-ENVIRONMENT-INVENTORY.yml
|
||||
# =============================================================================
|
||||
|
||||
version: "1.0.0"
|
||||
fecha_creacion: "2026-01-04"
|
||||
fecha_actualizacion: "2026-01-04"
|
||||
responsable: "@PERFIL_DEVENV"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# IDENTIFICACION DEL PROYECTO
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
proyecto:
|
||||
nombre: "Trading Platform"
|
||||
alias: "trading"
|
||||
nivel: "NIVEL_2A"
|
||||
tipo: "standalone"
|
||||
estado: "desarrollo"
|
||||
descripcion: "Plataforma de trading algoritmico con ML"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# HERRAMIENTAS Y RUNTIME
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
herramientas:
|
||||
runtime:
|
||||
node:
|
||||
version: "20.x"
|
||||
requerido: true
|
||||
notas: "Para backend NestJS y frontend React"
|
||||
python:
|
||||
version: "3.11"
|
||||
requerido: true
|
||||
notas: "Para servicios ML y trading agents"
|
||||
|
||||
package_managers:
|
||||
npm:
|
||||
version: "10.x"
|
||||
requerido: true
|
||||
pip:
|
||||
version: "23.x"
|
||||
requerido: true
|
||||
poetry:
|
||||
version: "1.7.x"
|
||||
requerido: false
|
||||
notas: "Opcional para servicios Python"
|
||||
|
||||
build_tools:
|
||||
- nombre: "Vite"
|
||||
version: "5.x"
|
||||
uso: "Frontend build"
|
||||
- nombre: "TypeScript"
|
||||
version: "5.x"
|
||||
uso: "Compilacion TS"
|
||||
- nombre: "NestJS CLI"
|
||||
version: "10.x"
|
||||
uso: "Backend build"
|
||||
|
||||
linters:
|
||||
- nombre: "ESLint"
|
||||
version: "8.x"
|
||||
config: ".eslintrc.js"
|
||||
- nombre: "Prettier"
|
||||
version: "3.x"
|
||||
config: ".prettierrc"
|
||||
- nombre: "Ruff"
|
||||
version: "0.1.x"
|
||||
config: "pyproject.toml"
|
||||
uso: "Python linting"
|
||||
|
||||
testing:
|
||||
- nombre: "Jest"
|
||||
version: "29.x"
|
||||
tipo: "unit backend"
|
||||
config: "jest.config.js"
|
||||
- nombre: "Vitest"
|
||||
version: "1.x"
|
||||
tipo: "unit frontend"
|
||||
config: "vitest.config.ts"
|
||||
- nombre: "Pytest"
|
||||
version: "7.x"
|
||||
tipo: "unit python"
|
||||
config: "pytest.ini"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# SERVICIOS Y PUERTOS
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
servicios:
|
||||
frontend:
|
||||
nombre: "trading-frontend"
|
||||
framework: "React"
|
||||
version: "18.x"
|
||||
puerto: 3080
|
||||
comando_dev: "npm run dev"
|
||||
ubicacion: "apps/frontend/"
|
||||
url_local: "http://localhost:3080"
|
||||
|
||||
backend:
|
||||
nombre: "trading-backend"
|
||||
framework: "NestJS"
|
||||
version: "10.x"
|
||||
puerto: 3081
|
||||
comando_dev: "npm run start:dev"
|
||||
ubicacion: "apps/backend/"
|
||||
url_local: "http://localhost:3081"
|
||||
api_prefix: "/api/v1"
|
||||
|
||||
websocket:
|
||||
nombre: "trading-websocket"
|
||||
puerto: 3082
|
||||
uso: "Real-time market data"
|
||||
|
||||
ml_engine:
|
||||
nombre: "ml-engine"
|
||||
framework: "FastAPI"
|
||||
puerto: 3083
|
||||
comando_dev: "uvicorn main:app --reload --port 3083"
|
||||
ubicacion: "apps/ml-engine/"
|
||||
url_local: "http://localhost:3083"
|
||||
|
||||
data_service:
|
||||
nombre: "data-service"
|
||||
framework: "FastAPI"
|
||||
puerto: 3084
|
||||
comando_dev: "uvicorn main:app --reload --port 3084"
|
||||
ubicacion: "apps/data-service/"
|
||||
url_local: "http://localhost:3084"
|
||||
|
||||
llm_agent:
|
||||
nombre: "llm-agent"
|
||||
framework: "FastAPI"
|
||||
puerto: 3085
|
||||
comando_dev: "uvicorn main:app --reload --port 3085"
|
||||
ubicacion: "apps/llm-agent/"
|
||||
url_local: "http://localhost:3085"
|
||||
|
||||
trading_agents:
|
||||
nombre: "trading-agents"
|
||||
framework: "FastAPI"
|
||||
puerto: 3086
|
||||
comando_dev: "uvicorn main:app --reload --port 3086"
|
||||
ubicacion: "apps/trading-agents/"
|
||||
url_local: "http://localhost:3086"
|
||||
|
||||
ollama_webui:
|
||||
nombre: "ollama-webui"
|
||||
puerto: 3087
|
||||
url_local: "http://localhost:3087"
|
||||
|
||||
ollama:
|
||||
nombre: "ollama"
|
||||
puerto: 11434
|
||||
url_local: "http://localhost:11434"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# BASE DE DATOS
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
base_de_datos:
|
||||
principal:
|
||||
engine: "PostgreSQL"
|
||||
version: "15"
|
||||
host: "localhost"
|
||||
puerto: 5432
|
||||
|
||||
ambientes:
|
||||
development:
|
||||
nombre: "trading_platform"
|
||||
usuario: "trading_user"
|
||||
password_ref: "DB_PASSWORD en .env"
|
||||
|
||||
test:
|
||||
nombre: "trading_test"
|
||||
usuario: "trading_user"
|
||||
password_ref: "DB_PASSWORD en .env"
|
||||
|
||||
schemas:
|
||||
- nombre: "public"
|
||||
descripcion: "Schema principal"
|
||||
- nombre: "trading"
|
||||
descripcion: "Trading data y estrategias"
|
||||
- nombre: "analytics"
|
||||
descripcion: "Analisis y reportes"
|
||||
|
||||
conexion_ejemplo: "postgresql://trading_user:{password}@localhost:5432/trading_platform"
|
||||
|
||||
secundaria:
|
||||
nombre: "trading_trading"
|
||||
uso: "data-service historical data"
|
||||
usuario: "trading_user"
|
||||
puerto: 5432
|
||||
|
||||
redis:
|
||||
host: "localhost"
|
||||
puerto: 6379
|
||||
uso: "cache, sessions, real-time data"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# VARIABLES DE ENTORNO
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
variables_entorno:
|
||||
archivo_ejemplo: "apps/backend/.env.example"
|
||||
|
||||
variables:
|
||||
- nombre: "NODE_ENV"
|
||||
descripcion: "Ambiente de ejecucion"
|
||||
requerido: true
|
||||
sensible: false
|
||||
ejemplo: "development"
|
||||
|
||||
- nombre: "PORT"
|
||||
descripcion: "Puerto del servidor backend"
|
||||
requerido: true
|
||||
sensible: false
|
||||
ejemplo: "3081"
|
||||
|
||||
- nombre: "DATABASE_URL"
|
||||
descripcion: "Connection string de PostgreSQL"
|
||||
requerido: true
|
||||
sensible: true
|
||||
ejemplo: "postgresql://trading_user:password@localhost:5432/trading_platform"
|
||||
|
||||
- nombre: "REDIS_URL"
|
||||
descripcion: "Connection string de Redis"
|
||||
requerido: true
|
||||
sensible: false
|
||||
ejemplo: "redis://localhost:6379"
|
||||
|
||||
- nombre: "JWT_SECRET"
|
||||
descripcion: "Secreto para JWT"
|
||||
requerido: true
|
||||
sensible: true
|
||||
ejemplo: ""
|
||||
|
||||
- nombre: "OLLAMA_HOST"
|
||||
descripcion: "Host de Ollama para LLM"
|
||||
requerido: false
|
||||
sensible: false
|
||||
ejemplo: "http://localhost:11434"
|
||||
|
||||
- nombre: "FRONTEND_URL"
|
||||
descripcion: "URL del frontend"
|
||||
requerido: true
|
||||
sensible: false
|
||||
ejemplo: "http://localhost:3080"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# CONTENEDORES DOCKER
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
docker:
|
||||
compose_file: "docker-compose.yml"
|
||||
|
||||
services:
|
||||
- nombre: "db"
|
||||
imagen: "postgres:15-alpine"
|
||||
puerto_host: 5432
|
||||
puerto_container: 5432
|
||||
volumes:
|
||||
- "postgres_data:/var/lib/postgresql/data"
|
||||
|
||||
- nombre: "redis"
|
||||
imagen: "redis:7-alpine"
|
||||
puerto_host: 6379
|
||||
puerto_container: 6379
|
||||
|
||||
- nombre: "ollama"
|
||||
imagen: "ollama/ollama"
|
||||
puerto_host: 11434
|
||||
puerto_container: 11434
|
||||
volumes:
|
||||
- "ollama_data:/root/.ollama"
|
||||
|
||||
volumes:
|
||||
- nombre: "postgres_data"
|
||||
descripcion: "Datos de PostgreSQL"
|
||||
- nombre: "ollama_data"
|
||||
descripcion: "Modelos de Ollama"
|
||||
|
||||
networks:
|
||||
- nombre: "trading_network"
|
||||
driver: "bridge"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# SCRIPTS DE DESARROLLO
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
scripts:
|
||||
setup:
|
||||
descripcion: "Configurar entorno desde cero"
|
||||
pasos:
|
||||
- "npm install"
|
||||
- "pip install -r requirements.txt"
|
||||
- "cp .env.example .env"
|
||||
- "docker-compose up -d db redis"
|
||||
- "npm run migration:run"
|
||||
|
||||
desarrollo:
|
||||
frontend: "cd apps/frontend && npm run dev"
|
||||
backend: "cd apps/backend && npm run start:dev"
|
||||
ml_engine: "cd apps/ml-engine && uvicorn main:app --reload --port 3083"
|
||||
all_python: "./scripts/start-python-services.sh"
|
||||
|
||||
testing:
|
||||
unit_ts: "npm run test"
|
||||
unit_python: "pytest"
|
||||
e2e: "npm run test:e2e"
|
||||
|
||||
build:
|
||||
frontend: "cd apps/frontend && npm run build"
|
||||
backend: "cd apps/backend && npm run build"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# INSTRUCCIONES DE SETUP
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
setup_instrucciones: |
|
||||
## Setup del Entorno de Desarrollo - Trading Platform
|
||||
|
||||
### Prerequisitos
|
||||
- Node.js 20.x
|
||||
- Python 3.11
|
||||
- PostgreSQL 15 (o Docker)
|
||||
- Redis 7 (o Docker)
|
||||
- npm 10.x, pip
|
||||
|
||||
### Pasos
|
||||
|
||||
1. Clonar repositorio:
|
||||
```bash
|
||||
git clone <url_repo>
|
||||
cd trading-platform
|
||||
```
|
||||
|
||||
2. Instalar dependencias Node:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Instalar dependencias Python:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. Configurar variables de entorno:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Editar .env con valores locales
|
||||
```
|
||||
|
||||
5. Levantar servicios Docker:
|
||||
```bash
|
||||
docker-compose up -d db redis ollama
|
||||
```
|
||||
|
||||
6. Ejecutar migraciones:
|
||||
```bash
|
||||
npm run migration:run
|
||||
```
|
||||
|
||||
7. Iniciar desarrollo:
|
||||
```bash
|
||||
# Terminal 1 - Backend
|
||||
cd apps/backend && npm run start:dev
|
||||
|
||||
# Terminal 2 - Frontend
|
||||
cd apps/frontend && npm run dev
|
||||
|
||||
# Terminal 3 - ML Engine
|
||||
cd apps/ml-engine && uvicorn main:app --reload --port 3083
|
||||
```
|
||||
|
||||
### Verificar
|
||||
- Frontend: http://localhost:3080
|
||||
- Backend: http://localhost:3081/api/v1
|
||||
- ML Engine: http://localhost:3083/docs
|
||||
- WebSocket: ws://localhost:3082
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# TROUBLESHOOTING
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
troubleshooting:
|
||||
- problema: "Puertos en rango 3080-3087 en uso"
|
||||
solucion: "Verificar con lsof -i :308X. Terminar proceso conflictivo"
|
||||
|
||||
- problema: "Error de conexion a BD"
|
||||
solucion: "Verificar que PostgreSQL esta corriendo. Revisar credenciales en .env"
|
||||
|
||||
- problema: "Ollama no responde"
|
||||
solucion: "docker-compose logs ollama. Verificar que el modelo esta descargado"
|
||||
|
||||
- problema: "Servicios Python fallan"
|
||||
solucion: "Verificar version Python 3.11. pip install -r requirements.txt"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# REFERENCIAS
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
referencias:
|
||||
perfil_devenv: "orchestration/agents/perfiles/PERFIL-DEVENV.md"
|
||||
inventario_master: "orchestration/inventarios/DEVENV-MASTER-INVENTORY.yml"
|
||||
inventario_puertos: "orchestration/inventarios/DEVENV-PORTS-INVENTORY.yml"
|
||||
contexto_proyecto: "orchestration/00-guidelines/CONTEXTO-PROYECTO.md"
|
||||
|
||||
# =============================================================================
|
||||
# FIN DE INVENTARIO
|
||||
# =============================================================================
|
||||
@ -1,219 +0,0 @@
|
||||
# =============================================================================
|
||||
# PROJECT-ENV-CONFIG.yml - TRADING-PLATFORM
|
||||
# =============================================================================
|
||||
# Proyecto: TRADING-PLATFORM - Plataforma de Trading Trading Platform
|
||||
# Actualizado: 2025-12-05
|
||||
# Referencia: ~/workspace/core/devtools/environment/DEV-ENVIRONMENT-REGISTRY.yml
|
||||
# Configuración de puertos: /home/isem/workspace/projects/trading-platform/.env.ports
|
||||
# =============================================================================
|
||||
|
||||
project:
|
||||
name: "TRADING_PLATFORM"
|
||||
slug: "trading-platform"
|
||||
description: "Plataforma de Trading con IA y ML para análisis de mercados"
|
||||
status: "active-development"
|
||||
port_block: 3100
|
||||
version: "0.1.0"
|
||||
|
||||
# =============================================================================
|
||||
# PUERTOS DE SERVICIOS
|
||||
# =============================================================================
|
||||
ports:
|
||||
# Frontend Services
|
||||
frontend_web: 3100 # Aplicación React principal
|
||||
frontend_admin: 3101 # Panel admin (futuro)
|
||||
frontend_preview: 4173 # Vite preview
|
||||
|
||||
# Backend Services (Node.js)
|
||||
backend_api: 4000 # Express API REST
|
||||
backend_ws: 4001 # WebSocket server
|
||||
backend_webhooks: 4002 # Webhooks endpoint
|
||||
|
||||
# Python Services
|
||||
ml_engine: 5000 # ML predictions (FastAPI)
|
||||
data_service: 5001 # Data sync service
|
||||
llm_agent: 5002 # LLM agent API (futuro)
|
||||
portfolio_manager: 5003 # Portfolio manager (futuro)
|
||||
|
||||
# Infrastructure
|
||||
postgres: 5432 # PostgreSQL principal
|
||||
postgres_test: 5433 # PostgreSQL testing
|
||||
redis: 6379 # Redis cache/queues
|
||||
mysql_legacy: 3306 # MySQL temporal (migración)
|
||||
|
||||
# CI/CD & Monitoring
|
||||
jenkins: 8080 # Jenkins CI/CD
|
||||
jenkins_agent: 50000 # Jenkins agents
|
||||
prometheus: 9090 # Métricas (opcional)
|
||||
grafana: 3200 # Dashboards (opcional)
|
||||
|
||||
# Dev Tools
|
||||
pgadmin: 5050 # PostgreSQL admin
|
||||
mailhog_smtp: 1025 # Email testing SMTP
|
||||
mailhog_web: 8025 # Email testing UI
|
||||
|
||||
# =============================================================================
|
||||
# DATABASE
|
||||
# =============================================================================
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 5432
|
||||
name: "trading_trading"
|
||||
user: "trading_user"
|
||||
# password: Ver archivo .env local
|
||||
schemas:
|
||||
- users # Usuarios y autenticación
|
||||
- market_data # Datos de mercado
|
||||
- trading # Señales y operaciones
|
||||
- education # Contenido educativo
|
||||
- investment # Cuentas de inversión
|
||||
- payments # Suscripciones Stripe
|
||||
- broker_integration # Integración brokers
|
||||
- data_sources # Fuentes de datos
|
||||
|
||||
# =============================================================================
|
||||
# REDIS
|
||||
# =============================================================================
|
||||
redis:
|
||||
host: "localhost"
|
||||
port: 6379
|
||||
uses:
|
||||
- sessions
|
||||
- cache
|
||||
- message_queues
|
||||
- rate_limiting
|
||||
|
||||
# =============================================================================
|
||||
# URLs DE ACCESO
|
||||
# =============================================================================
|
||||
urls:
|
||||
frontend_web: "http://localhost:3100"
|
||||
frontend_admin: "http://localhost:3101"
|
||||
backend_api: "http://localhost:4000/api/v1"
|
||||
backend_health: "http://localhost:4000/health"
|
||||
backend_ws: "ws://localhost:4001"
|
||||
ml_engine: "http://localhost:5000"
|
||||
ml_engine_docs: "http://localhost:5000/docs"
|
||||
data_service: "http://localhost:5001"
|
||||
pgadmin: "http://localhost:5050"
|
||||
mailhog: "http://localhost:8025"
|
||||
|
||||
# =============================================================================
|
||||
# ARCHIVOS DE CONFIGURACIÓN
|
||||
# =============================================================================
|
||||
env_files:
|
||||
ports: ".env.ports" # Configuración centralizada de puertos
|
||||
backend: "apps/backend/.env"
|
||||
frontend: "apps/frontend/.env"
|
||||
ml_engine: "apps/ml-engine/.env"
|
||||
data_service: "apps/data-service/.env"
|
||||
docker: "docker-compose.yml"
|
||||
|
||||
# =============================================================================
|
||||
# STACK TECNOLÓGICO
|
||||
# =============================================================================
|
||||
stack:
|
||||
backend: "Express + TypeScript"
|
||||
frontend: "React + TypeScript + Vite"
|
||||
database: "PostgreSQL 15"
|
||||
cache: "Redis 7"
|
||||
ml_engine: "FastAPI + Python + scikit-learn"
|
||||
data_service: "Python AsyncIO + APScheduler"
|
||||
llm_agent: "FastAPI + LangChain (futuro)"
|
||||
orchestration: "Docker Compose"
|
||||
ci_cd: "Jenkins (planeado)"
|
||||
|
||||
# =============================================================================
|
||||
# MÓDULOS DEL PROYECTO
|
||||
# =============================================================================
|
||||
modules:
|
||||
- name: "OQI-001-authentication"
|
||||
status: "active"
|
||||
description: "Sistema de autenticación multi-factor"
|
||||
|
||||
- name: "OQI-002-education"
|
||||
status: "active"
|
||||
description: "Plataforma educativa de trading"
|
||||
|
||||
- name: "OQI-003-trading-charts"
|
||||
status: "active"
|
||||
description: "Visualización de charts y señales"
|
||||
|
||||
- name: "OQI-004-investment-accounts"
|
||||
status: "active"
|
||||
description: "Gestión de cuentas de inversión"
|
||||
|
||||
- name: "OQI-005-payments-stripe"
|
||||
status: "active"
|
||||
description: "Suscripciones con Stripe"
|
||||
|
||||
- name: "OQI-006-ml-engine"
|
||||
status: "active"
|
||||
description: "Motor de predicciones ML"
|
||||
|
||||
- name: "OQI-007-llm-agent"
|
||||
status: "planned"
|
||||
description: "Asistente inteligente con LLM"
|
||||
|
||||
- name: "OQI-008-portfolio-manager"
|
||||
status: "planned"
|
||||
description: "Gestión de portafolios"
|
||||
|
||||
# =============================================================================
|
||||
# INTEGRACIONES EXTERNAS
|
||||
# =============================================================================
|
||||
integrations:
|
||||
- name: "Polygon.io"
|
||||
purpose: "Datos de mercado en tiempo real"
|
||||
type: "REST API"
|
||||
|
||||
- name: "Massive API"
|
||||
purpose: "Datos históricos de forex"
|
||||
type: "REST API"
|
||||
|
||||
- name: "MetaAPI.cloud"
|
||||
purpose: "Conexión a MT4/MT5"
|
||||
type: "Cloud API"
|
||||
|
||||
- name: "Stripe"
|
||||
purpose: "Procesamiento de pagos"
|
||||
type: "REST API + Webhooks"
|
||||
port: 4002
|
||||
|
||||
- name: "Claude AI / OpenAI"
|
||||
purpose: "LLM para asistente"
|
||||
type: "REST API"
|
||||
status: "planned"
|
||||
|
||||
# =============================================================================
|
||||
# NOTAS
|
||||
# =============================================================================
|
||||
notes: |
|
||||
CONFIGURACIÓN ACTUALIZADA - 2025-12-05
|
||||
|
||||
Cambios realizados:
|
||||
- Puertos reorganizados para evitar conflictos con puertos 3000 y 8000 ya en uso
|
||||
- Frontend movido de 5173 a 3100 para consistencia
|
||||
- Backend movido de 3000 a 4000 para evitar conflicto
|
||||
- ML Engine en 5000 (ya configurado)
|
||||
- Data Service en 5001
|
||||
- Todos los servicios documentados en docs/95-guias-desarrollo/PUERTOS-SERVICIOS.md
|
||||
|
||||
Archivos creados:
|
||||
- .env.ports - Configuración centralizada de puertos
|
||||
- docker-compose.yml - Orquestación completa
|
||||
- docs/95-guias-desarrollo/PUERTOS-SERVICIOS.md - Documentación detallada
|
||||
|
||||
Estado del proyecto:
|
||||
- PostgreSQL: Activo en puerto 5432
|
||||
- Redis: Activo en puerto 6379
|
||||
- Backend: Requiere actualización de puerto en .env
|
||||
- Frontend: Requiere actualización de puerto en vite.config
|
||||
- ML Engine: Configurado en 5000 (correcto)
|
||||
- Data Service: Configurado en 5001 (nuevo)
|
||||
|
||||
Próximos pasos:
|
||||
1. Actualizar archivos .env de cada servicio con nuevos puertos
|
||||
2. Testear docker-compose up -d
|
||||
3. Verificar conectividad entre servicios
|
||||
4. Actualizar CI/CD cuando se implemente Jenkins
|
||||
@ -1,65 +0,0 @@
|
||||
{
|
||||
"proyecto": "trading-platform",
|
||||
"limite_maximo": 15,
|
||||
"slots_disponibles": 15,
|
||||
"ultima_actualizacion": "2025-12-07T22:15:00-06:00",
|
||||
"activos": [],
|
||||
"completados": [
|
||||
{
|
||||
"id": "ml-engine-migration",
|
||||
"tipo": "ML-Engine-Agent",
|
||||
"tarea": "Migrar modelos avanzados del TradingAgent (AMDDetector, Phase2Pipeline, Backtesting)",
|
||||
"inicio": "2025-12-07T21:38:00-06:00",
|
||||
"fin": "2025-12-07T22:10:00-06:00",
|
||||
"estado": "completado",
|
||||
"track": "Track B - ML Engine",
|
||||
"resultado": {
|
||||
"archivos_creados": 7,
|
||||
"lineas_codigo": 5000,
|
||||
"componentes": ["AMDDetector", "AMDModels", "API Endpoints", "Tests"],
|
||||
"pendiente_manual": ["phase2_pipeline.py", "walk_forward.py", "signal_logger.py", "backtesting/*.py"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "llm-service-setup",
|
||||
"tipo": "LLM-Integration-Agent",
|
||||
"tarea": "Configurar LLM local (Ollama + Llama 3) e implementar Trading Tools",
|
||||
"inicio": "2025-12-07T21:38:00-06:00",
|
||||
"fin": "2025-12-07T22:12:00-06:00",
|
||||
"estado": "completado",
|
||||
"track": "Track C - LLM Service",
|
||||
"resultado": {
|
||||
"archivos_creados": 15,
|
||||
"lineas_codigo": 3500,
|
||||
"tools_implementados": 12,
|
||||
"endpoints_api": 8,
|
||||
"system_prompt_lineas": 1500
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "trading-agents-impl",
|
||||
"tipo": "Trading-Operations-Agent",
|
||||
"tarea": "Implementar agentes Atlas/Orion/Nova con paper trading",
|
||||
"inicio": "2025-12-07T21:38:00-06:00",
|
||||
"fin": "2025-12-07T22:14:00-06:00",
|
||||
"estado": "completado",
|
||||
"track": "Track D - Trading Agents",
|
||||
"resultado": {
|
||||
"archivos_creados": 31,
|
||||
"lineas_codigo": 6500,
|
||||
"agentes": ["Atlas", "Orion", "Nova"],
|
||||
"estrategias": ["Mean Reversion", "Trend Following", "Grid Trading", "Momentum"],
|
||||
"endpoints_api": 11
|
||||
}
|
||||
}
|
||||
],
|
||||
"fallidos": [],
|
||||
"resumen_sesion": {
|
||||
"fecha": "2025-12-07",
|
||||
"subagentes_ejecutados": 3,
|
||||
"todos_exitosos": true,
|
||||
"archivos_totales": 53,
|
||||
"lineas_codigo_total": 15000,
|
||||
"reporte": "orchestration/reportes/REPORTE-SESION-2025-12-07.md"
|
||||
}
|
||||
}
|
||||
@ -1,386 +0,0 @@
|
||||
# Plan de Desarrollo - Trading Platform
|
||||
## Fase 2: Integracion y Testing (Enero 2026)
|
||||
|
||||
**Fecha:** 2026-01-07
|
||||
**Version:** 1.0.0
|
||||
**Basado en:** ANALISIS-CONSOLIDADO-FASE1-2026-01-07.md
|
||||
**Estado:** EN REVISION
|
||||
|
||||
---
|
||||
|
||||
## 1. OBJETIVO DEL PLAN
|
||||
|
||||
Completar el 100% de la Fase 2 (Integracion y Testing) del proyecto Trading Platform, resolviendo todos los gaps criticos identificados en el analisis consolidado.
|
||||
|
||||
### 1.1 Criterios de Exito
|
||||
|
||||
- [ ] Todos los gaps CRITICOS resueltos (4 items)
|
||||
- [ ] Todos los gaps ALTA prioridad resueltos (6 items)
|
||||
- [ ] Cobertura de tests > 60%
|
||||
- [ ] ML Engine funcional con R^2 positivo
|
||||
- [ ] Sistema listo para produccion
|
||||
|
||||
---
|
||||
|
||||
## 2. PLAN POR SPRINTS
|
||||
|
||||
### SPRINT 1: ESTABILIZACION ML ENGINE
|
||||
|
||||
**Duracion:** 5-7 dias
|
||||
**Objetivo:** Resolver problemas criticos de predicciones ML
|
||||
|
||||
#### Tareas Sprint 1
|
||||
|
||||
| ID | Tarea | Prioridad | Componente | Archivos |
|
||||
|----|-------|-----------|------------|----------|
|
||||
| S1-T1 | Analizar feature engineering RangePredictor | CRITICA | ML Engine | `src/models/range_predictor.py` |
|
||||
| S1-T2 | Revisar normalizacion de datos | CRITICA | ML Engine | `src/data/features.py` |
|
||||
| S1-T3 | Verificar data leakage en targets | CRITICA | ML Engine | `src/data/targets.py` |
|
||||
| S1-T4 | Implementar auto-load en FastAPI startup | CRITICA | ML Engine | `src/api/main.py` |
|
||||
| S1-T5 | Reentrenar modelos con fixes | ALTA | ML Engine | `src/training/*.py` |
|
||||
| S1-T6 | Validacion OOS completa | ALTA | ML Engine | Scripts nuevos |
|
||||
| S1-T7 | Tests unitarios para modelos | MEDIA | ML Engine | `tests/` |
|
||||
|
||||
#### Entregables Sprint 1
|
||||
|
||||
1. **REPORTE-ANALISIS-RANGEPREDICTOR.md**
|
||||
- Root cause del R^2 negativo
|
||||
- Acciones correctivas aplicadas
|
||||
- Metricas antes/despues
|
||||
|
||||
2. **ML Engine API funcional**
|
||||
- Modelos cargados automaticamente
|
||||
- Endpoint `/health` con status de modelos
|
||||
- Endpoint `/predictions` operativo
|
||||
|
||||
3. **REPORTE-VALIDACION-OOS.md**
|
||||
- Metricas en datos out-of-sample
|
||||
- Comparacion con in-sample
|
||||
- Recomendaciones
|
||||
|
||||
#### Criterios de Aceptacion Sprint 1
|
||||
|
||||
- [ ] RangePredictor R^2 > 0.10 en datos OOS
|
||||
- [ ] API ML responde en < 500ms
|
||||
- [ ] Tests unitarios > 70% coverage en models/
|
||||
- [ ] Documentacion actualizada
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 2: INTEGRACION BACKEND
|
||||
|
||||
**Duracion:** 5 dias
|
||||
**Objetivo:** Completar servicios de integracion backend
|
||||
|
||||
#### Tareas Sprint 2
|
||||
|
||||
| ID | Tarea | Prioridad | Componente | Archivos |
|
||||
|----|-------|-----------|------------|----------|
|
||||
| S2-T1 | Implementar ml-integration.service.ts | CRITICA | Backend | `src/modules/ml/services/` |
|
||||
| S2-T2 | Auth middleware paper trading | ALTA | Backend | `src/modules/trading/` |
|
||||
| S2-T3 | Auth middleware investment | ALTA | Backend | `src/modules/investment/` |
|
||||
| S2-T4 | Completar agents.service.ts | ALTA | Backend | `src/modules/agents/` |
|
||||
| S2-T5 | Implementar users module | MEDIA | Backend | `src/modules/users/` |
|
||||
| S2-T6 | Tests integracion Backend-ML | MEDIA | Backend | `src/__tests__/` |
|
||||
|
||||
#### Archivos a Modificar/Crear
|
||||
|
||||
```
|
||||
apps/backend/src/
|
||||
├── modules/
|
||||
│ ├── ml/
|
||||
│ │ └── services/
|
||||
│ │ └── ml-integration.service.ts # COMPLETAR (actualmente 100 LOC)
|
||||
│ ├── trading/
|
||||
│ │ └── trading.routes.ts # AGREGAR auth middleware
|
||||
│ ├── investment/
|
||||
│ │ └── investment.routes.ts # AGREGAR auth middleware
|
||||
│ ├── agents/
|
||||
│ │ └── services/
|
||||
│ │ └── agents.service.ts # COMPLETAR orquestacion
|
||||
│ └── users/
|
||||
│ ├── users.routes.ts # IMPLEMENTAR
|
||||
│ ├── controllers/
|
||||
│ │ └── users.controller.ts # CREAR
|
||||
│ └── services/
|
||||
│ └── users.service.ts # CREAR
|
||||
└── __tests__/
|
||||
└── integration/
|
||||
└── ml-backend.spec.ts # CREAR
|
||||
```
|
||||
|
||||
#### Criterios de Aceptacion Sprint 2
|
||||
|
||||
- [ ] ml-integration.service.ts completamente implementado
|
||||
- [ ] Todos los endpoints paper trading requieren auth
|
||||
- [ ] Users module con CRUD basico
|
||||
- [ ] Tests de integracion pasando
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 3: LLM Y TRADING AGENTS
|
||||
|
||||
**Duracion:** 5-7 dias
|
||||
**Objetivo:** Completar funcionalidades de agentes inteligentes
|
||||
|
||||
#### Tareas Sprint 3
|
||||
|
||||
| ID | Tarea | Prioridad | Componente | Archivos |
|
||||
|----|-------|-----------|------------|----------|
|
||||
| S3-T1 | Completar MCPOrchestrator | CRITICA | LLM Agent | `src/services/mcp_orchestrator.py` |
|
||||
| S3-T2 | Live trading execution | ALTA | LLM Agent | `src/tools/trading.py` |
|
||||
| S3-T3 | Persistencia decisiones | ALTA | LLM Agent | `src/services/auto_trade_service.py` |
|
||||
| S3-T4 | Rate limiting API | ALTA | LLM Agent | `src/api/routes.py` |
|
||||
| S3-T5 | Implementar Scalping strategy | ALTA | Trading Agents | `src/strategies/scalping.py` |
|
||||
| S3-T6 | Persistencia BD trades | ALTA | Trading Agents | `src/` |
|
||||
| S3-T7 | WebSocket signals consumer | MEDIA | Trading Agents | `src/signals/` |
|
||||
|
||||
#### Archivos a Modificar/Crear
|
||||
|
||||
```
|
||||
apps/llm-agent/src/
|
||||
├── services/
|
||||
│ └── mcp_orchestrator.py # COMPLETAR (actualmente 100 LOC)
|
||||
├── tools/
|
||||
│ └── trading.py # AGREGAR _execute_order real
|
||||
└── api/
|
||||
└── routes.py # AGREGAR rate limiting
|
||||
|
||||
apps/trading-agents/src/
|
||||
├── strategies/
|
||||
│ └── scalping.py # CREAR
|
||||
├── persistence/
|
||||
│ └── db_manager.py # CREAR
|
||||
└── signals/
|
||||
└── ws_consumer.py # CREAR
|
||||
```
|
||||
|
||||
#### Criterios de Aceptacion Sprint 3
|
||||
|
||||
- [ ] MCPOrchestrator con portfolio consolidado MT4+Binance
|
||||
- [ ] Live trading ejecutando ordenes reales
|
||||
- [ ] Rate limiting < 100 req/min por usuario
|
||||
- [ ] Scalping strategy funcional para Nova
|
||||
- [ ] Trades persistidos en PostgreSQL
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 4: FRONTEND Y UX
|
||||
|
||||
**Duracion:** 5 dias
|
||||
**Objetivo:** Mejorar experiencia de usuario
|
||||
|
||||
#### Tareas Sprint 4
|
||||
|
||||
| ID | Tarea | Prioridad | Componente | Archivos |
|
||||
|----|-------|-----------|------------|----------|
|
||||
| S4-T1 | WebSocket real-time trading | ALTA | Frontend | `src/services/websocket.service.ts` |
|
||||
| S4-T2 | Streaming LLM responses | ALTA | Frontend | `src/modules/assistant/` |
|
||||
| S4-T3 | Certificados PDF | MEDIA | Frontend | `src/modules/education/` |
|
||||
| S4-T4 | Investment module conectado | MEDIA | Frontend | `src/modules/investment/` |
|
||||
| S4-T5 | Dark mode toggle | BAJA | Frontend | `src/` |
|
||||
|
||||
#### Archivos a Modificar/Crear
|
||||
|
||||
```
|
||||
apps/frontend/src/
|
||||
├── services/
|
||||
│ └── websocket.service.ts # COMPLETAR
|
||||
├── modules/
|
||||
│ ├── assistant/
|
||||
│ │ └── pages/
|
||||
│ │ └── Assistant.tsx # AGREGAR streaming
|
||||
│ ├── education/
|
||||
│ │ └── services/
|
||||
│ │ └── certificate.service.ts # CREAR
|
||||
│ └── investment/
|
||||
│ └── services/
|
||||
│ └── investment.service.ts # CONECTAR backend
|
||||
└── contexts/
|
||||
└── ThemeContext.tsx # CREAR (dark mode)
|
||||
```
|
||||
|
||||
#### Criterios de Aceptacion Sprint 4
|
||||
|
||||
- [ ] Precios actualizandose via WebSocket
|
||||
- [ ] Chat con streaming de respuestas
|
||||
- [ ] Certificados descargables en PDF
|
||||
- [ ] Investment mostrando datos reales
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 5: SEGURIDAD Y TESTING
|
||||
|
||||
**Duracion:** 5-7 dias
|
||||
**Objetivo:** Hardening para produccion
|
||||
|
||||
#### Tareas Sprint 5
|
||||
|
||||
| ID | Tarea | Prioridad | Componente | Archivos |
|
||||
|----|-------|-----------|------------|----------|
|
||||
| S5-T1 | Habilitar RLS PostgreSQL | ALTA | Database | DDL scripts |
|
||||
| S5-T2 | Rate limiting Backend | ALTA | Backend | Middleware |
|
||||
| S5-T3 | Auth Bearer MCP servers | ALTA | MCP | Todos |
|
||||
| S5-T4 | E2E Testing suite | ALTA | Testing | Cypress/Playwright |
|
||||
| S5-T5 | Integration tests | MEDIA | Testing | Jest |
|
||||
| S5-T6 | Security audit | MEDIA | Todos | - |
|
||||
|
||||
#### Archivos a Modificar/Crear
|
||||
|
||||
```
|
||||
apps/database/ddl/
|
||||
├── rls/
|
||||
│ ├── auth-rls.sql # CREAR
|
||||
│ ├── trading-rls.sql # CREAR
|
||||
│ └── financial-rls.sql # CREAR
|
||||
|
||||
apps/backend/src/
|
||||
├── middleware/
|
||||
│ └── rate-limiter.ts # ACTUALIZAR
|
||||
|
||||
apps/mcp-mt4-connector/src/
|
||||
└── middleware/
|
||||
└── auth.ts # CREAR
|
||||
|
||||
e2e/
|
||||
├── cypress/
|
||||
│ └── integration/
|
||||
│ ├── auth.spec.ts # CREAR
|
||||
│ ├── trading.spec.ts # CREAR
|
||||
│ └── education.spec.ts # CREAR
|
||||
```
|
||||
|
||||
#### Criterios de Aceptacion Sprint 5
|
||||
|
||||
- [ ] RLS habilitado en auth, trading, financial
|
||||
- [ ] Rate limiting en todos los endpoints
|
||||
- [ ] MCP servers con autenticacion
|
||||
- [ ] E2E tests > 50 casos
|
||||
- [ ] Security audit sin vulnerabilidades criticas
|
||||
|
||||
---
|
||||
|
||||
## 3. DEPENDENCIAS ENTRE TAREAS
|
||||
|
||||
```
|
||||
Sprint 1 (ML Engine)
|
||||
|
|
||||
v
|
||||
Sprint 2 (Backend) ---> Requiere ML funcional
|
||||
|
|
||||
v
|
||||
Sprint 3 (LLM/Agents) ---> Requiere Backend integrado
|
||||
|
|
||||
v
|
||||
Sprint 4 (Frontend) ---> Requiere Backend/LLM funcional
|
||||
|
|
||||
v
|
||||
Sprint 5 (Testing) ---> Requiere todo funcional
|
||||
```
|
||||
|
||||
### Dependencias Criticas
|
||||
|
||||
| Tarea | Depende de |
|
||||
|-------|-----------|
|
||||
| S2-T1 (ml-integration) | S1-T4 (ML API funcional) |
|
||||
| S3-T2 (live trading) | S3-T1 (MCPOrchestrator) |
|
||||
| S4-T4 (investment frontend) | S2-T5 (users module) |
|
||||
| S5-T4 (E2E tests) | Sprints 1-4 completados |
|
||||
|
||||
---
|
||||
|
||||
## 4. ASIGNACION DE RECURSOS
|
||||
|
||||
### Perfiles Requeridos
|
||||
|
||||
| Perfil | Sprints | Dedicacion |
|
||||
|--------|---------|------------|
|
||||
| ML-SPECIALIST | 1, 3 | 100% |
|
||||
| BACKEND-EXPRESS | 2, 5 | 100% |
|
||||
| LLM-AGENT | 3 | 100% |
|
||||
| FRONTEND-REACT | 4 | 100% |
|
||||
| QA-TESTING | 5 | 100% |
|
||||
| DBA | 5 | 50% |
|
||||
|
||||
### Capacidad Estimada
|
||||
|
||||
- **Total dias de trabajo:** 25-30 dias
|
||||
- **Paralelizacion posible:** Sprints 3-4 parcialmente
|
||||
- **Buffer para imprevistos:** 20%
|
||||
|
||||
---
|
||||
|
||||
## 5. RIESGOS Y MITIGACION
|
||||
|
||||
| Riesgo | Probabilidad | Mitigacion |
|
||||
|--------|--------------|------------|
|
||||
| ML no mejora con fixes | Media | Plan B: Simplificar modelo a baseline |
|
||||
| Dependencia EA Bridge | Alta | Crear mock service para testing |
|
||||
| Retrasos en Sprint 1 | Media | Extender a 7 dias, priorizar criticos |
|
||||
| Integracion compleja | Media | Agregar dias buffer a Sprint 3 |
|
||||
|
||||
---
|
||||
|
||||
## 6. METRICAS DE SEGUIMIENTO
|
||||
|
||||
### Por Sprint
|
||||
|
||||
| Sprint | Velocidad Target | Criterio Exito |
|
||||
|--------|-----------------|----------------|
|
||||
| 1 | 7 tareas | ML R^2 > 0.10 |
|
||||
| 2 | 6 tareas | Backend 100% |
|
||||
| 3 | 7 tareas | Live trading OK |
|
||||
| 4 | 5 tareas | UX mejorado |
|
||||
| 5 | 6 tareas | Ready for prod |
|
||||
|
||||
### Globales
|
||||
|
||||
- **Burndown chart** actualizado diariamente
|
||||
- **Tests pasando** verificado en cada PR
|
||||
- **Metricas ML** monitoreadas continuamente
|
||||
|
||||
---
|
||||
|
||||
## 7. CHECKPOINTS DE VALIDACION
|
||||
|
||||
### Checkpoint 1 (Post-Sprint 1)
|
||||
- [ ] ML Engine API respondiendo
|
||||
- [ ] Modelos con metricas positivas
|
||||
- [ ] Documentacion actualizada
|
||||
|
||||
### Checkpoint 2 (Post-Sprint 2)
|
||||
- [ ] Backend completamente integrado
|
||||
- [ ] Tests de integracion pasando
|
||||
- [ ] Endpoints protegidos
|
||||
|
||||
### Checkpoint 3 (Post-Sprint 3)
|
||||
- [ ] Agentes operativos
|
||||
- [ ] Trading ejecutandose
|
||||
- [ ] Persistencia funcionando
|
||||
|
||||
### Checkpoint 4 (Post-Sprint 4)
|
||||
- [ ] Frontend completo
|
||||
- [ ] UX validado
|
||||
- [ ] Usuarios pueden operar
|
||||
|
||||
### Checkpoint 5 (Post-Sprint 5)
|
||||
- [ ] Seguridad auditada
|
||||
- [ ] Tests > 60% coverage
|
||||
- [ ] LISTO PARA PRODUCCION
|
||||
|
||||
---
|
||||
|
||||
## 8. APROBACION DEL PLAN
|
||||
|
||||
Este plan requiere aprobacion antes de iniciar ejecucion.
|
||||
|
||||
**Pendiente aprobacion de:**
|
||||
- [ ] Technical Lead
|
||||
- [ ] Product Owner
|
||||
- [ ] Stakeholders
|
||||
|
||||
---
|
||||
|
||||
**Plan creado:** 2026-01-07
|
||||
**Version:** 1.0.0
|
||||
**Estado:** PENDIENTE APROBACION
|
||||
@ -1,636 +0,0 @@
|
||||
---
|
||||
id: "PLAN-DESARROLLO-ML-FIRST-2026-01"
|
||||
title: "Plan de Desarrollo ML-First - Trading Platform"
|
||||
type: "Plan"
|
||||
project: "trading-platform"
|
||||
version: "1.0.0"
|
||||
created_date: "2026-01-04"
|
||||
author: "Orquestador - Tech Leader"
|
||||
status: "Aprobado"
|
||||
approved_date: "2026-01-04"
|
||||
approved_by: "Usuario"
|
||||
---
|
||||
|
||||
# Plan de Desarrollo ML-First - Trading Platform
|
||||
|
||||
**Version:** 1.0.0
|
||||
**Fecha:** 2026-01-04
|
||||
**Autor:** Agente Orquestador / Tech Leader
|
||||
**Estado:** APROBADO - En Ejecucion
|
||||
|
||||
---
|
||||
|
||||
## Resumen Ejecutivo
|
||||
|
||||
Este plan reordena el desarrollo de la plataforma Trading Platform segun las siguientes prioridades:
|
||||
|
||||
| Prioridad | Componente | Objetivo |
|
||||
|-----------|------------|----------|
|
||||
| **P0** | Modelos ML | Prediccion de maximos/minimos con 80%+ efectividad |
|
||||
| **P1** | LLM Local + Fine-tuning | Agente que analice predicciones y ejecute operaciones |
|
||||
| **P2** | MCP Server + MT4/Binance | Conector para ejecucion automatizada |
|
||||
| **P3** | Visualizacion Web | Graficos tipo TradingView con predicciones ML |
|
||||
| **P4** | SaaS Features | Stripe, wallet, cursos, membresias (posterior) |
|
||||
|
||||
### Objetivos de Rendimiento
|
||||
|
||||
| Metrica | Target |
|
||||
|---------|--------|
|
||||
| Efectividad operaciones ganadas | **80%** |
|
||||
| Rendimiento semanal | **30-100%** |
|
||||
| Prediccion de maximos/minimos | Multiple temporalidades |
|
||||
| Integraciones | MT4 (Forex) + Binance (BTC) |
|
||||
|
||||
---
|
||||
|
||||
## 1. Analisis del Estado Actual vs Prioridades
|
||||
|
||||
### 1.1 Estado Actual del Proyecto
|
||||
|
||||
| Componente | Estado | Completitud | Prioridad Actual |
|
||||
|------------|--------|-------------|------------------|
|
||||
| Auth/Users (OQI-001) | Completado | 100% | Alta |
|
||||
| Education (OQI-002) | En desarrollo | 40% | Media |
|
||||
| Trading Charts (OQI-003) | En desarrollo | 85% | Alta |
|
||||
| Investment Accounts (OQI-004) | Planificado | 30% | Media |
|
||||
| Payments Stripe (OQI-005) | En desarrollo | 30% | Media |
|
||||
| **ML Signals (OQI-006)** | En desarrollo | **70%** | **Critica** |
|
||||
| LLM Agent (OQI-007) | Planificado | 20% | Alta |
|
||||
| Portfolio Manager (OQI-008) | Planificado | 10% | Baja |
|
||||
| Marketplace (OQI-009) | Backlog | 0% | Baja |
|
||||
|
||||
### 1.2 Gaps Identificados para Nuevas Prioridades
|
||||
|
||||
#### Gap 1: Validacion Temporal de Modelos ML
|
||||
- **Problema**: No hay estrategia definida para excluir ultimo ano de datos
|
||||
- **Solucion**: Implementar walk-forward validation con holdout del ultimo ano
|
||||
- **Impacto**: Critico para validar efectividad real de predicciones
|
||||
|
||||
#### Gap 2: Prediccion de Maximos/Minimos Multi-Temporalidad
|
||||
- **Problema**: RangePredictor actual solo tiene 15m y 1h
|
||||
- **Solucion**: Extender a 4h, 1D, 1W para diferentes estilos de trading
|
||||
- **Impacto**: Alto - necesario para objetivo de 30-100% semanal
|
||||
|
||||
#### Gap 3: Fine-tuning LLM con Estrategias
|
||||
- **Problema**: LLM Agent actual usa prompts estaticos, no fine-tuning
|
||||
- **Solucion**: Crear dataset de estrategias + entrenamiento con LoRA
|
||||
- **Impacto**: Critico para decision-making autonomo
|
||||
|
||||
#### Gap 4: MCP Server para MT4
|
||||
- **Problema**: No existe MCP server para integracion
|
||||
- **Solucion**: Crear MCP server que exponga tools para MT4 y Binance
|
||||
- **Impacto**: Critico para ejecucion automatizada
|
||||
|
||||
#### Gap 5: Integracion Binance para Bitcoin
|
||||
- **Problema**: Trading agents tiene Binance parcial, no optimizado para BTC
|
||||
- **Solucion**: Implementar estrategias especificas para Bitcoin
|
||||
- **Impacto**: Alto - diversificacion de mercados
|
||||
|
||||
---
|
||||
|
||||
## 2. Plan de Desarrollo Reordenado
|
||||
|
||||
### FASE 0: Preparacion de Datos (Semana 1)
|
||||
|
||||
**Objetivo**: Preparar datasets con exclusion del ultimo ano para validacion
|
||||
|
||||
```
|
||||
Datos Historicos (10 anos)
|
||||
|
|
||||
v
|
||||
+---------------------+
|
||||
| Anos 1-9 | --> Training + Validation (Walk-forward)
|
||||
+---------------------+
|
||||
|
|
||||
v
|
||||
+---------------------+
|
||||
| Ano 10 (ultimo) | --> Out-of-Sample Testing (NUNCA visto en training)
|
||||
+---------------------+
|
||||
```
|
||||
|
||||
#### Tareas:
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F0-01 | Configurar pipeline de ingesta de datos | ML-SPECIALIST | - | 2 dias |
|
||||
| F0-02 | Implementar split temporal (excluir ultimo ano) | ML-SPECIALIST | F0-01 | 1 dia |
|
||||
| F0-03 | Crear datasets por temporalidad (5m, 15m, 1H, 4H, D, W) | ML-SPECIALIST | F0-02 | 2 dias |
|
||||
| F0-04 | Validar integridad de datos | DATABASE | F0-03 | 1 dia |
|
||||
|
||||
**Entregable**: Datasets listos para entrenamiento con split temporal correcto
|
||||
|
||||
---
|
||||
|
||||
### FASE 1: Modelos ML - Entrenamiento y Optimizacion (Semanas 2-4)
|
||||
|
||||
**Objetivo**: Modelos ML funcionando con metricas de produccion
|
||||
|
||||
#### Track 1.1: RangePredictor Multi-Temporalidad
|
||||
|
||||
```python
|
||||
# Horizontes a implementar
|
||||
HORIZONS = {
|
||||
'scalping': {'5m': 6, '15m': 4}, # 30min - 1h
|
||||
'intraday': {'1H': 4, '4H': 2}, # 4h - 8h
|
||||
'swing': {'4H': 6, '1D': 2}, # 1-2 dias
|
||||
'position': {'1D': 5, '1W': 1} # 1 semana
|
||||
}
|
||||
|
||||
# Targets
|
||||
TARGETS = {
|
||||
'delta_high': (max_high - entry_price) / entry_price,
|
||||
'delta_low': (entry_price - min_low) / entry_price,
|
||||
'range_size': (max_high - min_low) / entry_price
|
||||
}
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F1-01 | Extender RangePredictor a todas las temporalidades | ML-SPECIALIST | F0-03 | 3 dias |
|
||||
| F1-02 | Implementar feature engineering multi-TF | ML-SPECIALIST | F1-01 | 2 dias |
|
||||
| F1-03 | Entrenar modelos con walk-forward validation | ML-SPECIALIST | F1-02 | 3 dias |
|
||||
| F1-04 | Optimizar hiperparametros con Optuna | ML-SPECIALIST | F1-03 | 2 dias |
|
||||
| F1-05 | Evaluar en datos out-of-sample (ultimo ano) | ML-SPECIALIST | F1-04 | 1 dia |
|
||||
|
||||
**Metricas Target**:
|
||||
- MAE < 0.5% para prediccion de maximos/minimos
|
||||
- Directional Accuracy > 70%
|
||||
- R² > 0.3
|
||||
|
||||
#### Track 1.2: AMD Detector (Fases de Mercado)
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F1-06 | Completar implementacion AMDDetector | ML-SPECIALIST | F0-03 | 3 dias |
|
||||
| F1-07 | Crear labels automaticos para fases AMD | ML-SPECIALIST | F1-06 | 2 dias |
|
||||
| F1-08 | Entrenar y validar detector de fases | ML-SPECIALIST | F1-07 | 2 dias |
|
||||
|
||||
**Metricas Target**:
|
||||
- Overall Accuracy > 70%
|
||||
- Macro F1 > 0.65
|
||||
|
||||
#### Track 1.3: TPSL Classifier (Optimizado para 80% Win Rate)
|
||||
|
||||
```python
|
||||
# Configuracion para objetivo de 80% win rate
|
||||
RR_CONFIGS = [
|
||||
{'name': 'conservative', 'sl_atr': 0.5, 'tp_atr': 0.5, 'target_wr': 0.80},
|
||||
{'name': 'moderate', 'sl_atr': 0.5, 'tp_atr': 0.75, 'target_wr': 0.75},
|
||||
{'name': 'aggressive', 'sl_atr': 0.3, 'tp_atr': 0.9, 'target_wr': 0.70}
|
||||
]
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F1-09 | Ajustar TPSL para target 80% win rate | ML-SPECIALIST | F1-05 | 2 dias |
|
||||
| F1-10 | Calibrar probabilidades con isotonic | ML-SPECIALIST | F1-09 | 1 dia |
|
||||
| F1-11 | Backtesting de estrategias con TPSL | ML-SPECIALIST | F1-10 | 2 dias |
|
||||
|
||||
**Metricas Target**:
|
||||
- Win Rate > 80% (en configuracion conservadora)
|
||||
- ROC-AUC > 0.90
|
||||
- Profit Factor > 2.0
|
||||
|
||||
#### Track 1.4: StrategyOrchestrator (Meta-Modelo)
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F1-12 | Implementar orquestador de senales | ML-SPECIALIST | F1-08, F1-11 | 3 dias |
|
||||
| F1-13 | Definir matriz de decision | BACKEND | F1-12 | 1 dia |
|
||||
| F1-14 | Backtesting completo del sistema | ML-SPECIALIST | F1-13 | 2 dias |
|
||||
|
||||
**Entregable Fase 1**: Modelos ML entrenados y validados con metricas de produccion
|
||||
|
||||
---
|
||||
|
||||
### FASE 2: LLM Local con Fine-Tuning (Semanas 5-7)
|
||||
|
||||
**Objetivo**: Agente LLM que analice predicciones ML y tome decisiones de trading
|
||||
|
||||
#### Track 2.1: Setup LLM Local
|
||||
|
||||
```yaml
|
||||
# Configuracion Ollama
|
||||
llm:
|
||||
provider: "ollama"
|
||||
base_model: "llama3:8b" # ~10GB VRAM
|
||||
fine_tuned_model: "trading-trader:v1"
|
||||
context_window: 8192
|
||||
temperature: 0.3 # Mas deterministico para trading
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F2-01 | Configurar Ollama en GPU | DEVOPS | - | 1 dia |
|
||||
| F2-02 | Desplegar modelo base Llama 3 8B | DEVOPS | F2-01 | 1 dia |
|
||||
| F2-03 | Crear API FastAPI para LLM local | BACKEND | F2-02 | 2 dias |
|
||||
|
||||
#### Track 2.2: Creacion de Dataset para Fine-Tuning
|
||||
|
||||
```python
|
||||
# Estructura del dataset de entrenamiento
|
||||
TRAINING_DATA = {
|
||||
'estrategias': [
|
||||
# AMD Strategy
|
||||
{
|
||||
'context': 'Fase de mercado: Accumulation, RSI: 35, Volumen: bajo',
|
||||
'analysis': 'El mercado esta en fase de acumulacion...',
|
||||
'decision': 'WAIT - Esperar confirmacion de ruptura',
|
||||
'reasoning': 'Smart money acumulando, esperar manipulacion'
|
||||
},
|
||||
# ICT Strategy
|
||||
{
|
||||
'context': 'OTE Zone: 0.705, Killzone: NY Open, FVG detectado',
|
||||
'analysis': 'Precio en zona OTE optima durante NY Open...',
|
||||
'decision': 'BUY - Entry en FVG con SL bajo swing low',
|
||||
'reasoning': 'Confluence de OTE + Killzone + FVG'
|
||||
},
|
||||
# + 1000+ ejemplos de decisiones de trading
|
||||
],
|
||||
'analisis_predicciones': [
|
||||
{
|
||||
'ml_signal': {'delta_high': 0.8%, 'delta_low': 0.3%, 'phase': 'accumulation'},
|
||||
'analysis': 'Prediccion ML indica movimiento alcista...',
|
||||
'action': 'LONG con TP en delta_high, SL ajustado'
|
||||
}
|
||||
],
|
||||
'gestion_riesgo': [
|
||||
# Ejemplos de position sizing, stop management, etc.
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F2-04 | Definir estructura del dataset de fine-tuning | ML-SPECIALIST | - | 1 dia |
|
||||
| F2-05 | Recopilar/crear ejemplos de estrategias AMD | TRADING-STRATEGIST | F2-04 | 3 dias |
|
||||
| F2-06 | Recopilar/crear ejemplos de estrategias ICT | TRADING-STRATEGIST | F2-04 | 3 dias |
|
||||
| F2-07 | Crear ejemplos de analisis de predicciones ML | ML-SPECIALIST | F2-04 | 2 dias |
|
||||
| F2-08 | Formatear dataset para fine-tuning (JSONL) | ML-SPECIALIST | F2-05, F2-06, F2-07 | 1 dia |
|
||||
|
||||
#### Track 2.3: Fine-Tuning del Modelo
|
||||
|
||||
```python
|
||||
# Fine-tuning con LoRA (Low-Rank Adaptation)
|
||||
LORA_CONFIG = {
|
||||
'r': 16, # Rank
|
||||
'alpha': 32, # Scaling factor
|
||||
'dropout': 0.05,
|
||||
'target_modules': ['q_proj', 'v_proj', 'k_proj', 'o_proj'],
|
||||
'epochs': 3,
|
||||
'learning_rate': 2e-4,
|
||||
'batch_size': 4
|
||||
}
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F2-09 | Setup entorno de fine-tuning (unsloth/axolotl) | ML-SPECIALIST | F2-02 | 1 dia |
|
||||
| F2-10 | Ejecutar fine-tuning con LoRA | ML-SPECIALIST | F2-08, F2-09 | 2 dias |
|
||||
| F2-11 | Evaluar modelo fine-tuned | ML-SPECIALIST | F2-10 | 1 dia |
|
||||
| F2-12 | Convertir a formato Ollama/GGUF | ML-SPECIALIST | F2-11 | 1 dia |
|
||||
| F2-13 | Desplegar modelo fine-tuned | DEVOPS | F2-12 | 1 dia |
|
||||
|
||||
#### Track 2.4: Integracion LLM con ML Engine
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F2-14 | Crear tools de integracion con ML Engine | BACKEND | F1-14, F2-13 | 2 dias |
|
||||
| F2-15 | Implementar flujo de analisis de predicciones | BACKEND | F2-14 | 2 dias |
|
||||
| F2-16 | Crear sistema de decision automatizada | BACKEND | F2-15 | 2 dias |
|
||||
| F2-17 | Tests de integracion LLM + ML | TESTING | F2-16 | 2 dias |
|
||||
|
||||
**Entregable Fase 2**: LLM local fine-tuned capaz de analizar predicciones ML
|
||||
|
||||
---
|
||||
|
||||
### FASE 3: MCP Server + Integraciones de Ejecucion (Semanas 8-10)
|
||||
|
||||
**Objetivo**: MCP Server que conecte el agente LLM con MT4 y Binance
|
||||
|
||||
#### Track 3.1: MCP Server Core
|
||||
|
||||
```typescript
|
||||
// Estructura del MCP Server
|
||||
const MCP_TOOLS = {
|
||||
// Trading Tools
|
||||
'execute_trade': {
|
||||
description: 'Ejecuta una operacion en el broker',
|
||||
parameters: {
|
||||
broker: 'mt4 | binance',
|
||||
symbol: 'string',
|
||||
action: 'buy | sell',
|
||||
lots: 'number',
|
||||
sl: 'number',
|
||||
tp: 'number'
|
||||
}
|
||||
},
|
||||
'get_positions': {
|
||||
description: 'Obtiene posiciones abiertas'
|
||||
},
|
||||
'close_position': {
|
||||
description: 'Cierra una posicion especifica'
|
||||
},
|
||||
'modify_position': {
|
||||
description: 'Modifica SL/TP de una posicion'
|
||||
},
|
||||
|
||||
// Analysis Tools
|
||||
'get_ml_signal': {
|
||||
description: 'Obtiene senal ML actual para un simbolo'
|
||||
},
|
||||
'get_market_data': {
|
||||
description: 'Obtiene datos OHLCV actuales'
|
||||
},
|
||||
'get_amd_phase': {
|
||||
description: 'Obtiene fase AMD actual'
|
||||
},
|
||||
|
||||
// Account Tools
|
||||
'get_account_info': {
|
||||
description: 'Obtiene info de la cuenta (balance, equity)'
|
||||
},
|
||||
'calculate_position_size': {
|
||||
description: 'Calcula tamano de posicion segun riesgo'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F3-01 | Disenar arquitectura MCP Server | MCP-ARCHITECT | - | 1 dia |
|
||||
| F3-02 | Implementar core del MCP Server | MCP-DEVELOPER | F3-01 | 3 dias |
|
||||
| F3-03 | Implementar tools de trading | MCP-DEVELOPER | F3-02 | 2 dias |
|
||||
| F3-04 | Implementar tools de analisis | MCP-DEVELOPER | F3-02 | 2 dias |
|
||||
| F3-05 | Implementar tools de cuenta | MCP-DEVELOPER | F3-02 | 1 dia |
|
||||
|
||||
#### Track 3.2: Integracion MT4 via MetaAPI
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F3-06 | Completar cliente MetaAPI | BACKEND | F3-03 | 3 dias |
|
||||
| F3-07 | Implementar risk manager para MT4 | BACKEND | F3-06 | 2 dias |
|
||||
| F3-08 | Implementar position sizer | BACKEND | F3-07 | 1 dia |
|
||||
| F3-09 | Tests con cuenta demo MT4 | TESTING | F3-08 | 2 dias |
|
||||
|
||||
#### Track 3.3: Integracion Binance para Bitcoin
|
||||
|
||||
```python
|
||||
# Configuracion especifica para BTC
|
||||
BINANCE_BTC_CONFIG = {
|
||||
'symbol': 'BTCUSDT',
|
||||
'testnet': True, # Iniciar en testnet
|
||||
'leverage': 1, # Sin apalancamiento inicial
|
||||
'position_mode': 'one-way',
|
||||
'risk_per_trade': 0.02, # 2%
|
||||
'strategies': ['trend_following', 'mean_reversion', 'breakout']
|
||||
}
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F3-10 | Configurar cliente Binance para BTC | BACKEND | F3-03 | 2 dias |
|
||||
| F3-11 | Adaptar modelos ML para BTC | ML-SPECIALIST | F1-14 | 2 dias |
|
||||
| F3-12 | Implementar estrategias BTC | BACKEND | F3-10, F3-11 | 3 dias |
|
||||
| F3-13 | Tests en Binance Testnet | TESTING | F3-12 | 2 dias |
|
||||
|
||||
#### Track 3.4: Conexion MCP Server con LLM Agent
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F3-14 | Integrar MCP Server con LLM Agent | BACKEND | F2-17, F3-05 | 2 dias |
|
||||
| F3-15 | Implementar flujo de ejecucion automatizada | BACKEND | F3-14 | 2 dias |
|
||||
| F3-16 | Crear modos de operacion (passive/advisory/auto) | BACKEND | F3-15 | 1 dia |
|
||||
| F3-17 | Tests end-to-end del sistema | TESTING | F3-16 | 3 dias |
|
||||
|
||||
**Entregable Fase 3**: Sistema completo de ejecucion automatizada via MCP Server
|
||||
|
||||
---
|
||||
|
||||
### FASE 4: Visualizacion Web (Semanas 11-13)
|
||||
|
||||
**Objetivo**: Dashboard con graficos tipo TradingView mostrando predicciones ML
|
||||
|
||||
#### Track 4.1: Componente de Charts
|
||||
|
||||
```typescript
|
||||
// Usando Lightweight Charts de TradingView
|
||||
const ChartConfig = {
|
||||
library: '@tradingview/lightweight-charts',
|
||||
features: {
|
||||
candlesticks: true,
|
||||
volume: true,
|
||||
drawings: true,
|
||||
indicators: ['SMA', 'RSI', 'AMD_Phase']
|
||||
},
|
||||
overlays: {
|
||||
ml_predictions: {
|
||||
predicted_high: 'green_line',
|
||||
predicted_low: 'red_line',
|
||||
confidence_band: 'shaded_area'
|
||||
},
|
||||
amd_phase: {
|
||||
accumulation: 'blue_bg',
|
||||
manipulation: 'orange_bg',
|
||||
distribution: 'red_bg'
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F4-01 | Implementar componente Chart base | FRONTEND | - | 3 dias |
|
||||
| F4-02 | Agregar overlay de predicciones ML | FRONTEND | F4-01 | 2 dias |
|
||||
| F4-03 | Agregar indicador de fase AMD | FRONTEND | F4-01 | 1 dia |
|
||||
| F4-04 | Implementar panel de senales | FRONTEND | F4-02 | 2 dias |
|
||||
|
||||
#### Track 4.2: Dashboard de Admin
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F4-05 | Crear layout de dashboard | FRONTEND | - | 2 dias |
|
||||
| F4-06 | Implementar panel de performance | FRONTEND | F4-05 | 2 dias |
|
||||
| F4-07 | Implementar historial de trades | FRONTEND | F4-05 | 1 dia |
|
||||
| F4-08 | Implementar estado de cuenta | FRONTEND | F4-05 | 1 dia |
|
||||
| F4-09 | Integracion WebSocket tiempo real | FRONTEND | F4-06 | 2 dias |
|
||||
|
||||
#### Track 4.3: Integracion con Backend
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F4-10 | Crear API endpoints para dashboard | BACKEND | F3-17 | 2 dias |
|
||||
| F4-11 | Implementar WebSocket server | BACKEND | F4-10 | 2 dias |
|
||||
| F4-12 | Conectar frontend con APIs | FRONTEND | F4-09, F4-11 | 2 dias |
|
||||
| F4-13 | Tests de integracion UI | TESTING | F4-12 | 2 dias |
|
||||
|
||||
**Entregable Fase 4**: Dashboard funcional con visualizacion de predicciones ML
|
||||
|
||||
---
|
||||
|
||||
### FASE 5: SaaS Features (Post-MVP - Semanas 14+)
|
||||
|
||||
**Nota**: Esta fase se desarrolla DESPUES de tener el MVP operativo validado
|
||||
|
||||
#### Componentes a Desarrollar (En Orden)
|
||||
|
||||
1. **Definicion completa de Auth/Portales/Usuarios** (aunque ya existe, refinar)
|
||||
2. **Integracion Stripe** (pagos y suscripciones)
|
||||
3. **Wallet interno** (fondeo de cuentas)
|
||||
4. **Agentes con diferentes perfiles de riesgo** (Atlas, Orion, Nova)
|
||||
5. **Contenido educativo** (cursos, quizzes)
|
||||
6. **Membresias y tienda**
|
||||
|
||||
| ID | Tarea | Perfil | Dependencia | Estimacion |
|
||||
|----|-------|--------|-------------|------------|
|
||||
| F5-01 | Completar integracion Stripe | BACKEND | F4-13 | 5 dias |
|
||||
| F5-02 | Implementar sistema de wallet | BACKEND | F5-01 | 5 dias |
|
||||
| F5-03 | Crear portal de inversion (agentes) | FRONTEND | F5-02 | 5 dias |
|
||||
| F5-04 | Modulo de educacion | FULL-STACK | F5-03 | 10 dias |
|
||||
| F5-05 | Sistema de membresias | BACKEND | F5-01 | 5 dias |
|
||||
| F5-06 | Tienda in-app | FULL-STACK | F5-05 | 7 dias |
|
||||
|
||||
---
|
||||
|
||||
## 3. Estrategia de Paralelizacion
|
||||
|
||||
### Diagrama de Dependencias
|
||||
|
||||
```
|
||||
Semana 1 Semana 2-4 Semana 5-7 Semana 8-10 Semana 11-13
|
||||
--------- ---------- ---------- ----------- ------------
|
||||
|
||||
[FASE 0] ──────┬──> [FASE 1: ML] ─────────────────────────────────────────>
|
||||
│ │ │
|
||||
│ └──> [FASE 2: LLM] ────>│
|
||||
│ │ │
|
||||
│ └──> [FASE 3: MCP] ───>│
|
||||
│ │ │
|
||||
│ │ [FASE 4: UI] ──>
|
||||
│ │ │
|
||||
└───────────────────────────────────────────────┴──> MVP
|
||||
```
|
||||
|
||||
### Equipos Paralelos Sugeridos
|
||||
|
||||
| Equipo | Perfiles | Fases | Foco |
|
||||
|--------|----------|-------|------|
|
||||
| **ML Team** | ML-SPECIALIST x2 | F0, F1, F2 (parcial) | Modelos y entrenamiento |
|
||||
| **LLM Team** | ML-SPECIALIST, BACKEND | F2 | Fine-tuning y agente |
|
||||
| **Integration Team** | BACKEND x2, MCP-DEVELOPER | F3 | MCP Server e integraciones |
|
||||
| **Frontend Team** | FRONTEND x2 | F4 | Dashboard y visualizacion |
|
||||
| **DevOps** | DEVOPS | Transversal | Infraestructura |
|
||||
| **QA** | TESTING | Transversal | Testing continuo |
|
||||
|
||||
### Sincronizacion
|
||||
|
||||
- **Daily standup**: 15min por equipo
|
||||
- **Weekly sync**: Viernes, todos los equipos (30min)
|
||||
- **Sprint review**: Cada 2 semanas
|
||||
- **Checkpoints criticos**:
|
||||
- Fin F1: Modelos ML validados
|
||||
- Fin F2: LLM fine-tuned funcionando
|
||||
- Fin F3: Ejecucion automatizada lista
|
||||
- Fin F4: MVP completo
|
||||
|
||||
---
|
||||
|
||||
## 4. Metricas de Exito por Fase
|
||||
|
||||
### FASE 1: Modelos ML
|
||||
|
||||
| Metrica | Target | Critico |
|
||||
|---------|--------|---------|
|
||||
| RangePredictor MAE | < 0.5% | Si |
|
||||
| Directional Accuracy | > 70% | Si |
|
||||
| AMD Detector Accuracy | > 70% | Si |
|
||||
| TPSL Win Rate (conservative) | > 80% | Si |
|
||||
| TPSL ROC-AUC | > 0.90 | Si |
|
||||
| Backtest Profit Factor | > 2.0 | Si |
|
||||
| Out-of-Sample Performance | > 60% del in-sample | Si |
|
||||
|
||||
### FASE 2: LLM Agent
|
||||
|
||||
| Metrica | Target | Critico |
|
||||
|---------|--------|---------|
|
||||
| Decision Accuracy | > 75% | Si |
|
||||
| Response Latency | < 2s | Si |
|
||||
| Strategy Adherence | > 90% | Si |
|
||||
| Risk Rule Compliance | 100% | Si |
|
||||
|
||||
### FASE 3: Ejecucion
|
||||
|
||||
| Metrica | Target | Critico |
|
||||
|---------|--------|---------|
|
||||
| Order Execution Success | > 99% | Si |
|
||||
| Latency MT4 | < 500ms | Si |
|
||||
| Latency Binance | < 200ms | Si |
|
||||
| Slippage | < 3 pips | Si |
|
||||
|
||||
### FASE 4: Visualizacion
|
||||
|
||||
| Metrica | Target | Critico |
|
||||
|---------|--------|---------|
|
||||
| Chart Load Time | < 1s | Si |
|
||||
| Real-time Update | < 100ms | Si |
|
||||
| UI Responsiveness | 60fps | No |
|
||||
|
||||
---
|
||||
|
||||
## 5. Riesgos y Mitigaciones
|
||||
|
||||
| Riesgo | Probabilidad | Impacto | Mitigacion |
|
||||
|--------|--------------|---------|------------|
|
||||
| Modelos ML no alcanzan 80% win rate | Media | Alto | Ajustar RR ratios, filtros de confianza |
|
||||
| Fine-tuning LLM insuficiente | Media | Alto | Aumentar dataset, iterar |
|
||||
| Latencia de ejecucion alta | Baja | Alto | MetaAPI cloud, optimizar network |
|
||||
| Diferencias de precio entre brokers | Alta | Medio | Price adjuster, validacion pre-trade |
|
||||
| GPU insuficiente para LLM | Baja | Alto | Usar modelo mas pequeno (Mistral 7B) |
|
||||
| Overfitting en modelos ML | Media | Alto | Walk-forward validation, regularizacion |
|
||||
|
||||
---
|
||||
|
||||
## 6. Proximos Pasos Inmediatos
|
||||
|
||||
### Dia 1-2: Preparacion
|
||||
|
||||
1. **Verificar disponibilidad de datos historicos**
|
||||
- 10 anos de XAUUSD, EURUSD, GBPUSD, USDJPY
|
||||
- Datos de BTC/USDT
|
||||
|
||||
2. **Configurar entorno de entrenamiento**
|
||||
- GPU disponible (RTX 5060 Ti 16GB)
|
||||
- Ollama instalado
|
||||
- Dependencias Python
|
||||
|
||||
3. **Crear rama de desarrollo**
|
||||
- `feature/ml-first-development`
|
||||
|
||||
### Dia 3-7: Fase 0
|
||||
|
||||
1. **Implementar pipeline de datos**
|
||||
2. **Crear splits temporales**
|
||||
3. **Validar datasets**
|
||||
|
||||
### Semana 2+: Fase 1
|
||||
|
||||
1. **Comenzar entrenamiento de modelos**
|
||||
2. **Documentar resultados**
|
||||
3. **Iterar hasta alcanzar metricas**
|
||||
|
||||
---
|
||||
|
||||
## 7. Referencias
|
||||
|
||||
- [MODELOS-ML-DEFINICION.md](../docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/MODELOS-ML-DEFINICION.md)
|
||||
- [FEATURES-TARGETS-ML.md](../docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/FEATURES-TARGETS-ML.md)
|
||||
- [ESTRATEGIA-AMD-COMPLETA.md](../docs/02-definicion-modulos/OQI-006-ml-signals/estrategias/ESTRATEGIA-AMD-COMPLETA.md)
|
||||
- [INTEGRACION-METATRADER4.md](../docs/01-arquitectura/INTEGRACION-METATRADER4.md)
|
||||
- [AUTO_TRADING.md](../apps/llm-agent/AUTO_TRADING.md)
|
||||
- [PLAN-ML-LLM-TRADING.md](./PLAN-ML-LLM-TRADING.md)
|
||||
|
||||
---
|
||||
|
||||
**Documento Generado:** 2026-01-04
|
||||
**Proxima Revision:** Despues de aprobacion
|
||||
**Sistema:** NEXUS + SIMCO v2.2.0
|
||||
@ -1,368 +0,0 @@
|
||||
---
|
||||
id: "PLAN-LLM-TRADING-INTEGRATION-2026"
|
||||
title: "Plan de Desarrollo - LLM Trading Integration 2026"
|
||||
type: "Development Plan"
|
||||
project: "trading-platform"
|
||||
version: "1.0.0"
|
||||
created_date: "2026-01-04"
|
||||
updated_date: "2026-01-04"
|
||||
author: "Orquestador Agent - Trading Platform"
|
||||
status: "Active"
|
||||
---
|
||||
|
||||
# Plan de Desarrollo: LLM Trading Integration 2026
|
||||
|
||||
**Fecha:** 2026-01-04
|
||||
**Epica:** OQI-010 - LLM Trading Integration
|
||||
**Estado:** Planificacion Activa
|
||||
**Story Points Total:** 89 SP
|
||||
|
||||
---
|
||||
|
||||
## Resumen Ejecutivo
|
||||
|
||||
Este plan detalla la implementacion de la integracion avanzada del LLM para trading autonomo, incluyendo fine-tuning, MCP servers, gestion de riesgo y API de predicciones.
|
||||
|
||||
### Hardware Disponible
|
||||
|
||||
| Recurso | Especificacion |
|
||||
|---------|----------------|
|
||||
| GPU | NVIDIA 16GB VRAM |
|
||||
| Modelo Base | chatgpt-oss / Llama 3 8B |
|
||||
| Quantizacion | Q5_K_M (balance calidad/VRAM) |
|
||||
| Fine-tuning | LoRA (r=16, alpha=32) |
|
||||
|
||||
### Entregables Principales
|
||||
|
||||
1. **MCP Binance Connector** - Puerto 3606
|
||||
2. **LLM Fine-tuned** con estrategias AMD/ICT/SMC
|
||||
3. **Risk Management Service** integrado
|
||||
4. **API de Predicciones** para frontend
|
||||
5. **Sistema de Tracking** de predicciones
|
||||
|
||||
---
|
||||
|
||||
## Fase 1: Infraestructura (Semanas 1-2)
|
||||
|
||||
### Objetivo
|
||||
Establecer la infraestructura base para los nuevos componentes.
|
||||
|
||||
### Tareas
|
||||
|
||||
#### 1.1 MCP Binance Connector
|
||||
- [ ] Crear estructura del proyecto `apps/mcp-binance-connector/`
|
||||
- [ ] Implementar tools de market data (get_ticker, get_klines, get_orderbook)
|
||||
- [ ] Implementar tools de account (get_account, get_positions)
|
||||
- [ ] Implementar tools de orders (create_order, cancel_order)
|
||||
- [ ] Implementar tools de futures (positions, leverage)
|
||||
- [ ] Configurar Docker y puerto 3606
|
||||
- [ ] Tests unitarios y de integracion
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 8
|
||||
|
||||
#### 1.2 DDL PostgreSQL
|
||||
- [ ] Crear tabla `ml.llm_predictions`
|
||||
- [ ] Crear tabla `ml.prediction_outcomes`
|
||||
- [ ] Crear tabla `ml.llm_decisions`
|
||||
- [ ] Crear tabla `ml.risk_events`
|
||||
- [ ] Crear funcion `ml.calculate_prediction_accuracy()`
|
||||
- [ ] Crear indices de performance
|
||||
|
||||
**Responsable:** Database Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 1.3 Pipeline de Fine-Tuning
|
||||
- [ ] Configurar ambiente de entrenamiento
|
||||
- [ ] Crear script de generacion de dataset
|
||||
- [ ] Implementar dataset de estrategias AMD
|
||||
- [ ] Implementar dataset de conceptos ICT/SMC
|
||||
- [ ] Implementar dataset de risk management
|
||||
- [ ] Crear script de entrenamiento LoRA
|
||||
- [ ] Crear script de merge y conversion a GGUF
|
||||
|
||||
**Responsable:** ML Specialist
|
||||
**Story Points:** 8
|
||||
|
||||
### Entregables Fase 1
|
||||
- MCP Binance Connector funcionando en testnet
|
||||
- Tablas de PostgreSQL creadas
|
||||
- Pipeline de fine-tuning configurado
|
||||
|
||||
---
|
||||
|
||||
## Fase 2: Core LLM Features (Semanas 3-5)
|
||||
|
||||
### Objetivo
|
||||
Implementar las funcionalidades core del LLM trading agent.
|
||||
|
||||
### Tareas
|
||||
|
||||
#### 2.1 Fine-Tuning del Modelo
|
||||
- [ ] Generar dataset completo (>20,000 ejemplos)
|
||||
- [ ] Ejecutar entrenamiento LoRA (3 epochs)
|
||||
- [ ] Evaluar modelo con dataset de validacion
|
||||
- [ ] Optimizar hiperparametros si es necesario
|
||||
- [ ] Convertir a GGUF y cargar en Ollama
|
||||
- [ ] Validar respuestas del modelo fine-tuned
|
||||
|
||||
**Responsable:** ML Specialist
|
||||
**Story Points:** 8
|
||||
|
||||
#### 2.2 Risk Management Service
|
||||
- [ ] Implementar RiskManager class
|
||||
- [ ] Implementar position sizing calculator
|
||||
- [ ] Implementar drawdown monitor
|
||||
- [ ] Implementar circuit breaker
|
||||
- [ ] Implementar exposure tracker
|
||||
- [ ] Integrar con LLM decision flow
|
||||
- [ ] Tests unitarios
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 8
|
||||
|
||||
#### 2.3 ML Analyzer Service
|
||||
- [ ] Implementar MLAnalyzer class
|
||||
- [ ] Integracion con ML Engine (AMD, Range, ICT)
|
||||
- [ ] Calculo de confluence score
|
||||
- [ ] Generacion de explicaciones en lenguaje natural
|
||||
- [ ] Cache de predicciones en Redis
|
||||
|
||||
**Responsable:** ML Specialist
|
||||
**Story Points:** 5
|
||||
|
||||
#### 2.4 Risk Validation Pre-Trade
|
||||
- [ ] Implementar validacion antes de execute_trade
|
||||
- [ ] Verificar position size limits
|
||||
- [ ] Verificar daily drawdown
|
||||
- [ ] Verificar exposure total
|
||||
- [ ] Verificar trades diarios
|
||||
- [ ] Responder con razon si rechazado
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
### Entregables Fase 2
|
||||
- Modelo LLM fine-tuned funcionando
|
||||
- Risk Manager integrado
|
||||
- ML Analyzer con confluence score
|
||||
|
||||
---
|
||||
|
||||
## Fase 3: API e Integracion (Semanas 6-7)
|
||||
|
||||
### Objetivo
|
||||
Exponer APIs para frontend y completar integracion entre servicios.
|
||||
|
||||
### Tareas
|
||||
|
||||
#### 3.1 API de Predicciones REST
|
||||
- [ ] Endpoint POST /api/v1/predictions/analyze
|
||||
- [ ] Endpoint GET /api/v1/predictions/history/{symbol}
|
||||
- [ ] Endpoint GET /api/v1/predictions/accuracy/{symbol}
|
||||
- [ ] Endpoint GET /api/v1/predictions/active-signals
|
||||
- [ ] Documentacion OpenAPI
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 3.2 WebSocket Predicciones
|
||||
- [ ] Implementar PredictionWebSocketManager
|
||||
- [ ] Endpoint WS /ws/predictions/{symbol}
|
||||
- [ ] Broadcast de predicciones cada 5s
|
||||
- [ ] Manejo de conexiones/desconexiones
|
||||
- [ ] Rate limiting
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 3.3 MCP Orchestrator
|
||||
- [ ] Implementar MCPOrchestrator class
|
||||
- [ ] Metodo call_tool(server, tool, params)
|
||||
- [ ] Metodo get_combined_portfolio()
|
||||
- [ ] Metodo execute_trade_on_best_venue()
|
||||
- [ ] Integracion con LLM decision flow
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 3.4 Ejecucion de Trades MT4/Binance
|
||||
- [ ] Integracion completa con MCP MT4
|
||||
- [ ] Integracion completa con MCP Binance
|
||||
- [ ] Seleccion automatica de venue
|
||||
- [ ] Logging de trades ejecutados
|
||||
- [ ] Persistencia de decisiones
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 8
|
||||
|
||||
### Entregables Fase 3
|
||||
- API REST de predicciones funcionando
|
||||
- WebSocket real-time
|
||||
- Ejecucion de trades via MCP
|
||||
|
||||
---
|
||||
|
||||
## Fase 4: Tracking y Optimizacion (Semanas 8-9)
|
||||
|
||||
### Objetivo
|
||||
Implementar tracking de outcomes y optimizar el sistema.
|
||||
|
||||
### Tareas
|
||||
|
||||
#### 4.1 Tracking de Outcomes
|
||||
- [ ] Servicio de monitoreo de predicciones
|
||||
- [ ] Deteccion automatica de outcomes
|
||||
- [ ] Calculo de accuracy por simbolo
|
||||
- [ ] Calculo de profit factor
|
||||
- [ ] Persistencia en prediction_outcomes
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 4.2 Metricas de Accuracy
|
||||
- [ ] Dashboard de accuracy por modelo
|
||||
- [ ] Grafico de accuracy temporal
|
||||
- [ ] Filtros por simbolo/timeframe
|
||||
- [ ] Export de datos
|
||||
|
||||
**Responsable:** Frontend Developer
|
||||
**Story Points:** 5
|
||||
|
||||
#### 4.3 Circuit Breaker Automatico
|
||||
- [ ] Deteccion de daily drawdown limit
|
||||
- [ ] Deteccion de perdidas consecutivas
|
||||
- [ ] Pausa automatica de trading
|
||||
- [ ] Alertas a usuario
|
||||
- [ ] Resume manual requerido
|
||||
|
||||
**Responsable:** Backend Developer
|
||||
**Story Points:** 3
|
||||
|
||||
#### 4.4 Fine-Tuning con Datos de Produccion
|
||||
- [ ] Recolectar decisiones correctas
|
||||
- [ ] Generar nuevos ejemplos de training
|
||||
- [ ] Re-entrenar modelo
|
||||
- [ ] A/B testing de versiones
|
||||
- [ ] Rollout gradual
|
||||
|
||||
**Responsable:** ML Specialist
|
||||
**Story Points:** 8
|
||||
|
||||
### Entregables Fase 4
|
||||
- Sistema de tracking funcionando
|
||||
- Dashboard de accuracy
|
||||
- Circuit breaker automatico
|
||||
|
||||
---
|
||||
|
||||
## Fase 5: Testing y Deployment (Semana 10)
|
||||
|
||||
### Objetivo
|
||||
Validar el sistema completo y desplegar a produccion.
|
||||
|
||||
### Tareas
|
||||
|
||||
#### 5.1 Tests de Integracion
|
||||
- [ ] Tests E2E del flujo completo
|
||||
- [ ] Tests de MCP Binance con testnet
|
||||
- [ ] Tests de risk management
|
||||
- [ ] Tests de persistence
|
||||
- [ ] Coverage > 70%
|
||||
|
||||
**Responsable:** Testing
|
||||
**Story Points:** 3
|
||||
|
||||
#### 5.2 Backtesting de Decisiones
|
||||
- [ ] Ejecutar backtesting con datos historicos
|
||||
- [ ] Validar que risk limits se respetan
|
||||
- [ ] Comparar accuracy real vs backtesting
|
||||
- [ ] Documentar resultados
|
||||
|
||||
**Responsable:** ML Specialist
|
||||
**Story Points:** 5
|
||||
|
||||
#### 5.3 Documentacion Final
|
||||
- [ ] Actualizar README de cada componente
|
||||
- [ ] Documentar APIs con OpenAPI
|
||||
- [ ] Crear guia de operaciones
|
||||
- [ ] Actualizar AGENTS.md
|
||||
|
||||
**Responsable:** Tech Writer
|
||||
**Story Points:** 3
|
||||
|
||||
#### 5.4 Deployment
|
||||
- [ ] Build de imagenes Docker
|
||||
- [ ] Configurar docker-compose.llm-advanced.yaml
|
||||
- [ ] Deploy a staging
|
||||
- [ ] Smoke tests
|
||||
- [ ] Deploy a produccion
|
||||
- [ ] Monitoreo inicial
|
||||
|
||||
**Responsable:** DevOps
|
||||
**Story Points:** 5
|
||||
|
||||
### Entregables Fase 5
|
||||
- Sistema completo testeado
|
||||
- Documentacion actualizada
|
||||
- Deploy a produccion
|
||||
|
||||
---
|
||||
|
||||
## Resumen de Story Points por Fase
|
||||
|
||||
| Fase | Descripcion | SP | Duracion |
|
||||
|------|-------------|-----|----------|
|
||||
| Fase 1 | Infraestructura | 21 | 2 semanas |
|
||||
| Fase 2 | Core LLM | 26 | 2-3 semanas |
|
||||
| Fase 3 | API e Integracion | 23 | 2 semanas |
|
||||
| Fase 4 | Tracking y Optimizacion | 21 | 2 semanas |
|
||||
| Fase 5 | Testing y Deployment | 16 | 1 semana |
|
||||
| **Total** | | **107** | **9-10 semanas** |
|
||||
|
||||
---
|
||||
|
||||
## Riesgos y Mitigaciones
|
||||
|
||||
| Riesgo | Probabilidad | Impacto | Mitigacion |
|
||||
|--------|--------------|---------|------------|
|
||||
| VRAM insuficiente | Media | Alto | LoRA + quantizacion Q5_K_M |
|
||||
| Latencia alta | Media | Alto | Cache, batch processing |
|
||||
| Errores del LLM | Alta | Critico | Risk limits, paper trading |
|
||||
| Rate limits Binance | Media | Medio | Rate limiter, caching |
|
||||
| Fine-tuning overfitting | Media | Alto | Validacion, early stopping |
|
||||
|
||||
---
|
||||
|
||||
## Metricas de Exito
|
||||
|
||||
| Metrica | Target | Medicion |
|
||||
|---------|--------|----------|
|
||||
| Direction Accuracy | >65% | Semanal |
|
||||
| Response Time | <5s | Continuo |
|
||||
| Risk Adherence | 100% | Continuo |
|
||||
| System Uptime | >99% | Continuo |
|
||||
| Fine-tuning Perplexity | <3.0 | Post-training |
|
||||
|
||||
---
|
||||
|
||||
## Siguiente Paso Inmediato
|
||||
|
||||
1. **Crear MCP Binance Connector** - Estructura base del proyecto
|
||||
2. **Ejecutar DDL** - Crear nuevas tablas en PostgreSQL
|
||||
3. **Preparar Dataset** - Iniciar recoleccion de ejemplos de training
|
||||
|
||||
---
|
||||
|
||||
## Referencias
|
||||
|
||||
- [Epica OQI-010](../docs/02-definicion-modulos/OQI-010-llm-trading-integration/README.md)
|
||||
- [Integracion LLM Fine-Tuning](../docs/01-arquitectura/INTEGRACION-LLM-FINE-TUNING.md)
|
||||
- [MCP Binance Spec](../docs/01-arquitectura/MCP-BINANCE-CONNECTOR-SPEC.md)
|
||||
- [Plan ML-LLM-Trading Original](./PLAN-ML-LLM-TRADING.md)
|
||||
|
||||
---
|
||||
|
||||
**Documento Generado:** 2026-01-04
|
||||
**Autor:** Orquestador Agent - Trading Platform
|
||||
**Version:** 1.0.0
|
||||
@ -1,315 +0,0 @@
|
||||
# Plan de Desarrollo: ML, LLM y Trading Operations
|
||||
|
||||
**Fecha:** 2025-12-07
|
||||
**Tech Leader:** Agente Orquestador
|
||||
**Estado:** En Desarrollo Paralelo
|
||||
|
||||
---
|
||||
|
||||
## Resumen Ejecutivo
|
||||
|
||||
Este plan coordina el desarrollo de las capacidades de Machine Learning, integración LLM local, y los agentes de trading operativos (Atlas, Orion, Nova) para Trading Platform.
|
||||
|
||||
### Recursos Disponibles
|
||||
|
||||
| Recurso | Especificación |
|
||||
|---------|----------------|
|
||||
| GPU | NVIDIA RTX 5060 Ti (16GB VRAM) |
|
||||
| TradingAgent Original | `[LEGACY: apps/ml-engine - migrado desde TradingAgent]` |
|
||||
| ML Engine Base | `apps/ml-engine/` (estructura migrada) |
|
||||
| LLM Local | chatgpt-oss (a configurar en GPU) |
|
||||
|
||||
---
|
||||
|
||||
## Track 1: ML Engine - Migración Avanzada
|
||||
|
||||
### Objetivo
|
||||
Migrar completamente los modelos del TradingAgent original al nuevo ML Engine con soporte GPU.
|
||||
|
||||
### Componentes a Migrar
|
||||
|
||||
| Componente | Origen | Destino | Estado |
|
||||
|------------|--------|---------|--------|
|
||||
| RangePredictor | TradingAgent/src/models/ | apps/ml-engine/src/models/ | Parcial |
|
||||
| TPSLClassifier | TradingAgent/src/models/ | apps/ml-engine/src/models/ | Parcial |
|
||||
| SignalGenerator | TradingAgent/src/models/ | apps/ml-engine/src/models/ | Parcial |
|
||||
| AMDDetector | TradingAgent/src/models/ | apps/ml-engine/src/models/ | Pendiente |
|
||||
| Phase2Pipeline | TradingAgent/src/pipelines/ | apps/ml-engine/src/pipelines/ | Pendiente |
|
||||
| WalkForward | TradingAgent/src/training/ | apps/ml-engine/src/training/ | Pendiente |
|
||||
| Backtesting | TradingAgent/src/backtesting/ | apps/ml-engine/src/backtesting/ | Pendiente |
|
||||
| Dashboard RT | TradingAgent/src/visualization/ | apps/ml-engine/src/visualization/ | Pendiente |
|
||||
|
||||
### Tareas Específicas
|
||||
|
||||
1. **Migrar AMDDetector**
|
||||
- Detector de fases Accumulation/Manipulation/Distribution
|
||||
- Crítico para filtrado de señales
|
||||
|
||||
2. **Migrar Pipeline Phase2**
|
||||
- Entrenamiento completo del sistema
|
||||
- Walk-forward validation
|
||||
|
||||
3. **Configurar GPU Training**
|
||||
- XGBoost con CUDA
|
||||
- Configurar para RTX 5060 Ti
|
||||
|
||||
4. **Implementar API completa**
|
||||
- Endpoints de señales en tiempo real
|
||||
- WebSocket para streaming
|
||||
|
||||
5. **Integrar con datos históricos**
|
||||
- 10 años de datos XAUUSD, EURUSD, GBPUSD
|
||||
- Pipeline de ingesta desde MySQL
|
||||
|
||||
---
|
||||
|
||||
## Track 2: LLM Agent - Integración Local
|
||||
|
||||
### Objetivo
|
||||
Implementar el copiloto de trading basado en LLM ejecutándose localmente en GPU.
|
||||
|
||||
### Arquitectura
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ LLM SERVICE (Local GPU) │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ LLM Model │ │ Trading Tools │ │
|
||||
│ │ (chatgpt-oss) │ │ (Functions) │ │
|
||||
│ └────────┬────────┘ └────────┬────────┘ │
|
||||
│ │ │ │
|
||||
│ ┌────────▼────────────────────▼────────┐ │
|
||||
│ │ LLM Orchestrator │ │
|
||||
│ │ - Prompt Templates │ │
|
||||
│ │ - Tool Calling │ │
|
||||
│ │ - Context Management │ │
|
||||
│ └──────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ TRADING PLATFORM │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ ML Engine│ │ Market │ │ Portfolio│ │ Trading │ │
|
||||
│ │ Signals │ │ Data │ │ State │ │ Execution│ │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Opciones de Modelo Local
|
||||
|
||||
| Modelo | VRAM Requerida | Capacidad | Recomendación |
|
||||
|--------|----------------|-----------|---------------|
|
||||
| Mistral 7B | ~8GB | Buena | Viable |
|
||||
| Llama 3 8B | ~10GB | Muy buena | Recomendado |
|
||||
| CodeLlama 7B | ~8GB | Code-focused | Alternativa |
|
||||
| Phi-3 Mini | ~4GB | Compacto | Backup |
|
||||
|
||||
### Tareas Específicas
|
||||
|
||||
1. **Configurar servidor LLM local**
|
||||
- Opciones: Ollama, vLLM, text-generation-webui
|
||||
- Endpoint compatible OpenAI API
|
||||
|
||||
2. **Implementar Trading Tools**
|
||||
- get_signal(symbol) → Señal ML actual
|
||||
- analyze_chart(symbol, timeframe) → Análisis técnico
|
||||
- check_portfolio() → Estado del portfolio
|
||||
- execute_trade(params) → Ejecutar orden
|
||||
- set_alert(params) → Crear alerta
|
||||
|
||||
3. **Prompt Engineering**
|
||||
- System prompt especializado en trading
|
||||
- Templates para análisis, estrategias, explicaciones
|
||||
|
||||
4. **Gestión de Contexto**
|
||||
- Historial de conversación (Redis)
|
||||
- Contexto de mercado en tiempo real
|
||||
- Perfil del usuario
|
||||
|
||||
---
|
||||
|
||||
## Track 3: Trading Agents - Operaciones
|
||||
|
||||
### Objetivo
|
||||
Implementar los agentes de trading automático (Atlas, Orion, Nova) que operan las cuentas de inversión.
|
||||
|
||||
### Arquitectura de Agentes
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ TRADING AGENTS SERVICE │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │
|
||||
│ │ ATLAS │ │ ORION │ │ NOVA │ │
|
||||
│ │ Conservador │ │ Moderado │ │ Agresivo │ │
|
||||
│ │ - Grid │ │ - Trend │ │ - Momentum │ │
|
||||
│ │ - Mean Rev │ │ - Breakout │ │ - Scalping │ │
|
||||
│ │ - BTC/ETH │ │ - Top 10 │ │ - All Pairs │ │
|
||||
│ └───────┬────────┘ └───────┬────────┘ └───────┬────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ┌───────▼──────────────────▼──────────────────▼───────┐ │
|
||||
│ │ EXECUTION ENGINE │ │
|
||||
│ │ - Risk Management │ │
|
||||
│ │ - Position Sizing │ │
|
||||
│ │ - Order Execution (Binance API) │ │
|
||||
│ │ - PnL Tracking │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌───────────────────────────▼──────────────────────────┐ │
|
||||
│ │ SIGNAL CONSUMER │ │
|
||||
│ │ - ML Engine Integration │ │
|
||||
│ │ - Signal Filtering per Agent Profile │ │
|
||||
│ │ - Trade Journaling │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Perfiles de Agentes
|
||||
|
||||
#### Atlas (Conservador)
|
||||
```yaml
|
||||
name: Atlas
|
||||
profile: conservative
|
||||
strategies:
|
||||
- mean_reversion
|
||||
- grid_trading
|
||||
pairs:
|
||||
- BTC/USDT
|
||||
- ETH/USDT
|
||||
risk:
|
||||
max_drawdown: 5%
|
||||
position_size: 2%
|
||||
max_positions: 3
|
||||
targets:
|
||||
monthly_return: 3-5%
|
||||
win_rate_min: 60%
|
||||
```
|
||||
|
||||
#### Orion (Moderado)
|
||||
```yaml
|
||||
name: Orion
|
||||
profile: moderate
|
||||
strategies:
|
||||
- trend_following
|
||||
- breakout
|
||||
pairs:
|
||||
- BTC/USDT
|
||||
- ETH/USDT
|
||||
- SOL/USDT
|
||||
- BNB/USDT
|
||||
# + Top 10
|
||||
risk:
|
||||
max_drawdown: 10%
|
||||
position_size: 3%
|
||||
max_positions: 5
|
||||
targets:
|
||||
monthly_return: 5-10%
|
||||
win_rate_min: 55%
|
||||
```
|
||||
|
||||
#### Nova (Agresivo)
|
||||
```yaml
|
||||
name: Nova
|
||||
profile: aggressive
|
||||
strategies:
|
||||
- momentum
|
||||
- scalping
|
||||
- altcoin_rotation
|
||||
pairs:
|
||||
- ALL available
|
||||
risk:
|
||||
max_drawdown: 20%
|
||||
position_size: 5%
|
||||
max_positions: 10
|
||||
targets:
|
||||
monthly_return: 10%+
|
||||
win_rate_min: 50%
|
||||
```
|
||||
|
||||
### Tareas Específicas
|
||||
|
||||
1. **Implementar Agent Base Class**
|
||||
- Ciclo de vida del agente
|
||||
- Risk management
|
||||
- Position sizing
|
||||
|
||||
2. **Implementar Estrategias**
|
||||
- MeanReversionStrategy
|
||||
- GridTradingStrategy
|
||||
- TrendFollowingStrategy
|
||||
- BreakoutStrategy
|
||||
- MomentumStrategy
|
||||
- ScalpingStrategy
|
||||
|
||||
3. **Integración Binance**
|
||||
- Paper trading (testnet)
|
||||
- Real trading (mainnet)
|
||||
- WebSocket feeds
|
||||
|
||||
4. **Sistema de Distribución**
|
||||
- Cálculo de PnL
|
||||
- Performance fees
|
||||
- Distribución automática
|
||||
|
||||
---
|
||||
|
||||
## Dependencias entre Tracks
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ DEPENDENCIAS │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Track 1 (ML Engine) ──────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ Señales │ Señales │
|
||||
│ ▼ ▼ │
|
||||
│ Track 2 (LLM Agent) ◄───────► Track 3 (Trading Agents) │
|
||||
│ │
|
||||
│ LLM interpreta Trading agents consumen │
|
||||
│ señales y sugiere señales y ejecutan trades │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Épicas Relacionadas
|
||||
|
||||
| Épica | Descripción | Tracks Involucrados |
|
||||
|-------|-------------|---------------------|
|
||||
| OQI-004 | Cuentas de Inversión | Track 3 |
|
||||
| OQI-006 | Señales ML | Track 1 |
|
||||
| OQI-007 | LLM Agent | Track 2 |
|
||||
| OQI-008 | Portfolio Manager | Track 2, 3 |
|
||||
|
||||
---
|
||||
|
||||
## Próximos Pasos Inmediatos
|
||||
|
||||
### Track 1 - ML Engine
|
||||
1. Migrar AMDDetector completo
|
||||
2. Migrar Phase2Pipeline
|
||||
3. Configurar entrenamiento GPU
|
||||
4. Implementar API de señales
|
||||
|
||||
### Track 2 - LLM Agent
|
||||
1. Configurar Ollama con Llama 3 8B
|
||||
2. Crear servicio FastAPI para LLM
|
||||
3. Implementar Trading Tools básicos
|
||||
4. Crear prompt templates
|
||||
|
||||
### Track 3 - Trading Agents
|
||||
1. Crear estructura base de agentes
|
||||
2. Implementar Atlas (estrategia conservadora)
|
||||
3. Integrar con señales ML
|
||||
4. Paper trading en Binance Testnet
|
||||
|
||||
---
|
||||
|
||||
*Plan generado por Tech-Leader Agent*
|
||||
*Fecha: 2025-12-07*
|
||||
@ -1,390 +0,0 @@
|
||||
# Plan de Desarrollo Refinado
|
||||
## Trading Platform - Version Final
|
||||
|
||||
**Fecha:** 2026-01-07
|
||||
**Version:** 2.0.0 (Refinado)
|
||||
**Estado:** LISTO PARA EJECUCION
|
||||
**Basado en:**
|
||||
- ANALISIS-CONSOLIDADO-FASE1-2026-01-07.md
|
||||
- VALIDACION-PLAN-VS-ANALISIS-2026-01-07.md
|
||||
- ANALISIS-DEPENDENCIAS-2026-01-07.md
|
||||
|
||||
---
|
||||
|
||||
## 1. CAMBIOS RESPECTO AL PLAN ORIGINAL
|
||||
|
||||
### 1.1 Tareas Agregadas
|
||||
|
||||
| Sprint | Tarea Nueva | Razon |
|
||||
|--------|-------------|-------|
|
||||
| 3 | S3-T0: Documentar EA Bridge | Dependencia critica no documentada |
|
||||
| 2 | S2-T7: Admin controllers | Gap identificado en validacion |
|
||||
| 5 | S5-T7: Contract tests | Dependencias entre servicios |
|
||||
|
||||
### 1.2 Orden de Ejecucion Ajustado
|
||||
|
||||
Basado en analisis de dependencias, se ajusto el orden interno de cada sprint.
|
||||
|
||||
### 1.3 Criterios de Aceptacion Refinados
|
||||
|
||||
| Criterio Original | Criterio Refinado | Razon |
|
||||
|-------------------|-------------------|-------|
|
||||
| R^2 > 0.10 | R^2 > 0.05 (minimo aceptable) | Realismo |
|
||||
| Live trading OK | Live trading + Mock fallback | Dependencia EA Bridge |
|
||||
|
||||
---
|
||||
|
||||
## 2. PLAN REFINADO POR SPRINTS
|
||||
|
||||
### SPRINT 1: ESTABILIZACION ML ENGINE (5-7 dias)
|
||||
|
||||
#### Objetivo
|
||||
Resolver problemas criticos de ML y establecer baseline funcional.
|
||||
|
||||
#### Tareas en Orden de Ejecucion
|
||||
|
||||
| # | ID | Tarea | Archivo(s) | Deps | Entregable |
|
||||
|---|-----|-------|-----------|------|------------|
|
||||
| 1 | S1-T1 | Analizar features RangePredictor | `src/data/features.py` | - | Reporte de features |
|
||||
| 2 | S1-T2 | Revisar normalizacion | `src/data/features.py` | S1-T1 | Fix normalizacion |
|
||||
| 3 | S1-T3 | Verificar data leakage | `src/data/targets.py` | S1-T1 | Reporte leakage |
|
||||
| 4 | S1-T4a | Corregir RangePredictor | `src/models/range_predictor.py` | S1-T2,T3 | Modelo corregido |
|
||||
| 5 | S1-T4b | Reentrenar modelos | `src/training/*.py` | S1-T4a | Modelos nuevos |
|
||||
| 6 | S1-T5 | Auto-load en API | `src/api/main.py` | S1-T4b | API funcional |
|
||||
| 7 | S1-T6 | Validacion OOS | Scripts nuevos | S1-T5 | Reporte OOS |
|
||||
| 8 | S1-T7 | Tests unitarios | `tests/` | S1-T5 | Coverage > 70% |
|
||||
|
||||
#### Metricas de Exito Sprint 1
|
||||
|
||||
| Metrica | Minimo Aceptable | Objetivo |
|
||||
|---------|-----------------|----------|
|
||||
| RangePredictor R^2 | > 0.05 | > 0.15 |
|
||||
| API Response Time | < 1000ms | < 500ms |
|
||||
| Test Coverage | > 50% | > 70% |
|
||||
| Modelos cargados | 100% | 100% |
|
||||
|
||||
#### Plan de Contingencia Sprint 1
|
||||
|
||||
Si R^2 < 0.05 despues de 5 dias:
|
||||
1. Cambiar a modelo baseline (media movil)
|
||||
2. Documentar limitaciones
|
||||
3. Continuar con Sprint 2 usando baseline
|
||||
4. Crear ticket para iteracion futura de ML
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 2: INTEGRACION BACKEND (5 dias)
|
||||
|
||||
#### Objetivo
|
||||
Completar servicios de integracion y seguridad basica.
|
||||
|
||||
#### Tareas en Orden de Ejecucion
|
||||
|
||||
| # | ID | Tarea | Archivo(s) | Deps | Entregable |
|
||||
|---|-----|-------|-----------|------|------------|
|
||||
| 1 | S2-T1 | ml-integration.service.ts | `src/modules/ml/services/` | Sprint 1 | Servicio completo |
|
||||
| 2 | S2-T2 | Auth paper trading | `src/modules/trading/trading.routes.ts` | - | Endpoints protegidos |
|
||||
| 3 | S2-T3 | Auth investment | `src/modules/investment/investment.routes.ts` | - | Endpoints protegidos |
|
||||
| 4 | S2-T4 | agents.service.ts | `src/modules/agents/services/` | S2-T1 | Orquestacion basica |
|
||||
| 5 | S2-T5 | Users module | `src/modules/users/` | - | CRUD usuarios |
|
||||
| 6 | S2-T6 | Tests integracion | `src/__tests__/integration/` | S2-T1 | Tests pasando |
|
||||
| 7 | S2-T7 | Admin controllers | `src/modules/admin/` | S2-T5 | Admin basico |
|
||||
|
||||
#### Metricas de Exito Sprint 2
|
||||
|
||||
| Metrica | Minimo Aceptable | Objetivo |
|
||||
|---------|-----------------|----------|
|
||||
| Endpoints con auth | 100% (paper/investment) | 100% |
|
||||
| ml-integration completo | 100% metodos | 100% |
|
||||
| Tests integracion | > 10 tests | > 20 tests |
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 3: LLM Y TRADING AGENTS (5-7 dias)
|
||||
|
||||
#### Objetivo
|
||||
Completar agentes inteligentes y trading automatizado.
|
||||
|
||||
#### Tareas en Orden de Ejecucion
|
||||
|
||||
| # | ID | Tarea | Archivo(s) | Deps | Entregable |
|
||||
|---|-----|-------|-----------|------|------------|
|
||||
| 0 | S3-T0 | Documentar EA Bridge | `docs/EA-BRIDGE.md` | - | Documentacion |
|
||||
| 1 | S3-T1 | MCPOrchestrator completo | `src/services/mcp_orchestrator.py` | - | Portfolio consolidado |
|
||||
| 2 | S3-T2 | Live trading execution | `src/tools/trading.py` | S3-T1 | Trading funcional |
|
||||
| 3 | S3-T3 | Persistencia decisiones | `src/services/auto_trade_service.py` | S3-T2 | Decisiones en BD |
|
||||
| 4 | S3-T4 | Rate limiting | `src/api/routes.py` | - | Limites aplicados |
|
||||
| 5 | S3-T5 | Scalping strategy | `src/strategies/scalping.py` (nuevo) | - | Estrategia funcional |
|
||||
| 6 | S3-T6 | Persistencia trades | `src/persistence/db_manager.py` (nuevo) | - | Trades en BD |
|
||||
| 7 | S3-T7 | WebSocket signals | `src/signals/ws_consumer.py` (nuevo) | S3-T6 | Real-time signals |
|
||||
|
||||
#### Configuracion Scalping Strategy
|
||||
|
||||
```yaml
|
||||
scalping:
|
||||
enabled: true
|
||||
description: "Fast in-and-out trades for Nova"
|
||||
suitable_for:
|
||||
- nova
|
||||
parameters:
|
||||
tick_interval: "1m"
|
||||
spread_threshold: 0.05
|
||||
min_profit_ticks: 2
|
||||
max_position_time_seconds: 300
|
||||
rsi_period: 7
|
||||
rsi_oversold: 25
|
||||
rsi_overbought: 75
|
||||
indicators:
|
||||
- type: rsi
|
||||
period: 7
|
||||
- type: ema
|
||||
period: 5
|
||||
- type: volume
|
||||
period: 10
|
||||
```
|
||||
|
||||
#### Metricas de Exito Sprint 3
|
||||
|
||||
| Metrica | Minimo Aceptable | Objetivo |
|
||||
|---------|-----------------|----------|
|
||||
| Portfolio consolidado | MT4 + Binance | Completo |
|
||||
| Live trading | Mock funcional | Real si EA Bridge disponible |
|
||||
| Rate limiting | 60 req/min | 100 req/min |
|
||||
| Scalping tests | > 5 tests | > 10 tests |
|
||||
| Trades persistidos | 100% | 100% |
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 4: FRONTEND Y UX (5 dias)
|
||||
|
||||
#### Objetivo
|
||||
Mejorar experiencia de usuario y completar modulos faltantes.
|
||||
|
||||
#### Tareas en Orden de Ejecucion
|
||||
|
||||
| # | ID | Tarea | Archivo(s) | Deps | Entregable |
|
||||
|---|-----|-------|-----------|------|------------|
|
||||
| 1 | S4-T1 | WebSocket trading | `src/services/websocket.service.ts` | Sprint 2 | Real-time prices |
|
||||
| 2 | S4-T2 | Streaming LLM | `src/modules/assistant/pages/Assistant.tsx` | Sprint 3 | Chat streaming |
|
||||
| 3 | S4-T3 | Certificados PDF | `src/modules/education/services/certificate.service.ts` | - | PDFs descargables |
|
||||
| 4 | S4-T4 | Investment conectado | `src/modules/investment/` | Sprint 2 | Datos reales |
|
||||
| 5 | S4-T5 | Dashboard basico | `src/modules/dashboard/` | - | Overview funcional |
|
||||
|
||||
#### Metricas de Exito Sprint 4
|
||||
|
||||
| Metrica | Minimo Aceptable | Objetivo |
|
||||
|---------|-----------------|----------|
|
||||
| WebSocket latencia | < 500ms | < 200ms |
|
||||
| Streaming funcionando | Si | Si |
|
||||
| Certificados | Descargables | Con verificacion |
|
||||
| Investment data | Backend conectado | Completo |
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 5: SEGURIDAD Y TESTING (5-7 dias)
|
||||
|
||||
#### Objetivo
|
||||
Hardening para produccion y cobertura de tests.
|
||||
|
||||
#### Tareas en Orden de Ejecucion
|
||||
|
||||
| # | ID | Tarea | Archivo(s) | Deps | Entregable |
|
||||
|---|-----|-------|-----------|------|------------|
|
||||
| 1 | S5-T1 | RLS PostgreSQL | `ddl/rls/*.sql` | - | RLS habilitado |
|
||||
| 2 | S5-T2 | Rate limiting Backend | `src/middleware/rate-limiter.ts` | - | Limites globales |
|
||||
| 3 | S5-T3 | Auth MCP servers | `apps/mcp-*/src/middleware/auth.ts` | - | Bearer tokens |
|
||||
| 4 | S5-T4 | E2E tests core | `e2e/cypress/integration/` | Sprints 1-4 | > 30 tests |
|
||||
| 5 | S5-T5 | Integration tests | `src/__tests__/integration/` | - | > 20 tests |
|
||||
| 6 | S5-T6 | Security audit | - | S5-T1,T2,T3 | Reporte |
|
||||
| 7 | S5-T7 | Contract tests | `tests/contracts/` | - | Interfaces validadas |
|
||||
|
||||
#### RLS Policies a Implementar
|
||||
|
||||
```sql
|
||||
-- Auth schema
|
||||
CREATE POLICY user_own_sessions ON auth.sessions
|
||||
FOR ALL USING (user_id = current_setting('app.user_id')::UUID);
|
||||
|
||||
-- Trading schema
|
||||
CREATE POLICY user_own_orders ON trading.orders
|
||||
FOR ALL USING (user_id = current_setting('app.user_id')::UUID);
|
||||
|
||||
CREATE POLICY user_own_positions ON trading.positions
|
||||
FOR ALL USING (user_id = current_setting('app.user_id')::UUID);
|
||||
|
||||
-- Financial schema
|
||||
CREATE POLICY user_own_wallets ON financial.wallets
|
||||
FOR ALL USING (user_id = current_setting('app.user_id')::UUID);
|
||||
```
|
||||
|
||||
#### Metricas de Exito Sprint 5
|
||||
|
||||
| Metrica | Minimo Aceptable | Objetivo |
|
||||
|---------|-----------------|----------|
|
||||
| RLS tablas | 10 tablas criticas | 20+ tablas |
|
||||
| E2E tests | 30 tests | 50 tests |
|
||||
| Integration tests | 20 tests | 40 tests |
|
||||
| Vulnerabilidades criticas | 0 | 0 |
|
||||
| Coverage global | 50% | 60% |
|
||||
|
||||
---
|
||||
|
||||
## 3. TIMELINE CONSOLIDADO
|
||||
|
||||
```
|
||||
Semana 1: Sprint 1 (ML Engine)
|
||||
L M X J V
|
||||
| | | | |
|
||||
S1-T1-T2-T3-T4a
|
||||
|
|
||||
Semana 2: Sprint 1 (cont) + Sprint 2 (inicio)
|
||||
L M X J V
|
||||
| | | | |
|
||||
S1-T4b-T5-T6-T7 | S2-T1
|
||||
|
|
||||
Semana 3: Sprint 2 (Backend)
|
||||
L M X J V
|
||||
| | | | |
|
||||
S2-T2-T3-T4-T5-T6-T7
|
||||
|
||||
Semana 4: Sprint 3 (LLM + Agents)
|
||||
L M X J V S D
|
||||
| | | | | | |
|
||||
S3-T0-T1-T2-T3-T4-T5
|
||||
|
||||
Semana 5: Sprint 3 (cont) + Sprint 4
|
||||
L M X J V
|
||||
| | | | |
|
||||
S3-T6-T7 | S4-T1-T2-T3
|
||||
|
|
||||
Semana 6: Sprint 4 (cont) + Sprint 5
|
||||
L M X J V
|
||||
| | | | |
|
||||
S4-T4-T5 | S5-T1-T2-T3
|
||||
|
|
||||
Semana 7: Sprint 5 (Testing)
|
||||
L M X J V
|
||||
| | | | |
|
||||
S5-T4-T5-T6-T7
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. CHECKPOINTS DE VALIDACION
|
||||
|
||||
### Checkpoint 1 (Fin Semana 2)
|
||||
|
||||
**Criterios:**
|
||||
- [ ] ML API respondiendo correctamente
|
||||
- [ ] Al menos 1 modelo con R^2 > 0 (positivo)
|
||||
- [ ] Backend puede conectar a ML
|
||||
|
||||
**Decision Gate:** Si no se cumple, activar Plan B ML
|
||||
|
||||
### Checkpoint 2 (Fin Semana 3)
|
||||
|
||||
**Criterios:**
|
||||
- [ ] Backend 100% integrado
|
||||
- [ ] Todos los endpoints protegidos
|
||||
- [ ] Tests de integracion pasando
|
||||
|
||||
**Decision Gate:** Si no se cumple, extender Sprint 2
|
||||
|
||||
### Checkpoint 3 (Fin Semana 5)
|
||||
|
||||
**Criterios:**
|
||||
- [ ] MCPOrchestrator funcional
|
||||
- [ ] Trading (mock o real) operativo
|
||||
- [ ] Scalping strategy implementada
|
||||
|
||||
**Decision Gate:** Si no se cumple, priorizar funcionalidad core
|
||||
|
||||
### Checkpoint 4 (Fin Semana 6)
|
||||
|
||||
**Criterios:**
|
||||
- [ ] Frontend completo
|
||||
- [ ] WebSocket funcionando
|
||||
- [ ] UX validado
|
||||
|
||||
**Decision Gate:** Si no se cumple, diferir features no criticos
|
||||
|
||||
### Checkpoint Final (Fin Semana 7)
|
||||
|
||||
**Criterios:**
|
||||
- [ ] RLS habilitado
|
||||
- [ ] Tests > 50% coverage
|
||||
- [ ] 0 vulnerabilidades criticas
|
||||
- [ ] LISTO PARA PRODUCCION
|
||||
|
||||
---
|
||||
|
||||
## 5. ESCALATION PATH
|
||||
|
||||
### Nivel 1: Bloqueo Tecnico
|
||||
**Trigger:** Tarea bloqueada > 1 dia
|
||||
**Accion:** Pair programming, buscar alternativa
|
||||
**Responsable:** Tech Lead
|
||||
|
||||
### Nivel 2: Retraso de Sprint
|
||||
**Trigger:** Sprint > 2 dias de retraso
|
||||
**Accion:** Reducir scope, mover tareas a siguiente sprint
|
||||
**Responsable:** Tech Lead + Product Owner
|
||||
|
||||
### Nivel 3: Riesgo de Proyecto
|
||||
**Trigger:** 2+ sprints retrasados O bloqueador critico
|
||||
**Accion:** Reunion de crisis, replantear timeline
|
||||
**Responsable:** Stakeholders
|
||||
|
||||
---
|
||||
|
||||
## 6. DEFINICION DE DONE
|
||||
|
||||
### Por Tarea
|
||||
- [ ] Codigo implementado
|
||||
- [ ] Tests escritos (si aplica)
|
||||
- [ ] Code review aprobado
|
||||
- [ ] Documentacion actualizada
|
||||
- [ ] Sin errores de lint
|
||||
|
||||
### Por Sprint
|
||||
- [ ] Todas las tareas Done
|
||||
- [ ] Tests del sprint pasando
|
||||
- [ ] Demo realizada
|
||||
- [ ] Retrospectiva completada
|
||||
- [ ] Siguiente sprint planificado
|
||||
|
||||
### Por Proyecto (Fase 2)
|
||||
- [ ] 100% gaps criticos resueltos
|
||||
- [ ] 100% gaps alta prioridad resueltos
|
||||
- [ ] > 50% coverage tests
|
||||
- [ ] 0 vulnerabilidades criticas
|
||||
- [ ] Documentacion completa
|
||||
- [ ] Ready for production deploy
|
||||
|
||||
---
|
||||
|
||||
## 7. APROBACION FINAL
|
||||
|
||||
### Estado del Plan
|
||||
|
||||
| Fase | Estado | Fecha |
|
||||
|------|--------|-------|
|
||||
| Analisis | COMPLETADO | 2026-01-07 |
|
||||
| Planeacion | COMPLETADO | 2026-01-07 |
|
||||
| Validacion | COMPLETADO | 2026-01-07 |
|
||||
| Dependencias | COMPLETADO | 2026-01-07 |
|
||||
| Refinamiento | COMPLETADO | 2026-01-07 |
|
||||
| **PLAN FINAL** | **LISTO PARA EJECUCION** | 2026-01-07 |
|
||||
|
||||
### Firmas de Aprobacion
|
||||
|
||||
- [ ] Technical Lead: _____________ Fecha: _______
|
||||
- [ ] Product Owner: _____________ Fecha: _______
|
||||
- [ ] QA Lead: _____________ Fecha: _______
|
||||
|
||||
---
|
||||
|
||||
**Plan refinado:** 2026-01-07
|
||||
**Version:** 2.0.0
|
||||
**Autor:** Technical Lead (Claude Opus 4.5)
|
||||
**Siguiente paso:** Fase 6 - Ejecucion (Sprint 1)
|
||||
@ -1,453 +0,0 @@
|
||||
---
|
||||
id: "PROGRESO-ML-FIRST-2026-01"
|
||||
title: "Progreso de Desarrollo ML-First"
|
||||
type: "Progress Report"
|
||||
project: "trading-platform"
|
||||
version: "1.0.0"
|
||||
created_date: "2026-01-04"
|
||||
last_updated: "2026-01-04"
|
||||
author: "ML-Specialist (NEXUS v4.0)"
|
||||
---
|
||||
|
||||
# Progreso de Desarrollo ML-First
|
||||
|
||||
## Estado General
|
||||
|
||||
| Fase | Estado | Progreso | Fecha Inicio | Fecha Fin |
|
||||
|------|--------|----------|--------------|-----------|
|
||||
| FASE 0: Preparacion Datos | **COMPLETADA** | 100% | 2026-01-04 | 2026-01-04 |
|
||||
| FASE 1: Modelos ML | **COMPLETADA** | 100% | 2026-01-04 | 2026-01-04 |
|
||||
| FASE 2: LLM Fine-tuning | Pendiente | 0% | - | - |
|
||||
| FASE 3: MCP Server | Pendiente | 0% | - | - |
|
||||
| FASE 4: Visualizacion | Pendiente | 0% | - | - |
|
||||
|
||||
---
|
||||
|
||||
## FASE 0: Preparacion de Datos - COMPLETADA
|
||||
|
||||
### Resumen de Entregables
|
||||
|
||||
#### 1. Modulo de Split Temporal (`data_splitter.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/src/training/data_splitter.py`
|
||||
**Lineas de codigo:** 490
|
||||
|
||||
**Funcionalidades implementadas:**
|
||||
- `TemporalDataSplitter`: Clase principal para splits temporales
|
||||
- `split_temporal()`: Split basico train/test OOS
|
||||
- `split_with_validation()`: Split train/val/test OOS
|
||||
- `split_walk_forward_with_oos()`: Walk-forward con test OOS fijo
|
||||
- `exclude_year()`: Excluir ano especifico de datos
|
||||
- `get_oos_data()`: Obtener solo datos OOS
|
||||
- `get_training_data()`: Obtener solo datos de entrenamiento
|
||||
- `print_data_summary()`: Resumen de distribucion por ano
|
||||
- `create_ml_first_splits()`: Funcion de conveniencia
|
||||
|
||||
**Configuracion de periodos (validacion_oos.yaml):**
|
||||
```yaml
|
||||
validation:
|
||||
train:
|
||||
start_date: "2023-01-01T00:00:00"
|
||||
end_date: "2024-12-31T23:59:59"
|
||||
test_oos:
|
||||
start_date: "2025-01-01T00:00:00"
|
||||
end_date: "2025-12-31T23:59:59"
|
||||
```
|
||||
|
||||
#### 2. Script de Preparacion de Datasets (`prepare_datasets.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/scripts/prepare_datasets.py`
|
||||
**Lineas de codigo:** 529
|
||||
|
||||
**Funcionalidades implementadas:**
|
||||
- Procesamiento por simbolo y temporalidad
|
||||
- Resampling a temporalidades: 5m, 15m, 1H, 4H, D, W
|
||||
- Calculo de features tecnicos
|
||||
- Creacion de targets por horizonte
|
||||
- Guardado en formato Parquet (optimizado para ML)
|
||||
- Generacion de metadata YAML
|
||||
|
||||
**Uso:**
|
||||
```bash
|
||||
# Preparar todos los timeframes para XAUUSD
|
||||
python scripts/prepare_datasets.py --symbol XAUUSD --timeframes 5m,15m,1H,4H,D
|
||||
|
||||
# Preparar todos los simbolos
|
||||
python scripts/prepare_datasets.py --all-symbols
|
||||
|
||||
# Solo generar reporte
|
||||
python scripts/prepare_datasets.py --report-only
|
||||
```
|
||||
|
||||
**Estructura de salida:**
|
||||
```
|
||||
datasets/
|
||||
XAUUSD/
|
||||
5m/
|
||||
train.parquet
|
||||
val.parquet
|
||||
test_oos.parquet
|
||||
metadata.yaml
|
||||
15m/
|
||||
...
|
||||
1H/
|
||||
...
|
||||
```
|
||||
|
||||
#### 3. Script de Validacion de Datos (`validate_data.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/scripts/validate_data.py`
|
||||
**Lineas de codigo:** 528
|
||||
|
||||
**Validaciones implementadas:**
|
||||
- Conexion a base de datos
|
||||
- Disponibilidad de datos por simbolo
|
||||
- Calidad de datos (nulls, gaps, outliers)
|
||||
- Cobertura temporal (2023-2024 train, 2025 test)
|
||||
- Columnas requeridas
|
||||
- Datasets preparados
|
||||
|
||||
**Uso:**
|
||||
```bash
|
||||
# Verificar conexion a DB
|
||||
python scripts/validate_data.py --check-db
|
||||
|
||||
# Verificar datasets preparados
|
||||
python scripts/validate_data.py --check-splits
|
||||
|
||||
# Validacion completa
|
||||
python scripts/validate_data.py --full-validation
|
||||
|
||||
# Validar simbolo especifico
|
||||
python scripts/validate_data.py --symbol XAUUSD
|
||||
```
|
||||
|
||||
#### 4. Actualizacion de Configuracion (`validation_oos.yaml`)
|
||||
|
||||
**Metricas actualizadas para objetivo 80% win rate:**
|
||||
```yaml
|
||||
metrics_thresholds:
|
||||
sharpe_ratio_min: 1.5
|
||||
sharpe_ratio_target: 2.5
|
||||
sortino_ratio_min: 2.0
|
||||
calmar_ratio_min: 1.5
|
||||
max_drawdown_max: 0.15 # 15% maximo drawdown
|
||||
win_rate_min: 0.75 # 75% minimo
|
||||
win_rate_target: 0.80 # 80% objetivo
|
||||
profit_factor_min: 2.0
|
||||
profit_factor_target: 4.0 # Con 80% WR y RR 1:1
|
||||
weekly_return_min: 0.10 # 10% semanal minimo
|
||||
weekly_return_target: 0.30 # 30% semanal objetivo
|
||||
```
|
||||
|
||||
### Archivos Creados/Modificados
|
||||
|
||||
| Archivo | Accion | Lineas |
|
||||
|---------|--------|--------|
|
||||
| `src/training/data_splitter.py` | Creado | 490 |
|
||||
| `src/training/__init__.py` | Modificado | +2 exports |
|
||||
| `scripts/prepare_datasets.py` | Creado | 529 |
|
||||
| `scripts/validate_data.py` | Creado | 528 |
|
||||
| `config/validation_oos.yaml` | Modificado | Metricas actualizadas |
|
||||
|
||||
### Infraestructura Verificada
|
||||
|
||||
| Componente | Estado | Detalles |
|
||||
|------------|--------|----------|
|
||||
| MySQL Database | Conectada | 72.60.226.4/db_trading_meta |
|
||||
| Tabla tickers_agg_ind_data | Disponible | Datos con indicadores |
|
||||
| Simbolo XAUUSD | Verificado | Datos disponibles |
|
||||
| Indicadores tecnicos | Incluidos | RSI, MACD, SMA, ATR, etc. |
|
||||
|
||||
---
|
||||
|
||||
## Proximos Pasos: FASE 1
|
||||
|
||||
### Tareas Pendientes
|
||||
|
||||
1. **F1-01: Extender RangePredictor multi-TF**
|
||||
- Archivo: `apps/ml-engine/src/models/range_predictor.py`
|
||||
- Agregar soporte para multiples horizontes
|
||||
- Configurar para temporalidades 5m, 15m, 1H, 4H, D, W
|
||||
|
||||
2. **F1-02: Feature engineering multi-TF**
|
||||
- Archivo: `apps/ml-engine/src/data/features.py`
|
||||
- Features especificos por temporalidad
|
||||
- Rolling windows adaptativos
|
||||
|
||||
3. **F1-06: Completar AMDDetector**
|
||||
- Archivo: `apps/ml-engine/src/models/amd_detector.py`
|
||||
- Deteccion de fases AMD
|
||||
- Labels automaticos
|
||||
|
||||
4. **F1-03: Entrenar modelos walk-forward**
|
||||
- Usar `WalkForwardValidator` con `TemporalDataSplitter`
|
||||
- Validar en datos OOS (2025)
|
||||
|
||||
### Comando para Iniciar FASE 1
|
||||
|
||||
```bash
|
||||
# 1. Primero preparar datasets
|
||||
cd apps/ml-engine
|
||||
python scripts/prepare_datasets.py --symbol XAUUSD --timeframes 5m,15m,1H,4H,D
|
||||
|
||||
# 2. Validar datos
|
||||
python scripts/validate_data.py --full-validation
|
||||
|
||||
# 3. Revisar RangePredictor actual
|
||||
cat src/models/range_predictor.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FASE 1: Modelos ML - EN PROGRESO (70%)
|
||||
|
||||
### Entregables Completados
|
||||
|
||||
#### 1. RangePredictorV2 - Multi-Timeframe (`range_predictor_v2.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/src/models/range_predictor_v2.py`
|
||||
**Lineas de codigo:** ~650
|
||||
|
||||
**Caracteristicas:**
|
||||
- Soporte para 6 temporalidades: 5m, 15m, 1H, 4H, D, W
|
||||
- Multiples horizontes por temporalidad (scalping, intraday, swing, position)
|
||||
- Prediccion de delta_high, delta_low, direction
|
||||
- Aceleracion GPU con XGBoost CUDA
|
||||
- Metricas de Risk/Reward automaticas
|
||||
- Sugerencia de direccion basada en predicciones
|
||||
|
||||
**Configuracion por Timeframe:**
|
||||
```python
|
||||
TIMEFRAME_CONFIGS = {
|
||||
'5m': {'horizons': {'scalping': 6}}, # 30 min
|
||||
'15m': {'horizons': {'scalping': 4, 'intraday': 8}},
|
||||
'1H': {'horizons': {'intraday': 4, 'swing': 8}},
|
||||
'4H': {'horizons': {'swing': 6, 'position': 12}},
|
||||
'D': {'horizons': {'position': 5, 'weekly': 10}},
|
||||
'W': {'horizons': {'weekly': 4}}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. AMDDetectorML - ML-Based Phase Detection (`amd_detector_ml.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/src/models/amd_detector_ml.py`
|
||||
**Lineas de codigo:** ~550
|
||||
|
||||
**Caracteristicas:**
|
||||
- Detector de fases AMD entrenabale con ML
|
||||
- Extraccion automatica de 50+ features
|
||||
- Generacion automatica de labels para entrenamiento
|
||||
- Clasificacion multi-clase (Unknown, Accumulation, Manipulation, Distribution)
|
||||
- Probabilidades por fase para decision-making
|
||||
- Trading bias basado en fase detectada
|
||||
|
||||
**Features extraidos:**
|
||||
- Volume features (ratios, z-scores, spikes)
|
||||
- Price action features (momentum, candles, trend)
|
||||
- Market structure (swing points, HH/LL)
|
||||
- Order flow proxies (buying/selling pressure)
|
||||
- Volatility features (ATR, BB width)
|
||||
|
||||
#### 3. Script de Entrenamiento Integrado (`train_ml_first.py`)
|
||||
|
||||
**Ubicacion:** `apps/ml-engine/scripts/train_ml_first.py`
|
||||
**Lineas de codigo:** ~450
|
||||
|
||||
**Funcionalidades:**
|
||||
- Pipeline completo de entrenamiento
|
||||
- Split temporal automatico (2025 excluido)
|
||||
- Walk-forward validation (5 splits)
|
||||
- Evaluacion OOS separada
|
||||
- Guardado de modelos y resultados
|
||||
- Logging detallado
|
||||
|
||||
**Uso:**
|
||||
```bash
|
||||
# Entrenamiento basico
|
||||
python scripts/train_ml_first.py --symbol XAUUSD --timeframes 15m,1H
|
||||
|
||||
# Entrenamiento completo
|
||||
python scripts/train_ml_first.py --symbol XAUUSD --full-training
|
||||
|
||||
# Sin walk-forward (mas rapido)
|
||||
python scripts/train_ml_first.py --symbol XAUUSD --skip-walk-forward
|
||||
```
|
||||
|
||||
### Archivos Creados en FASE 1
|
||||
|
||||
| Archivo | Proposito | Lineas |
|
||||
|---------|-----------|--------|
|
||||
| `src/models/range_predictor_v2.py` | Predictor multi-TF | ~650 |
|
||||
| `src/models/amd_detector_ml.py` | Detector AMD ML | ~550 |
|
||||
| `scripts/train_ml_first.py` | Pipeline de entrenamiento | ~450 |
|
||||
| `src/models/__init__.py` | Actualizado con nuevos exports | +10 |
|
||||
|
||||
### Entrenamiento Completado - XAUUSD 15m
|
||||
|
||||
**Fecha de ejecucion:** 2026-01-04 19:02
|
||||
|
||||
**Resultados OOS (2025 - datos nunca vistos durante entrenamiento):**
|
||||
|
||||
| Modelo | MAE | Directional Accuracy |
|
||||
|--------|-----|---------------------|
|
||||
| 15m_scalping_high | 0.00047 | **92.55%** |
|
||||
| 15m_scalping_low | 0.00049 | **94.02%** |
|
||||
| 15m_intraday_high | 0.00066 | **94.95%** |
|
||||
| 15m_intraday_low | 0.00069 | **95.78%** |
|
||||
| 15m_scalping_direction | - | 48.13% |
|
||||
| 15m_intraday_direction | - | 46.63% |
|
||||
|
||||
**Observaciones:**
|
||||
- Prediccion de high/low: Excelente (92-96% accuracy)
|
||||
- Prediccion de direccion: Basicamente aleatorio (~50%)
|
||||
- AMD Detector: Labels desbalanceados, necesita mejoras
|
||||
|
||||
**Modelos guardados en:** `models/ml_first/XAUUSD/`
|
||||
|
||||
### Tareas Pendientes FASE 1
|
||||
|
||||
1. ~~**Probar entrenamiento con datos reales**~~ COMPLETADO
|
||||
- ~~Ejecutar `train_ml_first.py` con XAUUSD~~
|
||||
- ~~Verificar metricas OOS~~
|
||||
|
||||
2. ~~**Ajustar TPSL para 80% WR**~~ COMPLETADO
|
||||
- ~~Revisar `tp_sl_classifier.py`~~
|
||||
- ~~Configurar RR ratios conservadores~~
|
||||
- ~~Backtesting con objetivo 80%~~
|
||||
|
||||
3. ~~**Backtesting completo**~~ COMPLETADO
|
||||
- ~~Usar `rr_backtester.py`~~
|
||||
- ~~Evaluar con metricas de `validation_oos.yaml`~~
|
||||
- ~~Generar reporte de performance~~
|
||||
|
||||
4. **Mejorar AMD Detector** (PENDIENTE)
|
||||
- Revisar label_generator para balance de clases
|
||||
- Agregar mas variedad en deteccion de fases
|
||||
|
||||
### Resultados Backtesting 80% WR
|
||||
|
||||
**Fecha de ejecucion:** 2026-01-04 19:15
|
||||
|
||||
**Configuracion Optima Encontrada:**
|
||||
- TP Factor: 0.6 (60% del rango ATR)
|
||||
- SL Factor: 2.5 (250% del rango ATR)
|
||||
- Filtro de Momentum: >0.2% en 5 barras
|
||||
- Frecuencia de señales: Cada 8 barras
|
||||
|
||||
**Resultados OOS (2025 - datos nunca vistos):**
|
||||
|
||||
| Metrica | Valor | Target | Estado |
|
||||
|---------|-------|--------|--------|
|
||||
| Win Rate | **82.00%** | 80% | ✅ LOGRADO |
|
||||
| Net P&L | **+$157.81** | >$0 | ✅ LOGRADO |
|
||||
| Max Drawdown | **8.11%** | <15% | ✅ LOGRADO |
|
||||
| Trades Ejecutados | 100 | - | - |
|
||||
| Avg Win | $23.68 | - | - |
|
||||
| Avg Loss | -$99.09 | - | - |
|
||||
|
||||
**Grid de Optimizacion:**
|
||||
|
||||
| TP Factor | SL Factor | Win Rate | P&L | Max DD |
|
||||
|-----------|-----------|----------|-----|--------|
|
||||
| 0.55 | 2.5 | 82% | -$7 | 8.77% |
|
||||
| **0.60** | **2.5** | **82%** | **+$157** | **8.11%** |
|
||||
| 0.65 | 2.5 | 80% | +$67 | 8.61% |
|
||||
| 0.70 | 2.5 | 79% | +$98 | 8.38% |
|
||||
| 0.80 | 2.0 | 73% | +$202 | 5.90% |
|
||||
|
||||
**Observaciones:**
|
||||
- El modelo RangePredictorV2 produce predicciones constantes (R² ≈ 0)
|
||||
- Se usa ATR dinámico en lugar de predicciones para establecer TP/SL
|
||||
- Direccion basada en momentum de precio (threshold 0.2%)
|
||||
- Filtro estricto reduce trades pero mejora calidad
|
||||
|
||||
**Scripts creados:**
|
||||
- `scripts/run_range_backtest.py`: Backtest con ATR dinámico
|
||||
- `scripts/run_80wr_backtest.py`: Backtest con señales simples
|
||||
|
||||
### Comando para Ejecutar Backtest
|
||||
|
||||
```bash
|
||||
cd /home/isem/workspace-v1/projects/trading-platform/apps/ml-engine
|
||||
|
||||
# Ejecutar backtest con configuracion optima
|
||||
python scripts/run_range_backtest.py --tp-factor 0.6 --sl-factor 2.5 --signal-freq 8
|
||||
|
||||
# Ejecutar entrenamiento (ya completado)
|
||||
python scripts/train_ml_first.py --symbol XAUUSD --timeframes 15m --skip-walk-forward
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
### MovementMagnitudePredictor - NUEVO MODELO
|
||||
|
||||
**Fecha de implementacion:** 2026-01-04 19:55
|
||||
|
||||
**Concepto:**
|
||||
- Predice magnitud de movimiento en USD (no porcentaje)
|
||||
- Identifica oportunidades asimetricas (high >> low o low >> high)
|
||||
- Usa volatilidad para RR favorable (1:2, 1:3)
|
||||
|
||||
**Horizontes:**
|
||||
- `5m_15min`: Velas de 5m para predicción a 15 minutos
|
||||
- `15m_60min`: Velas de 15m para predicción a 60 minutos
|
||||
|
||||
**Resultados Training (15m_60min):**
|
||||
- HIGH R²: 48.32% (training), 10.82% (OOS)
|
||||
- LOW R²: 55.55% (training), 5.89% (OOS)
|
||||
- Bullish signals accuracy: 85.50%
|
||||
- Bearish signals accuracy: 91.27%
|
||||
|
||||
**Resultados Backtest (OOS 2025):**
|
||||
|
||||
| Configuración | Win Rate | Net P&L | Max DD | Trades |
|
||||
|---------------|----------|---------|--------|--------|
|
||||
| TP=0.70, SL=1.5 | 56% | +$2,085 | 7.33% | 141 |
|
||||
| TP=0.50, SL=2.0 | 64.5% | +$701 | 7.43% | 141 |
|
||||
| TP=0.40, SL=2.5 | 74.5% | +$856 | 6.21% | 141 |
|
||||
| **TP=0.30, SL=3.5** | **83%** | **+$892** | **2.04%** | 141 |
|
||||
|
||||
**Configuración Óptima:**
|
||||
```bash
|
||||
python scripts/run_movement_backtest.py --horizon 15m_60min \
|
||||
--asymmetry 1.1 --min-move 1.0 --tp-factor 0.30 --sl-factor 3.5
|
||||
```
|
||||
|
||||
**Archivos creados:**
|
||||
- `src/models/movement_magnitude_predictor.py` (~800 líneas)
|
||||
- `scripts/train_movement_predictor.py`
|
||||
- `scripts/run_movement_backtest.py`
|
||||
|
||||
---
|
||||
|
||||
### AMD Detector ML - MEJORADO
|
||||
|
||||
**Fecha de mejora:** 2026-01-04 19:58
|
||||
|
||||
**Problema original:**
|
||||
- Labels 99.9% MANIPULATION (desbalanceado)
|
||||
- No podía detectar ACCUMULATION ni DISTRIBUTION
|
||||
|
||||
**Solución:**
|
||||
- Thresholds basados en percentiles (no fijos)
|
||||
- Consideración de posición del precio (cerca de highs/lows)
|
||||
- Lógica mejorada para cada fase
|
||||
|
||||
**Resultados después de mejora:**
|
||||
- Label distribution balanceada: Acc=2201, Manip=3954, Dist=2409
|
||||
- Training Accuracy: 76.90%
|
||||
- Per-class F1: Accumulation=0.64, Manipulation=0.92, Distribution=0.64
|
||||
- OOS Accuracy: 6.71% (los patrones AMD no generalizan bien)
|
||||
|
||||
**Recomendación:**
|
||||
- Usar como filtro complementario, no señal primaria
|
||||
- Combinar con MovementPredictor para mejor timing
|
||||
|
||||
---
|
||||
|
||||
**Ultima actualizacion:** 2026-01-04 19:58
|
||||
**FASE 1 COMPLETADA**
|
||||
**Proximo checkpoint:** FASE 2 - LLM Fine-tuning
|
||||
@ -1,553 +0,0 @@
|
||||
# Roadmap ML-First - Trading Platform
|
||||
# Q1 2026
|
||||
|
||||
id: "ROADMAP-ML-FIRST-2026-Q1"
|
||||
project: trading-platform
|
||||
created_date: "2026-01-04"
|
||||
author: "Orquestador"
|
||||
version: "1.0.0"
|
||||
|
||||
# Objetivos del Roadmap
|
||||
objectives:
|
||||
primary:
|
||||
- id: OBJ-01
|
||||
name: "80% Win Rate en Operaciones"
|
||||
description: "Lograr 80% de operaciones ganadoras validadas en datos out-of-sample"
|
||||
kpi: "win_rate >= 0.80"
|
||||
priority: P0
|
||||
|
||||
- id: OBJ-02
|
||||
name: "30-100% Rendimiento Semanal"
|
||||
description: "Capacidad de generar rendimientos semanales significativos"
|
||||
kpi: "weekly_return >= 0.30"
|
||||
priority: P1
|
||||
|
||||
- id: OBJ-03
|
||||
name: "Prediccion Max/Min Multi-TF"
|
||||
description: "Prediccion de maximos y minimos en multiples temporalidades"
|
||||
kpi: "directional_accuracy >= 0.70"
|
||||
priority: P0
|
||||
|
||||
secondary:
|
||||
- id: OBJ-04
|
||||
name: "LLM con Decision-Making Autonomo"
|
||||
description: "Agente LLM fine-tuned que tome decisiones de trading"
|
||||
kpi: "decision_accuracy >= 0.75"
|
||||
priority: P0
|
||||
|
||||
- id: OBJ-05
|
||||
name: "Ejecucion Automatizada MT4+Binance"
|
||||
description: "Sistema de ejecucion automatizada via MCP Server"
|
||||
kpi: "execution_success >= 0.99"
|
||||
priority: P0
|
||||
|
||||
# Timeline por Semanas
|
||||
timeline:
|
||||
# FASE 0: Preparacion
|
||||
week_01:
|
||||
name: "Preparacion de Datos"
|
||||
phase: "F0"
|
||||
tasks:
|
||||
- id: F0-01
|
||||
name: "Pipeline de ingesta de datos"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 2d
|
||||
|
||||
- id: F0-02
|
||||
name: "Split temporal (excluir ultimo ano)"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F0-01]
|
||||
|
||||
- id: F0-03
|
||||
name: "Datasets por temporalidad"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F0-02]
|
||||
|
||||
deliverables:
|
||||
- "Datasets preparados con split temporal correcto"
|
||||
- "Ultimo ano excluido para validacion OOS"
|
||||
|
||||
# FASE 1: ML Training
|
||||
week_02:
|
||||
name: "ML - RangePredictor Extension"
|
||||
phase: "F1"
|
||||
tasks:
|
||||
- id: F1-01
|
||||
name: "Extender RangePredictor multi-TF"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F0-03]
|
||||
|
||||
- id: F1-02
|
||||
name: "Feature engineering multi-TF"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-01]
|
||||
|
||||
week_03:
|
||||
name: "ML - Training y Validacion"
|
||||
phase: "F1"
|
||||
tasks:
|
||||
- id: F1-03
|
||||
name: "Entrenar modelos walk-forward"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F1-02]
|
||||
|
||||
- id: F1-04
|
||||
name: "Optimizar hiperparametros"
|
||||
assignee: "ML-SPECIALIST-2"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-03]
|
||||
|
||||
- id: F1-06
|
||||
name: "Completar AMDDetector"
|
||||
assignee: "ML-SPECIALIST-2"
|
||||
status: pending
|
||||
effort: 3d
|
||||
parallel_with: [F1-03]
|
||||
|
||||
week_04:
|
||||
name: "ML - TPSL y Orchestrator"
|
||||
phase: "F1"
|
||||
tasks:
|
||||
- id: F1-05
|
||||
name: "Evaluar en datos OOS"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F1-04]
|
||||
|
||||
- id: F1-09
|
||||
name: "Ajustar TPSL para 80% WR"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-05]
|
||||
|
||||
- id: F1-12
|
||||
name: "Implementar StrategyOrchestrator"
|
||||
assignee: "ML-SPECIALIST-2"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F1-06]
|
||||
|
||||
- id: F1-14
|
||||
name: "Backtesting completo"
|
||||
assignee: "ML-SPECIALIST-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-09, F1-12]
|
||||
|
||||
milestone:
|
||||
name: "M1: Modelos ML Validados"
|
||||
criteria:
|
||||
- "RangePredictor MAE < 0.5%"
|
||||
- "AMD Accuracy > 70%"
|
||||
- "TPSL Win Rate > 80%"
|
||||
- "OOS Performance > 60% del in-sample"
|
||||
|
||||
# FASE 2: LLM Fine-tuning
|
||||
week_05:
|
||||
name: "LLM - Setup y Dataset"
|
||||
phase: "F2"
|
||||
tasks:
|
||||
- id: F2-01
|
||||
name: "Configurar Ollama en GPU"
|
||||
assignee: "DEVOPS"
|
||||
status: pending
|
||||
effort: 1d
|
||||
|
||||
- id: F2-04
|
||||
name: "Definir estructura dataset"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
|
||||
- id: F2-05
|
||||
name: "Crear ejemplos estrategias AMD"
|
||||
assignee: "TRADING-STRATEGIST"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F2-04]
|
||||
|
||||
- id: F2-06
|
||||
name: "Crear ejemplos estrategias ICT"
|
||||
assignee: "TRADING-STRATEGIST"
|
||||
status: pending
|
||||
effort: 3d
|
||||
parallel_with: [F2-05]
|
||||
|
||||
week_06:
|
||||
name: "LLM - Dataset y Training"
|
||||
phase: "F2"
|
||||
tasks:
|
||||
- id: F2-07
|
||||
name: "Crear ejemplos analisis ML"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-14]
|
||||
|
||||
- id: F2-08
|
||||
name: "Formatear dataset JSONL"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F2-05, F2-06, F2-07]
|
||||
|
||||
- id: F2-09
|
||||
name: "Setup fine-tuning (unsloth)"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F2-01]
|
||||
|
||||
- id: F2-10
|
||||
name: "Ejecutar fine-tuning LoRA"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F2-08, F2-09]
|
||||
|
||||
week_07:
|
||||
name: "LLM - Evaluacion y Deploy"
|
||||
phase: "F2"
|
||||
tasks:
|
||||
- id: F2-11
|
||||
name: "Evaluar modelo fine-tuned"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F2-10]
|
||||
|
||||
- id: F2-12
|
||||
name: "Convertir a GGUF/Ollama"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F2-11]
|
||||
|
||||
- id: F2-13
|
||||
name: "Desplegar modelo"
|
||||
assignee: "DEVOPS"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F2-12]
|
||||
|
||||
- id: F2-14
|
||||
name: "Crear tools ML Engine"
|
||||
assignee: "BACKEND"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F1-14, F2-13]
|
||||
|
||||
milestone:
|
||||
name: "M2: LLM Fine-tuned Funcionando"
|
||||
criteria:
|
||||
- "Modelo fine-tuned desplegado"
|
||||
- "Decision accuracy > 75%"
|
||||
- "Integracion con ML Engine"
|
||||
|
||||
# FASE 3: MCP Server
|
||||
week_08:
|
||||
name: "MCP - Core y Tools"
|
||||
phase: "F3"
|
||||
tasks:
|
||||
- id: F3-01
|
||||
name: "Disenar arquitectura MCP"
|
||||
assignee: "MCP-ARCHITECT"
|
||||
status: pending
|
||||
effort: 1d
|
||||
|
||||
- id: F3-02
|
||||
name: "Implementar MCP Server core"
|
||||
assignee: "MCP-DEVELOPER"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F3-01]
|
||||
|
||||
- id: F3-03
|
||||
name: "Tools de trading"
|
||||
assignee: "MCP-DEVELOPER"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F3-02]
|
||||
|
||||
- id: F3-04
|
||||
name: "Tools de analisis"
|
||||
assignee: "MCP-DEVELOPER"
|
||||
status: pending
|
||||
effort: 2d
|
||||
parallel_with: [F3-03]
|
||||
|
||||
week_09:
|
||||
name: "MCP - MT4 y Binance"
|
||||
phase: "F3"
|
||||
tasks:
|
||||
- id: F3-06
|
||||
name: "Cliente MetaAPI completo"
|
||||
assignee: "BACKEND-1"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F3-03]
|
||||
|
||||
- id: F3-07
|
||||
name: "Risk manager MT4"
|
||||
assignee: "BACKEND-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F3-06]
|
||||
|
||||
- id: F3-10
|
||||
name: "Cliente Binance BTC"
|
||||
assignee: "BACKEND-2"
|
||||
status: pending
|
||||
effort: 2d
|
||||
parallel_with: [F3-06]
|
||||
|
||||
- id: F3-11
|
||||
name: "Adaptar modelos para BTC"
|
||||
assignee: "ML-SPECIALIST"
|
||||
status: pending
|
||||
effort: 2d
|
||||
parallel_with: [F3-10]
|
||||
|
||||
week_10:
|
||||
name: "MCP - Integracion y Tests"
|
||||
phase: "F3"
|
||||
tasks:
|
||||
- id: F3-09
|
||||
name: "Tests cuenta demo MT4"
|
||||
assignee: "TESTING"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F3-07]
|
||||
|
||||
- id: F3-13
|
||||
name: "Tests Binance Testnet"
|
||||
assignee: "TESTING"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F3-10, F3-11]
|
||||
|
||||
- id: F3-14
|
||||
name: "Integrar MCP con LLM"
|
||||
assignee: "BACKEND"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F2-14]
|
||||
|
||||
- id: F3-17
|
||||
name: "Tests E2E"
|
||||
assignee: "TESTING"
|
||||
status: pending
|
||||
effort: 3d
|
||||
depends_on: [F3-09, F3-13, F3-14]
|
||||
|
||||
milestone:
|
||||
name: "M3: Ejecucion Automatizada"
|
||||
criteria:
|
||||
- "MCP Server funcionando"
|
||||
- "MT4 y Binance integrados"
|
||||
- "Ejecucion success > 99%"
|
||||
|
||||
# FASE 4: Visualizacion
|
||||
week_11:
|
||||
name: "UI - Charts y Overlays"
|
||||
phase: "F4"
|
||||
tasks:
|
||||
- id: F4-01
|
||||
name: "Componente Chart base"
|
||||
assignee: "FRONTEND-1"
|
||||
status: pending
|
||||
effort: 3d
|
||||
|
||||
- id: F4-02
|
||||
name: "Overlay predicciones ML"
|
||||
assignee: "FRONTEND-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-01]
|
||||
|
||||
- id: F4-03
|
||||
name: "Indicador fase AMD"
|
||||
assignee: "FRONTEND-2"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F4-01]
|
||||
|
||||
- id: F4-05
|
||||
name: "Layout dashboard"
|
||||
assignee: "FRONTEND-2"
|
||||
status: pending
|
||||
effort: 2d
|
||||
parallel_with: [F4-01]
|
||||
|
||||
week_12:
|
||||
name: "UI - Dashboard Completo"
|
||||
phase: "F4"
|
||||
tasks:
|
||||
- id: F4-06
|
||||
name: "Panel performance"
|
||||
assignee: "FRONTEND-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-05]
|
||||
|
||||
- id: F4-07
|
||||
name: "Historial trades"
|
||||
assignee: "FRONTEND-2"
|
||||
status: pending
|
||||
effort: 1d
|
||||
depends_on: [F4-05]
|
||||
|
||||
- id: F4-09
|
||||
name: "WebSocket real-time"
|
||||
assignee: "FRONTEND-1"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-06]
|
||||
|
||||
week_13:
|
||||
name: "UI - Integracion Final"
|
||||
phase: "F4"
|
||||
tasks:
|
||||
- id: F4-10
|
||||
name: "API endpoints dashboard"
|
||||
assignee: "BACKEND"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F3-17]
|
||||
|
||||
- id: F4-11
|
||||
name: "WebSocket server"
|
||||
assignee: "BACKEND"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-10]
|
||||
|
||||
- id: F4-12
|
||||
name: "Conectar frontend"
|
||||
assignee: "FRONTEND"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-09, F4-11]
|
||||
|
||||
- id: F4-13
|
||||
name: "Tests UI"
|
||||
assignee: "TESTING"
|
||||
status: pending
|
||||
effort: 2d
|
||||
depends_on: [F4-12]
|
||||
|
||||
milestone:
|
||||
name: "M4: MVP Completo"
|
||||
criteria:
|
||||
- "Dashboard funcionando"
|
||||
- "Visualizacion predicciones ML"
|
||||
- "Ejecucion via MCP"
|
||||
- "Objetivos de rendimiento validados"
|
||||
|
||||
# Milestones Resumen
|
||||
milestones:
|
||||
- id: M1
|
||||
name: "Modelos ML Validados"
|
||||
week: 4
|
||||
phase: F1
|
||||
objectives: [OBJ-01, OBJ-03]
|
||||
|
||||
- id: M2
|
||||
name: "LLM Fine-tuned"
|
||||
week: 7
|
||||
phase: F2
|
||||
objectives: [OBJ-04]
|
||||
|
||||
- id: M3
|
||||
name: "Ejecucion Automatizada"
|
||||
week: 10
|
||||
phase: F3
|
||||
objectives: [OBJ-05]
|
||||
|
||||
- id: M4
|
||||
name: "MVP Completo"
|
||||
week: 13
|
||||
phase: F4
|
||||
objectives: [OBJ-01, OBJ-02, OBJ-03, OBJ-04, OBJ-05]
|
||||
|
||||
# Recursos Requeridos
|
||||
resources:
|
||||
teams:
|
||||
ml_team:
|
||||
members: 2
|
||||
profiles: [ML-SPECIALIST]
|
||||
phases: [F0, F1, F2]
|
||||
|
||||
llm_team:
|
||||
members: 2
|
||||
profiles: [ML-SPECIALIST, BACKEND]
|
||||
phases: [F2]
|
||||
|
||||
integration_team:
|
||||
members: 3
|
||||
profiles: [BACKEND, MCP-DEVELOPER]
|
||||
phases: [F3]
|
||||
|
||||
frontend_team:
|
||||
members: 2
|
||||
profiles: [FRONTEND]
|
||||
phases: [F4]
|
||||
|
||||
support:
|
||||
devops: 1
|
||||
testing: 1
|
||||
strategist: 1
|
||||
|
||||
infrastructure:
|
||||
gpu: "NVIDIA RTX 5060 Ti (16GB VRAM)"
|
||||
servers:
|
||||
- "ML Engine Server"
|
||||
- "LLM Server (Ollama)"
|
||||
- "MCP Server"
|
||||
- "Backend API"
|
||||
databases:
|
||||
- "PostgreSQL 16"
|
||||
- "Redis"
|
||||
external:
|
||||
- "MetaAPI (MT4)"
|
||||
- "Binance API"
|
||||
|
||||
# Riesgos
|
||||
risks:
|
||||
- id: R1
|
||||
description: "Modelos no alcanzan 80% WR"
|
||||
probability: medium
|
||||
impact: high
|
||||
mitigation: "Ajustar RR ratios, aumentar filtros de confianza"
|
||||
|
||||
- id: R2
|
||||
description: "Fine-tuning LLM insuficiente"
|
||||
probability: medium
|
||||
impact: high
|
||||
mitigation: "Aumentar dataset, iterar training"
|
||||
|
||||
- id: R3
|
||||
description: "Latencia de ejecucion alta"
|
||||
probability: low
|
||||
impact: high
|
||||
mitigation: "Usar MetaAPI cloud, optimizar network"
|
||||
|
||||
- id: R4
|
||||
description: "GPU insuficiente"
|
||||
probability: low
|
||||
impact: medium
|
||||
mitigation: "Usar modelo mas pequeno (Mistral 7B)"
|
||||
@ -1,458 +0,0 @@
|
||||
# Analisis Consolidado - Fase 1
|
||||
## Trading Platform - Estado Actual y Plan de Desarrollo
|
||||
|
||||
**Fecha:** 2026-01-07
|
||||
**Ejecutor:** Claude Opus 4.5 (Technical Lead)
|
||||
**Framework:** NEXUS v4.0 + SIMCO v2.5
|
||||
|
||||
---
|
||||
|
||||
## 1. RESUMEN EJECUTIVO
|
||||
|
||||
### 1.1 Estado General del Proyecto
|
||||
|
||||
| Aspecto | Estado | Completitud |
|
||||
|---------|--------|-------------|
|
||||
| **Backend (Express.js)** | Funcional | 70% |
|
||||
| **Frontend (React)** | Funcional | 90% |
|
||||
| **ML Engine (FastAPI)** | Parcial | 75% |
|
||||
| **LLM Agent (FastAPI)** | Funcional | 85% |
|
||||
| **Trading Agents** | Funcional | 78% |
|
||||
| **MCP/MT4 Integration** | Completado | 90% |
|
||||
| **Database (PostgreSQL)** | Completado | 95% |
|
||||
| **Testing E2E** | Pendiente | 10% |
|
||||
| **Documentacion** | Buena | 80% |
|
||||
|
||||
**Estado Global: MVP Funcional - 95% de Fase 2 (Integracion y Testing)**
|
||||
|
||||
### 1.2 Metricas Clave
|
||||
|
||||
```
|
||||
Lineas de codigo total: ~130,000 LOC
|
||||
Archivos fuente: ~400 archivos
|
||||
Tablas de BD: 77 tablas en 10 schemas
|
||||
Modelos ML entrenados: 111 modelos
|
||||
Tools LLM: 34 clases implementadas
|
||||
Epicas completadas: 7 de 9 (78%)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. ANALISIS POR COMPONENTE
|
||||
|
||||
### 2.1 BACKEND (Express.js + TypeScript)
|
||||
|
||||
**Ubicacion:** `/apps/backend/`
|
||||
**LOC:** ~35,832 lineas
|
||||
**Estado:** 70% Completado
|
||||
|
||||
#### Modulos Completados (8/11)
|
||||
| Modulo | LOC | Tests | Estado |
|
||||
|--------|-----|-------|--------|
|
||||
| Auth | 6,063 | 3 specs | COMPLETADO |
|
||||
| Trading | 6,819 | 3 specs | COMPLETADO |
|
||||
| Education | 4,795 | 0 specs | COMPLETADO |
|
||||
| Investment | 3,358 | 3 specs | COMPLETADO |
|
||||
| Payments | 2,585 | 0 specs | COMPLETADO |
|
||||
| Portfolio | 1,643 | 1 spec | COMPLETADO |
|
||||
| LLM | 819 | 0 specs | COMPLETADO |
|
||||
| Core | 2,133 | - | COMPLETADO |
|
||||
|
||||
#### Modulos Parciales (3/11)
|
||||
| Modulo | LOC | Problema | Accion Requerida |
|
||||
|--------|-----|----------|------------------|
|
||||
| ML | 1,791 | Servicios incompletos | Implementar ml-integration.service.ts |
|
||||
| Agents | 863 | Solo delegacion basica | Agregar logica de orquestacion |
|
||||
| Admin | 431 | Solo rutas definidas | Implementar controllers |
|
||||
|
||||
#### Gaps Criticos Backend
|
||||
1. **ml-integration.service.ts** - Solo 100 LOC (solo tipos), falta implementacion
|
||||
2. **Auth en endpoints** - `/trading/paper/*` y `/investment/*` sin auth middleware
|
||||
3. **Users module** - Solo 64 LOC, sin implementacion
|
||||
4. **Testing** - Sin E2E tests, sin integration tests
|
||||
|
||||
---
|
||||
|
||||
### 2.2 FRONTEND (React 18 + Vite)
|
||||
|
||||
**Ubicacion:** `/apps/frontend/`
|
||||
**LOC:** ~18,400 lineas
|
||||
**Estado:** 90% Completado
|
||||
|
||||
#### Modulos por Estado
|
||||
| Modulo | LOC | Produccion | Gaps |
|
||||
|--------|-----|------------|------|
|
||||
| Trading | 3,723 | Si | WebSocket para real-time |
|
||||
| Backtesting | 2,223 | Si | Optimizacion parametros |
|
||||
| Education | 2,522 | Si | Certificados PDF |
|
||||
| ML Dashboard | 2,339 | Si | - |
|
||||
| Auth | 1,402 | Si | - |
|
||||
| Admin | 1,583 | Si | - |
|
||||
| Payments | 729 | Si | Metered billing |
|
||||
| Assistant | 648 | Si | Streaming respuestas |
|
||||
| Investment | 722 | No | Necesita backend |
|
||||
| Dashboard | 77 | No | Stub |
|
||||
| Settings | 89 | No | Stub |
|
||||
|
||||
#### Gaps Criticos Frontend
|
||||
1. **WebSocket real-time** - Trading usa polling, necesita WS
|
||||
2. **Certificados PDF** - API existe pero no genera/descarga
|
||||
3. **Dark mode** - No implementado
|
||||
4. **Investment module** - Sin backend conectado
|
||||
|
||||
---
|
||||
|
||||
### 2.3 ML ENGINE (FastAPI + Python)
|
||||
|
||||
**Ubicacion:** `/apps/ml-engine/`
|
||||
**LOC:** ~28,523 lineas
|
||||
**Estado:** 75% Completado
|
||||
|
||||
#### Modelos Implementados
|
||||
| Modelo | LOC | Precision | Estado |
|
||||
|--------|-----|-----------|--------|
|
||||
| AMDDetector | 570 | ~75% | COMPLETADO |
|
||||
| RangePredictor | 690 | R^2 NEGATIVO | PROBLEMA |
|
||||
| TPSLClassifier | 658 | ~68% | COMPLETADO |
|
||||
| AttentionModel | 667 | ~60% | COMPLETADO |
|
||||
| NeuralGating | 853 | - | COMPLETADO |
|
||||
| AssetMetamodel | 787 | - | COMPLETADO |
|
||||
|
||||
#### Pipelines
|
||||
| Pipeline | LOC | Estado |
|
||||
|----------|-----|--------|
|
||||
| Phase2Pipeline | 604 | COMPLETADO |
|
||||
| HierarchicalPipeline | 723 | COMPLETADO |
|
||||
| SymbolTimeframeTrainer | 917 | COMPLETADO |
|
||||
| AttentionTrainer | 591 | COMPLETADO |
|
||||
|
||||
#### Gaps Criticos ML Engine
|
||||
1. **RangePredictor R^2 NEGATIVO** - Modelos peor que baseline
|
||||
2. **API no funcional** - Modelos no cargan en startup
|
||||
3. **Backtesting** - Win rate 42.1% (muy bajo)
|
||||
4. **Sin validacion OOS** - Reportes no muestran metricas out-of-sample
|
||||
|
||||
---
|
||||
|
||||
### 2.4 LLM AGENT (FastAPI + Python)
|
||||
|
||||
**Ubicacion:** `/apps/llm-agent/`
|
||||
**LOC:** ~8,000+ lineas
|
||||
**Estado:** 85% Completado
|
||||
|
||||
#### Tools Implementados (34 clases)
|
||||
| Categoria | Tools | Estado |
|
||||
|-----------|-------|--------|
|
||||
| Market Data | 3 | COMPLETADO |
|
||||
| Portfolio | 3 | COMPLETADO |
|
||||
| Trading | 3 | PARCIAL (live trading pendiente) |
|
||||
| MT4 | 7 | COMPLETADO |
|
||||
| ML Analysis | 5 | COMPLETADO |
|
||||
| Auto-Trading | 2 | COMPLETADO |
|
||||
| Strategy | 5 | COMPLETADO |
|
||||
| Education | 2 | COMPLETADO |
|
||||
|
||||
#### Fine-tuning Pipeline
|
||||
| Componente | Estado |
|
||||
|------------|--------|
|
||||
| QLoRA Config | COMPLETADO |
|
||||
| Training Scripts | COMPLETADO |
|
||||
| Dataset Generation | COMPLETADO |
|
||||
| Evaluation | COMPLETADO |
|
||||
|
||||
#### Gaps Criticos LLM Agent
|
||||
1. **Live Trading** - ExecuteTradeTool sin ejecucion real
|
||||
2. **Persistencia** - Decisiones solo en memoria
|
||||
3. **MCPOrchestrator** - Solo 100 LOC (incompleto)
|
||||
4. **Rate Limiting** - No implementado
|
||||
|
||||
---
|
||||
|
||||
### 2.5 TRADING AGENTS (FastAPI + Python)
|
||||
|
||||
**Ubicacion:** `/apps/trading-agents/`
|
||||
**LOC:** ~6,000+ lineas
|
||||
**Estado:** 78% Completado
|
||||
|
||||
#### Agentes
|
||||
| Agente | Perfil | Target Mensual | Max Drawdown | Estado |
|
||||
|--------|--------|----------------|--------------|--------|
|
||||
| Atlas | Conservador | 3-5% | 5% | COMPLETADO |
|
||||
| Orion | Moderado | 5-10% | 10% | COMPLETADO |
|
||||
| Nova | Agresivo | 10%+ | 20% | COMPLETADO |
|
||||
|
||||
#### Estrategias
|
||||
| Estrategia | Agentes | Estado |
|
||||
|------------|---------|--------|
|
||||
| Mean Reversion | Atlas | COMPLETADO |
|
||||
| Grid Trading | Atlas | COMPLETADO |
|
||||
| Trend Following | Orion, Nova | COMPLETADO |
|
||||
| Momentum | Orion, Nova | COMPLETADO |
|
||||
| Scalping | Nova | PENDIENTE |
|
||||
| Breakout | - | PENDIENTE |
|
||||
|
||||
#### Gaps Criticos Trading Agents
|
||||
1. **Scalping/Breakout** - No implementados
|
||||
2. **WebSocket Signals** - Usa polling
|
||||
3. **Persistencia BD** - No almacena trades
|
||||
4. **Testing** - 0% coverage
|
||||
|
||||
---
|
||||
|
||||
### 2.6 MCP/MT4 INTEGRATION
|
||||
|
||||
**Ubicaciones:**
|
||||
- `/apps/mcp-mt4-connector/` (TypeScript)
|
||||
- `/apps/mt4-gateway/` (Python)
|
||||
- `/apps/mcp-binance-connector/` (TypeScript)
|
||||
|
||||
**Estado:** 90% Completado
|
||||
|
||||
#### Componentes
|
||||
| Componente | Puerto | Tools | Estado |
|
||||
|------------|--------|-------|--------|
|
||||
| MCP MT4 Connector | 3605 | 6 | COMPLETADO |
|
||||
| MT4 Gateway | 8090 | - | COMPLETADO |
|
||||
| MCP Binance | 3606 | 7 | COMPLETADO |
|
||||
|
||||
#### Gaps Criticos MCP
|
||||
1. **EA Bridge** - No documentado, dependencia externa
|
||||
2. **Autenticacion** - Endpoints publicos
|
||||
3. **Rate Limiting** - No implementado
|
||||
|
||||
---
|
||||
|
||||
### 2.7 DATABASE (PostgreSQL 16)
|
||||
|
||||
**Ubicacion:** `/apps/database/`
|
||||
**LOC:** ~898 lineas SQL
|
||||
**Estado:** 95% Completado
|
||||
|
||||
#### Schemas
|
||||
| Schema | Tablas | Funciones | Estado |
|
||||
|--------|--------|-----------|--------|
|
||||
| auth | 11 | 4 | COMPLETADO |
|
||||
| education | 14 | 8 | COMPLETADO |
|
||||
| trading | 10 | 4 | COMPLETADO |
|
||||
| investment | 7 | 0 | COMPLETADO |
|
||||
| financial | 10 | 4+ | COMPLETADO |
|
||||
| ml | 9 | 1 | COMPLETADO |
|
||||
| llm | 5 | 0 | PARCIAL (pgvector) |
|
||||
| audit | 7 | 0 | COMPLETADO |
|
||||
| market_data | 4 | 2 | COMPLETADO |
|
||||
| **TOTAL** | **77** | **23+** | - |
|
||||
|
||||
#### Datos Historicos
|
||||
- 10 anos de datos OHLCV
|
||||
- 3.9M registros 5m
|
||||
- 1.3M registros 15m
|
||||
- 6 activos: XAUUSD, EURUSD, BTCUSD, GBPUSD, USDJPY, AUDUSD
|
||||
|
||||
#### Gaps Criticos Database
|
||||
1. **RLS no habilitado** - Multi-tenant sin politicas
|
||||
2. **pgvector opcional** - Tabla embeddings no funcional sin extension
|
||||
|
||||
---
|
||||
|
||||
## 3. MATRIZ DE GAPS PRIORITARIOS
|
||||
|
||||
### 3.1 Prioridad CRITICA (Bloquean produccion)
|
||||
|
||||
| # | Componente | Gap | Impacto | Esfuerzo |
|
||||
|---|------------|-----|---------|----------|
|
||||
| 1 | ML Engine | RangePredictor R^2 negativo | Predicciones inutiles | 3-5 dias |
|
||||
| 2 | ML Engine | API no carga modelos | ML no operativo | 1 dia |
|
||||
| 3 | Backend | ml-integration.service incompleto | Sin senales ML | 2 dias |
|
||||
| 4 | LLM Agent | MCPOrchestrator incompleto | Sin portfolio consolidado | 2 dias |
|
||||
|
||||
### 3.2 Prioridad ALTA (Funcionalidad limitada)
|
||||
|
||||
| # | Componente | Gap | Impacto | Esfuerzo |
|
||||
|---|------------|-----|---------|----------|
|
||||
| 5 | Backend | Auth en paper trading endpoints | Seguridad | 1 dia |
|
||||
| 6 | Frontend | WebSocket real-time | UX degradado | 2 dias |
|
||||
| 7 | Trading Agents | Scalping strategy | Nova incompleto | 3 dias |
|
||||
| 8 | LLM Agent | Live trading execution | No operable | 2 dias |
|
||||
| 9 | Trading Agents | Persistencia BD | Sin historial | 2 dias |
|
||||
| 10 | Database | RLS policies | Multi-tenant inseguro | 1 dia |
|
||||
|
||||
### 3.3 Prioridad MEDIA (Mejoras)
|
||||
|
||||
| # | Componente | Gap | Impacto | Esfuerzo |
|
||||
|---|------------|-----|---------|----------|
|
||||
| 11 | Backend | Testing E2E | Calidad | 3 dias |
|
||||
| 12 | Frontend | Certificados PDF | Feature faltante | 2 dias |
|
||||
| 13 | ML Engine | Validacion OOS | Confianza modelos | 2 dias |
|
||||
| 14 | LLM Agent | Rate limiting | Seguridad API | 1 dia |
|
||||
| 15 | MCP | Autenticacion Bearer | Seguridad | 1 dia |
|
||||
|
||||
---
|
||||
|
||||
## 4. PLAN DE DESARROLLO PROPUESTO
|
||||
|
||||
### SPRINT 1: Estabilizacion ML (Semana 1)
|
||||
|
||||
**Objetivo:** Resolver problemas criticos de ML Engine
|
||||
|
||||
| Tarea | Asignee | Dias | Dependencias |
|
||||
|-------|---------|------|--------------|
|
||||
| Fix RangePredictor (feature engineering) | ML-SPECIALIST | 3 | - |
|
||||
| Implementar auto-load modelos en API | ML-SPECIALIST | 1 | - |
|
||||
| Validacion OOS completa | ML-SPECIALIST | 2 | Fix RangePredictor |
|
||||
| Tests unitarios ML | ML-SPECIALIST | 1 | - |
|
||||
|
||||
**Entregables:**
|
||||
- RangePredictor con R^2 > 0
|
||||
- API ML funcional con modelos cargados
|
||||
- Reporte de validacion OOS
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 2: Integracion Backend (Semana 2)
|
||||
|
||||
**Objetivo:** Completar servicios de integracion
|
||||
|
||||
| Tarea | Asignee | Dias | Dependencias |
|
||||
|-------|---------|------|--------------|
|
||||
| Implementar ml-integration.service.ts | BACKEND | 2 | Sprint 1 |
|
||||
| Auth middleware en paper trading | BACKEND | 1 | - |
|
||||
| Completar agents.service.ts | BACKEND | 1 | - |
|
||||
| Implementar users module | BACKEND | 1 | - |
|
||||
|
||||
**Entregables:**
|
||||
- Backend 100% funcional
|
||||
- Endpoints protegidos
|
||||
- Modulo de usuarios operativo
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 3: LLM y Trading Agents (Semana 3)
|
||||
|
||||
**Objetivo:** Completar funcionalidades de agentes
|
||||
|
||||
| Tarea | Asignee | Dias | Dependencias |
|
||||
|-------|---------|------|--------------|
|
||||
| Completar MCPOrchestrator | LLM-SPECIALIST | 2 | - |
|
||||
| Implementar live trading execution | LLM-SPECIALIST | 2 | MCPOrchestrator |
|
||||
| Implementar Scalping strategy | TRADING-SPECIALIST | 2 | - |
|
||||
| Persistencia BD en Trading Agents | BACKEND | 2 | - |
|
||||
|
||||
**Entregables:**
|
||||
- Portfolio consolidado funcional
|
||||
- Live trading operativo
|
||||
- Scalping strategy para Nova
|
||||
- Historial de trades en BD
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 4: Frontend y UX (Semana 4)
|
||||
|
||||
**Objetivo:** Mejorar experiencia de usuario
|
||||
|
||||
| Tarea | Asignee | Dias | Dependencias |
|
||||
|-------|---------|------|--------------|
|
||||
| WebSocket real-time en Trading | FRONTEND | 2 | - |
|
||||
| Streaming respuestas LLM | FRONTEND | 1 | - |
|
||||
| Certificados PDF education | FRONTEND | 2 | - |
|
||||
| Investment module conectado | FRONTEND | 2 | Sprint 2 |
|
||||
|
||||
**Entregables:**
|
||||
- Trading con precios en tiempo real
|
||||
- Chat con streaming
|
||||
- Certificados descargables
|
||||
- Investment funcional
|
||||
|
||||
---
|
||||
|
||||
### SPRINT 5: Seguridad y Testing (Semana 5)
|
||||
|
||||
**Objetivo:** Hardening para produccion
|
||||
|
||||
| Tarea | Asignee | Dias | Dependencias |
|
||||
|-------|---------|------|--------------|
|
||||
| Habilitar RLS en PostgreSQL | DBA | 1 | - |
|
||||
| Rate limiting en APIs | BACKEND | 1 | - |
|
||||
| Autenticacion MCP servers | BACKEND | 1 | - |
|
||||
| E2E Testing suite | QA | 3 | Sprints 1-4 |
|
||||
|
||||
**Entregables:**
|
||||
- RLS habilitado en tablas criticas
|
||||
- APIs con rate limiting
|
||||
- MCP con auth Bearer
|
||||
- Suite E2E > 80% cobertura
|
||||
|
||||
---
|
||||
|
||||
## 5. DEPENDENCIAS ENTRE COMPONENTES
|
||||
|
||||
```
|
||||
Database (PostgreSQL)
|
||||
|
|
||||
+---> Backend (Express.js)
|
||||
| |
|
||||
| +---> Frontend (React)
|
||||
| |
|
||||
| +---> ML Engine (FastAPI)
|
||||
| | |
|
||||
| | +---> Trading Agents (FastAPI)
|
||||
| | |
|
||||
| | +---> LLM Agent (FastAPI)
|
||||
| | |
|
||||
| | +---> MCP MT4 Connector
|
||||
| | | |
|
||||
| | | +---> MT4 Gateway
|
||||
| | | |
|
||||
| | | +---> EA Bridge (EXTERNO)
|
||||
| | |
|
||||
| | +---> MCP Binance Connector
|
||||
| |
|
||||
| +---> Data Service (FastAPI)
|
||||
|
|
||||
+---> Ollama (LLM Local)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. RIESGOS IDENTIFICADOS
|
||||
|
||||
| Riesgo | Probabilidad | Impacto | Mitigacion |
|
||||
|--------|--------------|---------|------------|
|
||||
| ML models overfitting | Alta | Alto | Walk-forward validation riguroso |
|
||||
| EA Bridge no disponible | Media | Alto | Documentar dependencia, crear mock |
|
||||
| Latencia MCP-MT4 | Media | Medio | Connection pooling, cache |
|
||||
| Costos API LLM | Baja | Medio | Ollama local como default |
|
||||
| Data leakage ML | Media | Alto | Auditar features, gaps temporales |
|
||||
|
||||
---
|
||||
|
||||
## 7. METRICAS DE EXITO
|
||||
|
||||
### KPIs de Desarrollo
|
||||
- Todos los gaps CRITICOS resueltos
|
||||
- Cobertura de tests > 60%
|
||||
- Tiempo de respuesta API < 200ms (p95)
|
||||
|
||||
### KPIs de ML
|
||||
- RangePredictor R^2 > 0.15
|
||||
- Win rate backtesting > 55%
|
||||
- Precision AMD > 70%
|
||||
|
||||
### KPIs de Produccion
|
||||
- Uptime > 99.5%
|
||||
- Error rate < 1%
|
||||
- Latencia trading < 500ms
|
||||
|
||||
---
|
||||
|
||||
## 8. PROXIMOS PASOS INMEDIATOS
|
||||
|
||||
1. **Aprobar plan de desarrollo** con stakeholders
|
||||
2. **Iniciar Sprint 1** - Fix ML Engine
|
||||
3. **Documentar EA Bridge** - Dependencia critica externa
|
||||
4. **Setup CI/CD** - Para testing automatizado
|
||||
|
||||
---
|
||||
|
||||
**Documento generado:** 2026-01-07
|
||||
**Version:** 1.0.0
|
||||
**Autor:** Technical Lead (Claude Opus 4.5)
|
||||
@ -1,319 +0,0 @@
|
||||
# Analisis de Dependencias
|
||||
## Trading Platform - Fase 4 del Proceso de Planeacion
|
||||
|
||||
**Fecha:** 2026-01-07
|
||||
**Objetivo:** Mapear dependencias entre archivos a modificar
|
||||
|
||||
---
|
||||
|
||||
## 1. MAPA DE DEPENDENCIAS POR SPRINT
|
||||
|
||||
### Sprint 1: ML Engine
|
||||
|
||||
```
|
||||
src/models/range_predictor.py
|
||||
|-- DEPENDE DE -->
|
||||
| src/data/features.py (Feature engineering)
|
||||
| src/data/targets.py (Target calculation)
|
||||
| src/training/sample_weighting.py (Weights)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/pipelines/phase2_pipeline.py
|
||||
src/services/prediction_service.py
|
||||
src/api/main.py (endpoints)
|
||||
|
||||
src/api/main.py
|
||||
|-- DEPENDE DE -->
|
||||
| src/services/prediction_service.py
|
||||
| src/models/*.py (todos los modelos)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
apps/backend/src/shared/clients/ml-engine.client.ts
|
||||
apps/llm-agent/src/tools/ml_tools.py
|
||||
```
|
||||
|
||||
### Sprint 2: Backend
|
||||
|
||||
```
|
||||
src/modules/ml/services/ml-integration.service.ts
|
||||
|-- DEPENDE DE -->
|
||||
| src/shared/clients/ml-engine.client.ts (HTTP client)
|
||||
| src/config/index.ts (ML_ENGINE_URL)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/modules/ml/controllers/ml.controller.ts
|
||||
src/modules/trading/services/indicators.service.ts
|
||||
|
||||
src/modules/trading/trading.routes.ts
|
||||
|-- DEPENDE DE -->
|
||||
| src/core/guards/auth.guard.ts
|
||||
| src/core/middleware/auth.middleware.ts
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
apps/frontend/src/services/trading.service.ts
|
||||
|
||||
src/modules/users/
|
||||
|-- DEPENDE DE -->
|
||||
| src/shared/database/ (PostgreSQL connection)
|
||||
| src/modules/auth/services/ (User validation)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
apps/frontend/src/modules/settings/
|
||||
```
|
||||
|
||||
### Sprint 3: LLM Agent + Trading Agents
|
||||
|
||||
```
|
||||
apps/llm-agent/src/services/mcp_orchestrator.py
|
||||
|-- DEPENDE DE -->
|
||||
| apps/mcp-mt4-connector/ (MCP Server)
|
||||
| apps/mcp-binance-connector/ (MCP Server)
|
||||
| src/config.py (URLs)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/tools/trading.py
|
||||
src/tools/portfolio.py
|
||||
src/api/routes.py
|
||||
|
||||
apps/llm-agent/src/tools/trading.py
|
||||
|-- DEPENDE DE -->
|
||||
| src/services/mcp_orchestrator.py
|
||||
| src/services/risk_manager.py
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/api/auto_trade_routes.py
|
||||
|
||||
apps/trading-agents/src/strategies/scalping.py (NUEVO)
|
||||
|-- DEPENDE DE -->
|
||||
| src/strategies/base.py
|
||||
| src/agents/nova.py (consumidor)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
config/strategies.yaml
|
||||
config/agents.yaml
|
||||
|
||||
apps/trading-agents/src/persistence/db_manager.py (NUEVO)
|
||||
|-- DEPENDE DE -->
|
||||
| PostgreSQL (schema: trading)
|
||||
| src/agents/base.py (Trade dataclass)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/agents/atlas.py
|
||||
src/agents/orion.py
|
||||
src/agents/nova.py
|
||||
src/api/main.py
|
||||
```
|
||||
|
||||
### Sprint 4: Frontend
|
||||
|
||||
```
|
||||
src/services/websocket.service.ts
|
||||
|-- DEPENDE DE -->
|
||||
| apps/backend/src/core/websocket/websocket.server.ts
|
||||
| src/stores/tradingStore.ts
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/modules/trading/pages/Trading.tsx
|
||||
src/modules/trading/components/CandlestickChartWithML.tsx
|
||||
|
||||
src/modules/assistant/pages/Assistant.tsx
|
||||
|-- DEPENDE DE -->
|
||||
| src/services/chat.service.ts
|
||||
| apps/llm-agent/src/api/routes.py (SSE streaming)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/stores/chatStore.ts
|
||||
|
||||
src/modules/education/services/certificate.service.ts (NUEVO)
|
||||
|-- DEPENDE DE -->
|
||||
| apps/backend/src/modules/education/services/course.service.ts
|
||||
| PDF generation library (pdfkit o similar)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/modules/education/pages/CourseDetail.tsx
|
||||
```
|
||||
|
||||
### Sprint 5: Security & Testing
|
||||
|
||||
```
|
||||
apps/database/ddl/rls/*.sql (NUEVO)
|
||||
|-- DEPENDE DE -->
|
||||
| apps/database/ddl/schemas/*/tables/*.sql
|
||||
| PostgreSQL current_setting('app.user_id')
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
apps/backend/ (debe pasar user_id en conexiones)
|
||||
|
||||
apps/backend/src/middleware/rate-limiter.ts
|
||||
|-- DEPENDE DE -->
|
||||
| express-rate-limit package
|
||||
| Redis (opcional, para distributed)
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
src/index.ts (middleware chain)
|
||||
|
||||
e2e/cypress/integration/*.spec.ts (NUEVO)
|
||||
|-- DEPENDE DE -->
|
||||
| Todos los endpoints backend
|
||||
| Todos los componentes frontend
|
||||
|
|
||||
|-- IMPACTA A -->
|
||||
CI/CD pipeline
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. GRAFO DE DEPENDENCIAS CRITICAS
|
||||
|
||||
```
|
||||
PostgreSQL
|
||||
|
|
||||
+------------+------------+
|
||||
| | |
|
||||
Backend ML Engine Trading Agents
|
||||
| | |
|
||||
+------+-----+------------+
|
||||
|
|
||||
LLM Agent
|
||||
|
|
||||
+---------+---------+
|
||||
| |
|
||||
MCP MT4 Connector MCP Binance
|
||||
|
|
||||
MT4 Gateway
|
||||
|
|
||||
EA Bridge (EXTERNO)
|
||||
|
|
||||
MT4 Terminal
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. ARCHIVOS DE ALTO IMPACTO
|
||||
|
||||
### Archivos que impactan muchos otros (modificar con cuidado)
|
||||
|
||||
| Archivo | Dependientes | Riesgo |
|
||||
|---------|-------------|--------|
|
||||
| `apps/ml-engine/src/api/main.py` | Backend, LLM Agent, Frontend | ALTO |
|
||||
| `apps/backend/src/shared/clients/ml-engine.client.ts` | 5+ servicios | ALTO |
|
||||
| `apps/llm-agent/src/services/mcp_orchestrator.py` | Tools, API | ALTO |
|
||||
| `apps/trading-agents/src/agents/base.py` | 3 agentes | ALTO |
|
||||
| `apps/backend/src/config/index.ts` | Todo el backend | ALTO |
|
||||
| `apps/frontend/src/stores/tradingStore.ts` | Trading pages | MEDIO |
|
||||
|
||||
### Archivos aislados (bajo riesgo de impacto)
|
||||
|
||||
| Archivo | Dependientes | Riesgo |
|
||||
|---------|-------------|--------|
|
||||
| `apps/trading-agents/src/strategies/scalping.py` | Solo Nova | BAJO |
|
||||
| `apps/frontend/src/modules/education/services/certificate.service.ts` | Solo CourseDetail | BAJO |
|
||||
| `e2e/cypress/integration/*.spec.ts` | Ninguno (tests) | BAJO |
|
||||
|
||||
---
|
||||
|
||||
## 4. ORDEN DE MODIFICACION RECOMENDADO
|
||||
|
||||
### Sprint 1 - Orden sugerido
|
||||
|
||||
1. `src/data/features.py` - Primero (base de todo)
|
||||
2. `src/data/targets.py` - Segundo
|
||||
3. `src/models/range_predictor.py` - Tercero (usa 1 y 2)
|
||||
4. `src/training/*.py` - Cuarto (reentrenar)
|
||||
5. `src/api/main.py` - Quinto (exponer)
|
||||
6. Tests - Ultimo
|
||||
|
||||
### Sprint 2 - Orden sugerido
|
||||
|
||||
1. `src/shared/clients/ml-engine.client.ts` - Primero (si hay cambios)
|
||||
2. `src/modules/ml/services/ml-integration.service.ts` - Segundo
|
||||
3. `src/modules/trading/trading.routes.ts` - Tercero (auth)
|
||||
4. `src/modules/investment/investment.routes.ts` - Cuarto (auth)
|
||||
5. `src/modules/users/*` - Quinto (nuevo modulo)
|
||||
6. Tests - Ultimo
|
||||
|
||||
### Sprint 3 - Orden sugerido
|
||||
|
||||
1. `src/services/mcp_orchestrator.py` - Primero (fundacion)
|
||||
2. `src/tools/trading.py` - Segundo (usa orchestrator)
|
||||
3. `src/strategies/scalping.py` - Tercero (independiente)
|
||||
4. `src/persistence/db_manager.py` - Cuarto (independiente)
|
||||
5. Agentes (atlas, orion, nova) - Quinto (integran persistencia)
|
||||
6. API updates - Ultimo
|
||||
|
||||
### Sprint 4 - Orden sugerido
|
||||
|
||||
1. Backend WebSocket fixes (si necesario) - Primero
|
||||
2. `src/services/websocket.service.ts` - Segundo
|
||||
3. Components (Trading, Chat) - Tercero
|
||||
4. `src/services/certificate.service.ts` - Cuarto
|
||||
5. Investment module - Quinto
|
||||
|
||||
### Sprint 5 - Orden sugerido
|
||||
|
||||
1. DDL RLS scripts - Primero (DB nivel)
|
||||
2. Backend rate limiter - Segundo
|
||||
3. MCP auth - Tercero
|
||||
4. E2E tests - Ultimo (requiere todo funcional)
|
||||
|
||||
---
|
||||
|
||||
## 5. CONFLICTOS POTENCIALES
|
||||
|
||||
### 5.1 Archivos con multiples modificadores
|
||||
|
||||
| Archivo | Sprints | Conflicto |
|
||||
|---------|---------|-----------|
|
||||
| `apps/backend/src/index.ts` | 2, 5 | Middleware chain |
|
||||
| `apps/trading-agents/config/agents.yaml` | 3 | Scalping config |
|
||||
|
||||
**Mitigacion:** Coordinar commits, usar feature branches
|
||||
|
||||
### 5.2 Interfaces compartidas
|
||||
|
||||
| Interface | Componentes | Riesgo |
|
||||
|-----------|-------------|--------|
|
||||
| ML Signal format | ML Engine, Backend, LLM Agent | Si cambia, rompe 3 componentes |
|
||||
| Trade execution | LLM Agent, Trading Agents, MCP | Si cambia, rompe integracion |
|
||||
|
||||
**Mitigacion:** Versionar interfaces, backward compatibility
|
||||
|
||||
---
|
||||
|
||||
## 6. DEPENDENCIAS EXTERNAS
|
||||
|
||||
| Dependencia | Componente | Criticidad | Alternativa |
|
||||
|-------------|------------|------------|-------------|
|
||||
| EA Bridge | MCP MT4 | CRITICA | Mock service |
|
||||
| Binance API | MCP Binance | ALTA | Testnet |
|
||||
| Ollama | LLM Agent | ALTA | Claude API |
|
||||
| PostgreSQL | Todos | CRITICA | Ninguna |
|
||||
| Redis | Backend | MEDIA | In-memory |
|
||||
|
||||
---
|
||||
|
||||
## 7. VALIDACION DE INTEGRACION
|
||||
|
||||
### Tests de integracion requeridos entre componentes
|
||||
|
||||
| Desde | Hacia | Test Requerido |
|
||||
|-------|-------|----------------|
|
||||
| Backend | ML Engine | `/api/v1/ml/health` responde |
|
||||
| LLM Agent | MCP MT4 | Tool execution funciona |
|
||||
| Frontend | Backend WS | Conexion WebSocket estable |
|
||||
| Trading Agents | PostgreSQL | Trades persisten |
|
||||
|
||||
---
|
||||
|
||||
## 8. RECOMENDACIONES
|
||||
|
||||
1. **Crear interfaces versionadas** antes de modificar componentes
|
||||
2. **Feature flags** para cambios grandes (ej: live trading)
|
||||
3. **Contract tests** entre servicios
|
||||
4. **Rollback plan** documentado por sprint
|
||||
5. **Ambiente staging** para integracion
|
||||
|
||||
---
|
||||
|
||||
**Analisis completado:** 2026-01-07
|
||||
**Siguiente paso:** Fase 5 - Refinamiento del Plan
|
||||
@ -1,312 +0,0 @@
|
||||
# Reporte de Analisis: RangePredictor R^2 Negativo
|
||||
## Trading Platform - Sprint 1, Tarea S1-T1
|
||||
|
||||
**Fecha:** 2026-01-07
|
||||
**Ejecutor:** Claude Opus 4.5 (ML-SPECIALIST)
|
||||
**Estado:** COMPLETADO
|
||||
|
||||
---
|
||||
|
||||
## 1. RESUMEN EJECUTIVO
|
||||
|
||||
### 1.1 Problema Identificado
|
||||
|
||||
El modelo `RangePredictor` presenta **R^2 negativo** en todas las evaluaciones:
|
||||
|
||||
| Modelo | Symbol | Timeframe | Target | R^2 |
|
||||
|--------|--------|-----------|--------|-----|
|
||||
| GBPUSD_5m_high_h3 | GBPUSD | 5m | high | **-0.6309** |
|
||||
| GBPUSD_5m_low_h3 | GBPUSD | 5m | low | **-0.6558** |
|
||||
| GBPUSD_15m_high_h3 | GBPUSD | 15m | high | **-0.6944** |
|
||||
| GBPUSD_15m_low_h3 | GBPUSD | 15m | low | **-0.7500** |
|
||||
|
||||
**Interpretacion:** Un R^2 negativo significa que el modelo predice PEOR que simplemente usar la media historica como prediccion.
|
||||
|
||||
### 1.2 Impacto
|
||||
|
||||
- Predicciones de rango inutiles para trading
|
||||
- Sistema de senales ML no operativo
|
||||
- Backtesting con win rate bajo (42.1%)
|
||||
|
||||
---
|
||||
|
||||
## 2. ANALISIS DE CAUSAS RAIZ
|
||||
|
||||
### 2.1 Causa 1: Targets Normalizados con Escala Incorrecta
|
||||
|
||||
**Archivo:** `src/data/targets.py`
|
||||
|
||||
**Hallazgo:**
|
||||
El target se calcula en valores absolutos (USD) pero las features estan normalizadas.
|
||||
En el entrenamiento, los valores de target son muy pequenos (0.0005 - 0.001) debido a normalizacion implicita.
|
||||
|
||||
```python
|
||||
# Linea 206-207 de targets.py
|
||||
df[f'delta_high_{horizon.name}'] = future_high - df['close'] # Valores en USD
|
||||
df[f'delta_low_{horizon.name}'] = df['close'] - future_low # Valores en USD
|
||||
```
|
||||
|
||||
**Problema:**
|
||||
- Para GBPUSD, delta_high podria ser 0.0005 (5 pips)
|
||||
- El modelo XGBoost tiene dificultad con valores tan pequenos
|
||||
- La varianza del target es minima comparada con el ruido
|
||||
|
||||
**Solucion Propuesta:**
|
||||
1. Normalizar targets por ATR antes de entrenar
|
||||
2. Usar targets en pips o puntos en lugar de precio absoluto
|
||||
3. Escalar features y targets de forma consistente
|
||||
|
||||
---
|
||||
|
||||
### 2.2 Causa 2: Features No Predictivas para el Target
|
||||
|
||||
**Archivo:** `src/data/features.py`
|
||||
|
||||
**Hallazgo:**
|
||||
Las features son principalmente indicadores tecnicos (RSI, MACD, Bollinger) que son:
|
||||
- Lagging indicators (basados en precio pasado)
|
||||
- No tienen relacion directa con rango futuro
|
||||
- Estan diseados para direccion, no para magnitud
|
||||
|
||||
**Features Actuales (Lineas 17-27):**
|
||||
```python
|
||||
'minimal': [
|
||||
'rsi', 'macd', 'macd_signal', 'bb_upper', 'bb_lower',
|
||||
'atr', 'volume_zscore', 'returns', 'log_returns'
|
||||
]
|
||||
```
|
||||
|
||||
**Problema:**
|
||||
- RSI predice condicion de sobrecompra/sobreventa, NO rango futuro
|
||||
- MACD predice tendencia, NO magnitud
|
||||
- Solo `atr` tiene relacion con volatilidad futura
|
||||
|
||||
**Solucion Propuesta:**
|
||||
1. Agregar features de volatilidad: ATR lags, volatilidad historica
|
||||
2. Agregar features de sesion: hora, dia de semana (codificados ciclicamente)
|
||||
3. Agregar features de momentum de volatilidad: cambio en ATR
|
||||
4. Reducir features de direccion no relevantes
|
||||
|
||||
---
|
||||
|
||||
### 2.3 Causa 3: Sample Weighting Agresivo
|
||||
|
||||
**Archivo:** `src/training/sample_weighting.py`
|
||||
|
||||
**Hallazgo:**
|
||||
El weighting de samples (softplus con beta=4.0) es muy agresivo:
|
||||
- Reduce peso de movimientos "normales" casi a cero
|
||||
- Solo entrena efectivamente con movimientos extremos
|
||||
- Esto causa sesgo hacia predicciones de alto rango
|
||||
|
||||
**Configuracion Actual (Lineas 66-69):**
|
||||
```python
|
||||
softplus_beta: float = 4.0 # MUY agresivo
|
||||
softplus_w_max: float = 3.0
|
||||
```
|
||||
|
||||
**Problema:**
|
||||
- Modelo aprende solo de 24-35% de los datos (high flow periods)
|
||||
- Predicciones sesgadas hacia valores altos
|
||||
- Varianza de prediccion muy baja (no captura distribucion real)
|
||||
|
||||
**Solucion Propuesta:**
|
||||
1. Reducir softplus_beta a 2.0 o menos
|
||||
2. Aumentar min_weight para incluir mas samples
|
||||
3. Considerar weighting uniforme como baseline
|
||||
|
||||
---
|
||||
|
||||
### 2.4 Causa 4: Data Leakage Potencial
|
||||
|
||||
**Archivo:** `src/training/sample_weighting.py`, `src/data/corrected_targets.py`
|
||||
|
||||
**Hallazgo:**
|
||||
Aunque se usa `shift(1)` en el factor de rolling median, hay posible leakage en:
|
||||
1. Targets que incluyen precio actual en calculo de futuros
|
||||
2. Features que usan datos futuros implicitamente
|
||||
|
||||
**Verificacion Requerida:**
|
||||
```python
|
||||
# Linea 126-129 sample_weighting.py
|
||||
factor = candle_range.rolling(
|
||||
window=window,
|
||||
min_periods=min_periods
|
||||
).median().shift(1) # Correcto - usa shift(1)
|
||||
|
||||
# Linea 190-195 targets.py - VERIFICAR
|
||||
for i in range(start, end + 1): # start=1, correcto
|
||||
future_highs.append(df['high'].shift(-i))
|
||||
```
|
||||
|
||||
**Resultado:** El codigo de targets usa `start_offset=1`, lo cual es correcto.
|
||||
No hay data leakage evidente en targets, pero hay que verificar features.
|
||||
|
||||
---
|
||||
|
||||
### 2.5 Causa 5: Hiperparametros XGBoost No Optimizados
|
||||
|
||||
**Archivo:** `src/models/range_predictor.py`
|
||||
|
||||
**Configuracion Actual (Lineas 146-162):**
|
||||
```python
|
||||
'xgboost': {
|
||||
'n_estimators': 200,
|
||||
'max_depth': 5,
|
||||
'learning_rate': 0.05,
|
||||
'subsample': 0.8,
|
||||
'colsample_bytree': 0.8,
|
||||
'min_child_weight': 3,
|
||||
'gamma': 0.1,
|
||||
'reg_alpha': 0.1,
|
||||
'reg_lambda': 1.0,
|
||||
}
|
||||
```
|
||||
|
||||
**Problema:**
|
||||
- `max_depth=5` puede ser muy profundo para datos ruidosos
|
||||
- `learning_rate=0.05` combinado con `n_estimators=200` puede overfit
|
||||
- `min_child_weight=3` puede ser muy bajo
|
||||
|
||||
**Solucion Propuesta:**
|
||||
1. Reducir `max_depth` a 3
|
||||
2. Aumentar `min_child_weight` a 10
|
||||
3. Aumentar regularizacion (`reg_alpha`, `reg_lambda`)
|
||||
4. Usar early stopping mas agresivo
|
||||
|
||||
---
|
||||
|
||||
## 3. PLAN DE CORRECCION
|
||||
|
||||
### 3.1 Fase 1: Correccion de Targets (Prioridad ALTA)
|
||||
|
||||
**Archivo:** `src/data/targets.py`
|
||||
|
||||
**Cambios:**
|
||||
1. Normalizar targets por ATR:
|
||||
```python
|
||||
# Agregar normalizacion
|
||||
df[f'delta_high_{horizon.name}_norm'] = (future_high - df['close']) / df['ATR']
|
||||
df[f'delta_low_{horizon.name}_norm'] = (df['close'] - future_low) / df['ATR']
|
||||
```
|
||||
|
||||
2. Usar targets normalizados en entrenamiento
|
||||
|
||||
**Beneficio Esperado:** Targets en escala [-3, 3] en lugar de [0, 0.001]
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Fase 2: Correccion de Features (Prioridad ALTA)
|
||||
|
||||
**Archivo:** `src/data/features.py`
|
||||
|
||||
**Cambios:**
|
||||
1. Agregar features de volatilidad:
|
||||
```python
|
||||
'volatility': [
|
||||
'atr',
|
||||
'atr_ratio', # ATR / rolling_median(ATR)
|
||||
'atr_pct_change',
|
||||
'range_pct', # (high-low)/close
|
||||
'true_range',
|
||||
'realized_volatility_10',
|
||||
'realized_volatility_20'
|
||||
]
|
||||
```
|
||||
|
||||
2. Agregar features de sesion (ya existen en `create_time_features`):
|
||||
```python
|
||||
# Ya implementado correctamente
|
||||
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
|
||||
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
|
||||
```
|
||||
|
||||
3. Usar solo features relevantes para prediccion de rango
|
||||
|
||||
---
|
||||
|
||||
### 3.3 Fase 3: Ajuste de Sample Weighting (Prioridad MEDIA)
|
||||
|
||||
**Archivo:** `src/training/sample_weighting.py`
|
||||
|
||||
**Cambios:**
|
||||
```python
|
||||
# Configuracion menos agresiva
|
||||
SampleWeightConfig(
|
||||
softplus_beta=2.0, # Reducir de 4.0
|
||||
softplus_w_max=2.0, # Reducir de 3.0
|
||||
min_weight=0.3, # Aumentar de 0.1
|
||||
filter_low_ratio=False # Incluir todos los samples
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.4 Fase 4: Optimizacion de Hiperparametros (Prioridad MEDIA)
|
||||
|
||||
**Archivo:** `src/models/range_predictor.py`
|
||||
|
||||
**Cambios:**
|
||||
```python
|
||||
'xgboost': {
|
||||
'n_estimators': 100, # Reducir
|
||||
'max_depth': 3, # Reducir de 5
|
||||
'learning_rate': 0.03, # Reducir
|
||||
'subsample': 0.7,
|
||||
'colsample_bytree': 0.7,
|
||||
'min_child_weight': 10, # Aumentar de 3
|
||||
'gamma': 0.5, # Aumentar de 0.1
|
||||
'reg_alpha': 1.0, # Aumentar de 0.1
|
||||
'reg_lambda': 10.0, # Aumentar de 1.0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. CRITERIOS DE EXITO
|
||||
|
||||
| Metrica | Valor Actual | Minimo Aceptable | Objetivo |
|
||||
|---------|--------------|------------------|----------|
|
||||
| R^2 (validacion) | -0.65 | > 0.05 | > 0.15 |
|
||||
| MAE (normizado) | N/A | < 0.5 ATR | < 0.3 ATR |
|
||||
| Direccion | 98% | > 60% | > 65% |
|
||||
| Win Rate Backtest | 42% | > 50% | > 55% |
|
||||
|
||||
---
|
||||
|
||||
## 5. ORDEN DE EJECUCION
|
||||
|
||||
1. **S1-T2:** Implementar normalizacion de targets por ATR
|
||||
2. **S1-T3:** Verificar no hay data leakage en features
|
||||
3. **S1-T4a:** Reducir agresividad de sample weighting
|
||||
4. **S1-T4b:** Ajustar hiperparametros XGBoost
|
||||
5. **S1-T5:** Reentrenar modelos con correcciones
|
||||
6. **S1-T6:** Validar R^2 > 0 en datos OOS
|
||||
|
||||
---
|
||||
|
||||
## 6. ARCHIVOS A MODIFICAR
|
||||
|
||||
| Archivo | Tipo de Cambio | Lineas Estimadas |
|
||||
|---------|---------------|------------------|
|
||||
| `src/data/targets.py` | Agregar normalizacion | +20 |
|
||||
| `src/data/features.py` | Agregar features volatilidad | +50 |
|
||||
| `src/training/sample_weighting.py` | Reducir agresividad | ~10 |
|
||||
| `src/models/range_predictor.py` | Ajustar hiperparametros | ~15 |
|
||||
| `scripts/train_symbol_timeframe_models.py` | Usar targets normalizados | ~20 |
|
||||
|
||||
---
|
||||
|
||||
## 7. RIESGOS
|
||||
|
||||
| Riesgo | Probabilidad | Mitigacion |
|
||||
|--------|--------------|------------|
|
||||
| R^2 sigue negativo | Media | Plan B: modelo baseline (media movil) |
|
||||
| Normalizacion introduce leakage | Baja | Usar ATR shift(1) |
|
||||
| Overfitting a nuevos hiperparametros | Media | Walk-forward validation |
|
||||
|
||||
---
|
||||
|
||||
**Reporte completado:** 2026-01-07
|
||||
**Siguiente paso:** S1-T2 - Implementar normalizacion de targets
|
||||
|
||||
Loading…
Reference in New Issue
Block a user