chore: Update orchestration docs, CLAUDE.md, docker-compose for Phase 2-4

- Update CLAUDE.md with project-level instructions
- Update docker-compose.yml with correct service ports
- Update PROJECT-PROFILE.yml with current module status
- Update PROJECT-STATUS.md with Phase 2/4 progress
- Update PROXIMA-ACCION.md with current priorities
- Purge stale sprint reports from _archive
- Add TASK-2026-01-27-MASTER-ANALYSIS-PLAN documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Adrian Flores Cortes 2026-01-27 04:40:59 -06:00
parent 92befe36d7
commit 1cdae920fc
14 changed files with 1470 additions and 2007 deletions

View File

@ -5,7 +5,7 @@
**Proyecto:** trading-platform
**Tipo:** STANDALONE
**Versión:** 1.0.0
**Actualizado:** 2026-01-24
**Actualizado:** 2026-01-27
---
@ -59,7 +59,7 @@ User: trading_user
Password: trading_dev_2026
Port: 5432
Host: localhost
Schemas: core, trading, ml, portfolio
Schemas: auth, education, trading, investment, financial, portfolio, market_data, ml, llm, audit
```
---
@ -92,15 +92,15 @@ trading-platform/
| ID | Módulo | Progreso | Descripción |
|----|--------|----------|-------------|
| OQI-001 | fundamentos-auth | 70% | Autenticación base |
| OQI-002 | educativo | 30% | Módulo educativo |
| OQI-003 | trading-charts | 40% | Charts de trading |
| OQI-004 | cuentas-inversion | 35% | Cuentas de inversión |
| OQI-005 | pagos-stripe | 50% | Integración Stripe |
| OQI-006 | senales-ml | 60% | Señales ML |
| OQI-007 | llm-strategy-agent | 25% | Agente LLM |
| OQI-008 | portfolio-manager | 20% | Gestión portafolio |
| OQI-009 | mt4-gateway | 15% | Gateway MetaTrader |
| OQI-001 | fundamentos-auth | 85% | Autenticacion base (token rotation, 2FA, OAuth) |
| OQI-002 | educativo | 55% | Modulo educativo (courses, quizzes, gamification, video) |
| OQI-003 | trading-charts | 60% | Charts de trading (panels, indicators, screener) |
| OQI-004 | cuentas-inversion | 55% | Cuentas de inversion (detail, wizard, risk analysis) |
| OQI-005 | pagos-stripe | 65% | Integracion Stripe (elements, refunds, invoices) |
| OQI-006 | senales-ml | 75% | Senales ML (models, signals, ensemble, ICT) |
| OQI-007 | llm-strategy-agent | 45% | Agente LLM (panels, prompts, connection, tokens) |
| OQI-008 | portfolio-manager | 45% | Gestion portafolio (dashboard, allocations, goals) |
| OQI-009 | mt4-gateway | 15% | Gateway MetaTrader (NO FUNCIONAL) |
---
@ -133,7 +133,7 @@ trading-platform/
### 2. ML Models
- Los modelos ML están en `apps/ml-engine/`
- Usar TensorFlow para predicciones
- Usar PyTorch + XGBoost para predicciones (NO TensorFlow)
- Validar con backtesting antes de deploy
### 3. Trading Safety

View File

@ -23,7 +23,7 @@ services:
# PostgreSQL nativo: localhost:5432
# - Database: trading_platform
# - User: trading_user
# - Password: trading_dev_2025
# - Password: trading_dev_2026
#
# Redis nativo: localhost:6379
# - DB: 1 (asignado a trading-platform)
@ -47,7 +47,7 @@ services:
DB_PORT: 5432
DB_NAME: trading_platform
DB_USER: trading_user
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2025}
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2026}
# Redis nativo
REDIS_HOST: host.docker.internal
REDIS_PORT: 6379
@ -112,7 +112,7 @@ services:
DB_PORT: 5432
DB_NAME: trading_platform
DB_USER: trading_user
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2025}
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2026}
# Redis nativo
REDIS_HOST: host.docker.internal
REDIS_PORT: 6379
@ -144,7 +144,7 @@ services:
DB_PORT: 5432
DB_NAME: trading_platform
DB_USER: trading_user
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2025}
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2026}
POLYGON_API_KEY: ${POLYGON_API_KEY}
METAAPI_TOKEN: ${METAAPI_TOKEN}
METAAPI_ACCOUNT_ID: ${METAAPI_ACCOUNT_ID}
@ -177,7 +177,7 @@ services:
DB_PORT: 5432
DB_NAME: trading_platform
DB_USER: trading_user
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2025}
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2026}
# Redis nativo
REDIS_HOST: host.docker.internal
REDIS_PORT: 6379
@ -217,7 +217,7 @@ services:
DB_PORT: 5432
DB_NAME: trading_platform
DB_USER: trading_user
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2025}
DB_PASSWORD: ${DB_PASSWORD:-trading_dev_2026}
# Redis nativo
REDIS_HOST: host.docker.internal
REDIS_PORT: 6379

View File

@ -49,19 +49,31 @@ stack:
ml:
frameworks:
- "TensorFlow"
- "PyTorch"
- "XGBoost"
- "scikit-learn"
- "pandas"
uso: "Predicciones y señales de trading"
- "NumPy"
uso: "Predicciones y senales de trading (3-level hierarchical pipeline)"
database:
motor: "PostgreSQL"
version: "16+"
schemas:
- "core"
- "auth"
- "education"
- "trading"
- "ml"
- "investment"
- "financial"
- "portfolio"
- "market_data"
- "ml"
- "llm"
- "audit"
tablas_total: 89
funciones_total: 41
triggers_total: 43
enums_total: 63
# ─────────────────────────────────────────────────────────────────────────────
# SERVICIOS
@ -95,16 +107,20 @@ servicios:
python_services:
- nombre: "ml-engine"
puerto: 8000
descripcion: "Motor de ML"
puerto: 3083
descripcion: "Motor de ML (PyTorch + XGBoost)"
- nombre: "data-service"
puerto: 8001
descripcion: "Datos de mercado"
puerto: 3084
descripcion: "Datos de mercado (Binance, Polygon)"
- nombre: "mt4-gateway"
puerto: 8002
descripcion: "Ejecución MT4/MT5"
- nombre: "llm-agent"
puerto: 3085
descripcion: "Agente LLM (Ollama + Claude fallback)"
- nombre: "trading-agents"
puerto: 3086
descripcion: "Agentes autonomos (Atlas, Orion, Nova)"
# ─────────────────────────────────────────────────────────────────────────────
# MÓDULOS
@ -114,39 +130,48 @@ modulos:
epicas:
- id: "OQI-001"
nombre: "fundamentos-auth"
estado: "70%"
estado: "85%"
nota: "Token rotation, 2FA, OAuth multi-provider completados"
- id: "OQI-002"
nombre: "educativo"
estado: "30%"
estado: "55%"
nota: "Courses, quizzes, gamification, video upload, E2E tests (153)"
- id: "OQI-003"
nombre: "trading-charts"
estado: "40%"
estado: "60%"
nota: "Panels, indicators, screener, drawing tools, ML overlays"
- id: "OQI-004"
nombre: "cuentas-inversion"
estado: "35%"
estado: "55%"
nota: "Account detail, wizard, risk analysis, portfolio optimizer"
- id: "OQI-005"
nombre: "pagos-stripe"
estado: "50%"
estado: "65%"
nota: "Stripe Elements, refunds, invoice preview"
- id: "OQI-006"
nombre: "senales-ml"
estado: "60%"
estado: "75%"
nota: "3-level pipeline, 12 attention models, backtesting framework"
- id: "OQI-007"
nombre: "llm-strategy-agent"
estado: "25%"
estado: "45%"
nota: "Error handling, connection status, token display, prompt library"
- id: "OQI-008"
nombre: "portfolio-manager"
estado: "20%"
estado: "45%"
nota: "Dashboard, allocations, goals, performance, WebSocket"
- id: "OQI-009"
nombre: "mt4-gateway"
estado: "15%"
nota: "NO FUNCIONAL - stubs only, gateway no implementado"
# ─────────────────────────────────────────────────────────────────────────────
# INTEGRACIONES EXTERNAS

View File

@ -1,85 +1,125 @@
# PROJECT STATUS - Trading Platform (trading-platform)
**Fecha:** 2026-01-07
**Estado:** MVP Funcional
**Fase:** 2 - Integracion y Testing (95%)
**Fecha:** 2026-01-27
**Estado:** Desarrollo Activo - Post MVP
**Completitud Global:** ~60%
---
## Resumen Ejecutivo
| Aspecto | Estado | Notas |
|---------|--------|-------|
| Database | Completado | 8 schemas, RLS configurado |
| Backend | Completado | Express.js + TypeScript |
| Frontend | Completado | React + Vite + TradingView |
| ML Engine | Completado | 3 modelos: AMD, Range, TPSL |
| LLM Agent | Completado | 17 tools, Llama 3 8B |
| Trading Agents | Completado | Atlas, Orion, Nova |
| MCP Server MT4 | Completado | 6 tools MCP |
| Tests | Pendiente | E2E por ejecutar |
| Aspecto | Estado | Completitud | Notas |
|---------|--------|-------------|-------|
| Database DDL | Completo | 95% | 10 schemas, 89 tablas, pgvector agregado |
| Seeds | Parcial | 70% | Symbols, products, tickers, admin creados |
| Backend API | Parcial | 48% | 113+ endpoints, ~50% implementados |
| Frontend SPA | Parcial | 65% | 189 components, services criticos faltantes |
| ML Engine | Funcional | 75% | 3-level pipeline, 12 attention models |
| Data Service | Incompleto | 20% | Solo estructura |
| LLM Agent | Parcial | 45% | Sin persistence layer |
| Trading Agents | Funcional | 75% | Atlas, Orion, Nova |
| Tests | Bajo | 15% | 153 E2E (video upload) |
| Documentacion | Alta | 85% | 280+ archivos, inventarios sync |
---
## Progreso por Epica
## Progreso por Epica (Actualizado 2026-01-27)
| Epica | Descripcion | Progreso |
|-------|-------------|----------|
| OQI-001 | Auth (OAuth, JWT, 2FA) | 100% |
| OQI-002 | Education Platform | 95% |
| OQI-003 | Trading Charts | 100% |
| OQI-004 | Trading Agents | 100% |
| OQI-005 | Stripe Integration | 95% |
| OQI-006 | ML Engine | 100% |
| OQI-007 | LLM Agent | 100% |
| Epica | Modulo | DDL | Backend | Frontend | ML | Total |
|-------|--------|-----|---------|----------|----|-------|
| OQI-001 | Auth | 100% | 90% | 70% | N/A | **85%** |
| OQI-002 | Education | 100% | 40% | 80% | N/A | **55%** |
| OQI-003 | Trading | 100% | 50% | 90% UI | N/A | **60%** |
| OQI-004 | Investment | 100% | 35% | 35% | N/A | **55%** |
| OQI-005 | Payments | 100% | 50% | 80% | N/A | **65%** |
| OQI-006 | ML Signals | 100% | 70% | 95% | 75% | **75%** |
| OQI-007 | LLM Agent | 100% | 40% | 45% | 60% | **45%** |
| OQI-008 | Portfolio | 100% | 45% | 0% | N/A | **45%** |
| OQI-009 | MT4 Gateway | 0% | 0% | 0% | N/A | **15%** |
---
## Servicios y Puertos
## Servicios y Puertos (Estandarizados 2026-01-27)
| Servicio | Puerto | Estado |
|----------|--------|--------|
| Frontend | 5173 | Activo |
| Backend | 3000 | Activo |
| ML Engine | 8001 | Activo |
| Data Service | 8002 | Pendiente |
| LLM Agent | 8003 | Activo |
| Trading Agents | 8004 | Activo |
| MT4 Gateway | 8005 | Activo |
| MCP Server MT4 | 3605 | Activo |
| PostgreSQL | 5432 | Activo |
| Redis | 6379 | Activo |
| Ollama | 11434 | Activo |
| Servicio | Puerto | Stack | Estado |
|----------|--------|-------|--------|
| Frontend | 3080 | React + Vite | Desarrollo |
| Backend API | 3081 | Express.js 5.0.1 | Desarrollo |
| WebSocket | 3082 | ws (Express) | Implementado |
| ML Engine | 3083 | FastAPI (Python) | Funcional |
| Data Service | 3084 | FastAPI (Python) | 20% |
| LLM Agent | 3085 | FastAPI (Python) | Parcial |
| Trading Agents | 3086 | FastAPI (Python) | Funcional |
| MCP Wallet | 3090 | TypeScript | Definido |
| MCP Products | 3091 | TypeScript | Definido |
| MCP VIP | 3092 | TypeScript | Definido |
| MCP Investment | 3093 | TypeScript | Definido |
| MCP Predictions | 3094 | TypeScript | Definido |
| MCP Auth | 3095 | TypeScript | Definido |
| PostgreSQL | 5432 | Nativo WSL | Activo |
| Redis | 6379 | Nativo WSL | Activo |
| Ollama | 11434 | Docker | Opcional |
---
## Modelos ML Implementados
| Modelo | Descripcion | Precision |
|--------|-------------|-----------|
| AMDDetector | Fases Accumulation/Manipulation/Distribution | ~75% |
| RangePredictor | Prediccion de rango High/Low | ~70% |
| TPSLClassifier | Clasificacion Take Profit/Stop Loss | ~68% |
| Modelo | Tipo | Framework | Precision | Estado |
|--------|------|-----------|-----------|--------|
| Attention (L0) | Filter | XGBoost | N/A | 12 modelos entrenados |
| RangePredictorV2 (L1) | Regression | XGBoost | R2: 0.48-0.55 | Entrenado |
| AMDDetectorML (L1) | Classification | XGBoost | Dir: 92%+ | Entrenado |
| MovementMagnitude (L1) | Regression | XGBoost | Functional | Entrenado |
| XGBoost Metamodel (L2) | Stacking | XGBoost | Default | Configurado |
| Neural Gating (L2) | Neural | PyTorch | XAUUSD only | Configurado |
---
## Proximas Acciones
## Credenciales BD (Estandarizadas)
1. Configurar EA Bridge en MT4 Terminals
2. Test de integracion MCP → MT4 Gateway
3. Generar datos para fine-tuning LLM
4. Testing E2E de integraciones
5. Deploy a produccion
```
Database: trading_platform
User: trading_user
Password: trading_dev_2026
Port: 5432
Host: localhost
Redis DB: 1
Schemas: auth, education, trading, investment, financial, portfolio, market_data, ml, llm, audit
```
---
## Riesgos
## Tareas Completadas (20)
| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Latencia MT4 Bridge | Media | Alto | Connection pooling |
| Overfitting modelos ML | Media | Alto | Walk-forward validation |
| Costo APIs LLM | Baja | Medio | Ollama local como default |
| Periodo | Completadas | Tipo |
|---------|-------------|------|
| 2026-01-27 | 3 (BLOCKER-001, E2E-VIDEO, MASTER-ANALYSIS) | Refactor, Testing, Analysis |
| 2026-01-26 | 3 (Integration Plan, LLM Panels, ML Panels) | Analysis, Feature x2 |
| 2026-01-25 | 14 (MVP, Notifications, ML Migration, etc) | Feature, Analysis, Docs |
---
## Blockers Activos
| ID | Descripcion | Impacto | Prioridad |
|----|-------------|---------|-----------|
| ~~B-001~~ | ~~trading.service.ts no existe en frontend~~ | RESUELTO - existe y funciona | ~~P0~~ |
| ~~B-002~~ | ~~auth.service.ts no existe en frontend~~ | RESUELTO - existe y funciona | ~~P0~~ |
| ~~B-003~~ | ~~Backend admin retorna mock data~~ | RESUELTO - wired to real DB | ~~P1~~ |
| B-004 | Frontend token key inconsistency (auth_token vs token) | Auth failures en 3 services | P1 RESUELTO |
| B-005 | OQI-009 MT4 Gateway 0% funcional | Feature no disponible | P2 |
| B-006 | Backend config defaults incorrectos (port, DB) | Conexion falla sin .env | P1 RESUELTO |
---
## Proximas Acciones (ver TASK-2026-01-27-MASTER-ANALYSIS-PLAN)
1. ~~Recrear BD en WSL con DDL + seeds actualizados~~ COMPLETADO (90 tablas, 10 schemas, pgvector)
2. ~~Implementar frontend service layers (auth, trading)~~ YA EXISTIAN (14 services)
3. ~~Backend admin wired to real DB~~ COMPLETADO
4. Ejecutar OOS backtesting (12 meses excluidos)
5. Implementar pages faltantes (portfolio, investment, settings)
6. Integration testing
---
@ -88,21 +128,10 @@
| Recurso | Especificacion | Uso |
|---------|----------------|-----|
| GPU | NVIDIA RTX 5060 Ti (16GB VRAM) | ML + LLM |
| CUDA | 13.0 | XGBoost, PyTorch |
| Modelo LLM | Llama 3 8B | ~10GB VRAM |
| CUDA | 13.0 | XGBoost GPU, PyTorch |
| Modelo LLM | Llama 3 8B | ~10GB VRAM via Ollama |
---
## Metricas
| Metrica | Objetivo | Actual |
|---------|----------|--------|
| Epicas completadas | 7 | 6.9 (98%) |
| Lineas de codigo | - | ~24,500 |
| Archivos de codigo | - | ~95 |
| Documentacion | 100% | 90% |
---
**Ultima actualizacion:** 2026-01-07
**Actualizado por:** Orquestador
**Ultima actualizacion:** 2026-01-27
**Actualizado por:** Claude Code (Opus 4.5) - Analisis Maestro

View File

@ -1,564 +1,100 @@
# Próxima Acción - Trading Platform (trading-platform)
# Proxima Accion - Trading Platform
## Estado Actual
- **Fecha:** 2026-01-04
- **Estado:** Integración MT4-MCP-LLM COMPLETADA
- **Fase:** Fase 2 - Integración y Testing (95% completado)
**Fecha:** 2026-01-27
**Referencia:** TASK-2026-01-27-MASTER-ANALYSIS-PLAN
**Estado:** Ejecucion Activa - Fases 0-2 Completadas
---
## COMPLETADO HOY (2026-01-04)
## COMPLETADO HOY (2026-01-27)
### Módulo Visualización ML (OQI-006) ✅
### Analisis Maestro Integral
- 8 subagentes en paralelo analizaron todas las capas
- 31 hallazgos documentados (7 criticos, 8 altos, 10 medios, 6 bajos)
- Plan jerarquico de 7 fases, 132+ items de trabajo
| Componente | Estado | Descripción |
|------------|--------|-------------|
| CandlestickChartWithML.tsx | ✅ Creado | Chart con overlays de ML (566 líneas) |
| Trading.tsx | ✅ Actualizado | Integración de chart ML con controles |
| ML Controls Dropdown | ✅ Creado | Panel de control para activar/desactivar capas ML |
### Fase 0 Ejecutada: Correcciones y Alineacion
- Password estandarizado a `trading_dev_2026` en 4 archivos + unified-recreate-db.sh
- PROJECT-PROFILE.yml actualizado (puertos 3083-3086, PyTorch/XGBoost, 10 schemas)
- CLAUDE.md proyecto actualizado (schemas, ML frameworks, OQI progress)
- trading-platform agregado a LOCAL-WSL-ENVIRONMENT.yml
- trading-platform agregado a SHARED-PLATFORM-CONFIG.yml
- WORKSPACE-INTEGRATION.yml actualizado
#### Características Implementadas
- **Líneas de Señal**: Entry, Stop Loss, Take Profit como líneas de precio
- **Rango Predicho**: Líneas punteadas para High/Low predicho
- **Fase AMD**: Badge indicador de Accumulation/Manipulation/Distribution
- **Marcadores de Señal**: Indicadores en velas con señales
- **Auto-refresh**: Actualización automática cada 30 segundos
- **Controles UI**: Checkboxes para activar/desactivar cada tipo de overlay
### Fase 1 Ejecutada: DDL + Seeds + BD
#### Preparado (No implementado aún)
- Order Blocks visualization
- Fair Value Gaps visualization
- WebSocket para tiempo real
**1.1 - DDL Fixes:**
- pgvector extension agregado a 00-extensions.sql
- Migration schema prefix corregido (auth.sessions)
- market_data schema agregado a 01-schemas.sql (faltaba)
- 2 tablas con core.users corregido a auth.users (education.videos, ml.backtest_runs)
**1.2 - Seeds Creados:**
- trading/01-symbols.sql (6 pares forex/crypto)
- investment/01-products.sql (Atlas, Orion, Nova)
- market_data/01-tickers.sql (6 tickers)
- auth/01-admin-user.sql (admin@orbiquant.com)
**1.3 - BD Recreada en WSL:**
- 90 tablas creadas en 10 schemas (auth:14, education:15, market_data:4, trading:10, financial:10, investment:9, portfolio:5, ml:11, llm:5, audit:7)
- 7 extensiones (uuid-ossp, pgcrypto, citext, unaccent, pg_trgm, plpgsql, vector/pgvector 0.8.1)
- 178 funciones
- Seeds validados: 6 symbols, 6 tickers, 3 products, 1 admin user
- Script dedicado creado: scripts/database/recreate-trading-platform.sh
### Fase 2 Ejecutada (Parcial): Backend Core
**Config Fixes:**
- config/index.ts defaults corregidos (DB: trading_platform, user: trading_user, port: 3081, CORS: 3080, Redis DB: 1)
- Admin endpoints reescritos con queries reales a BD (dashboard, users, audit, stats, health)
- DB health check real integrado en system/health endpoint
- User management (list/detail/status/role) con queries reales + JOIN user_profiles
**Frontend Token Fix:**
- 3 services corregidos: auth_token -> token (education, payment, notification)
- Token key ahora consistente en los 14 services
### Fase 6.1 Ejecutada: Purga Documentacion
- 5 reportes obsoletos eliminados de _archive/reportes/
- PROJECT-STATUS.md reescrito
- PROXIMA-ACCION.md actualizado
### Hallazgo Importante: Frontend Services Ya Existian
- Los 14 services frontend estaban implementados (auth, trading, portfolio, etc.)
- B-001 y B-002 eran falsos positivos - los archivos existian todo el tiempo
- El problema real era inconsistencia de token keys (auth_token vs token) - RESUELTO
---
### Módulo Education Frontend (OQI-002) ✅
## PROXIMA ACCION INMEDIATA
| Componente | Estado | Descripción |
|------------|--------|-------------|
| Lesson.tsx | ✅ Creado | Página de lección con video player, progreso, sidebar de curso |
| Quiz.tsx | ✅ Creado | Página de quiz con timer, preguntas, resultados XP |
| App.tsx | ✅ Actualizado | Rutas para /lesson/:lessonId y /quiz agregadas |
| Seeds Education | ✅ Creado | 1 curso ICT, 7 módulos, 28 lecciones, 5 quizzes |
### Fase 4: ML Backtesting (PRIORIDAD)
1. Parametrizar OOS dinamico (12 meses desde max fecha BD)
2. Ejecutar entrenamiento completo (6 symbols x 2 timeframes)
3. Ejecutar backtesting OOS y validar metricas (WR>=75%, PF>=2.0, Sharpe>=1.5)
#### Archivos Creados
- `apps/frontend/src/modules/education/pages/Lesson.tsx` (~450 líneas)
- Video player con controles (play/pause, seek, mute, fullscreen)
- Sidebar con outline del curso
- Tracking de progreso en tiempo real
- Navegación entre lecciones
- Soporte para contenido tipo: video, text, quiz, exercise
### Fase 2 Pendiente: Backend Completar
1. Crear entity interfaces TypeScript (10 archivos por schema)
2. Redis health check en admin/system/health
3. P&L calculation queries para dashboard
- `apps/frontend/src/modules/education/pages/Quiz.tsx` (~380 líneas)
- Estados: intro, in_progress, submitted
- Timer con tiempo límite
- Tipos de pregunta: multiple_choice, multiple_answer, short_answer
- Resultados con XP y feedback
- Opción de reintentar
### Fase 3 Pendiente: Frontend Polish
1. Error Boundaries globales
2. Migrar services restantes al apiClient centralizado (auto-refresh)
3. Verificar todas las rutas conectan correctamente
#### Rutas Agregadas
```
/education/courses/:courseSlug/lesson/:lessonId
/education/courses/:courseSlug/lesson/:lessonId/quiz
```
### Estado Verificado de Épicas
| Épica | Estado Real | Documentado | Notas |
|-------|-------------|-------------|-------|
| OQI-001 Auth | ✅ 100% | ✅ 100% | OAuth, JWT, 2FA completo |
| OQI-002 Education | ✅ 95% | 30% | Backend 100%, Frontend 95% (faltaban Lesson/Quiz) |
| OQI-003 Trading Charts | ✅ 100% | ✅ 100% | TradingView clone completo |
| OQI-004 Trading Agents | ✅ 100% | ✅ 100% | Atlas, Orion, Nova |
| OQI-005 Stripe | ✅ 95% | 30% | Backend 100%, Frontend 100%, falta testing |
| OQI-006 ML Engine | ✅ 100% | ✅ 100% | AMDDetector, RangePredictor, TPSLClassifier |
| OQI-007 LLM Agent | ✅ 100% | ✅ 100% | Copiloto con 17 tools |
### Integración MT4-MCP-LLM ✅
| Componente | Estado | Descripción |
|------------|--------|-------------|
| MCP Server MT4 | ✅ Completado | Servidor MCP con 6 tools para MT4 (puerto 3605) |
| MT4 Gateway | ✅ Completado | FastAPI service para comunicación con EA Bridge (puerto 8005) |
| Fine-tuning Pipeline | ✅ Completado | QLoRA para Llama 3 8B optimizado para 16GB VRAM |
| Strategy Analysis Tools | ✅ Completado | 5 herramientas para integración con Trading Agents |
| Strategy Prompts | ✅ Completado | System prompts especializados para análisis ICT/SMC |
#### MCP Server MT4 (`apps/mcp-mt4-connector/`)
- **6 MCP Tools**: mt4_get_account, mt4_get_positions, mt4_execute_trade, mt4_close_position, mt4_modify_position, mt4_get_quote
- Puerto: 3605
- Arquitectura: TypeScript + Express.js + @modelcontextprotocol/sdk
- Documentación: ARCHITECTURE.md, MCP-TOOLS-SPEC.md
#### MT4 Gateway (`apps/mt4-gateway/`)
- Endpoints FastAPI para MT4 Bridge
- Configuración Pydantic para EA Bridge
- Puerto: 8005
- Integración con EA Bridge (puertos 8081-8083)
#### Fine-tuning Pipeline (`apps/llm-agent/fine-tuning/`)
```
fine-tuning/
├── config/training_config.yaml # QLoRA config (4-bit, LoRA rank 16)
├── scripts/
│ ├── prepare_dataset.py # Convierte SignalLogger → JSONL
│ ├── train_lora.py # Entrenamiento QLoRA
│ └── evaluate_model.py # Evaluación + métricas trading
├── prompts/
│ └── training_examples.jsonl # 10 ejemplos de entrenamiento
└── README.md # Guía completa
```
#### Strategy Analysis Tools (`apps/llm-agent/src/tools/strategy_analysis.py`)
- GetAgentPerformanceTool: Métricas de Atlas/Orion/Nova
- CompareAgentsTool: Comparación multi-agente
- RecommendStrategyTool: Recomendación según perfil de riesgo
- GetBacktestResultsTool: Resultados históricos
- AnalyzeTradeDecisionTool: Análisis de trades vs reglas del agente
### Fase 5: Integration Testing
1. Backend API tests
2. Frontend E2E tests
3. ML integration tests
---
## COMPLETADO ANTERIORMENTE (2025-12-08)
## PLAN COMPLETO
### OQI-003 Trading y Charts ✅
| Componente | Estado | Descripción |
|------------|--------|-------------|
| TradingView Charts | ✅ Completado | Lightweight Charts v4, velas japonesas, volumen |
| ChartToolbar | ✅ Completado | Selector símbolos, timeframes, indicadores |
| WatchlistSidebar | ✅ Completado | Lista símbolos con precios en tiempo real |
| PaperTradingPanel | ✅ Completado | Órdenes, posiciones, historial |
| WebSocket Server | ✅ Completado | Real-time price updates via Binance |
| Trading Store | ✅ Completado | Zustand store con todas las acciones |
### OQI-006 ML Engine - Migración Avanzada ✅
| Componente | Estado | Descripción |
|------------|--------|-------------|
| AMDDetector | ✅ Completado | Detección fases Accumulation/Manipulation/Distribution |
| AMDModels | ✅ Completado | 3 redes neuronales especializadas + Ensemble |
| Phase2Pipeline | ✅ Completado | Pipeline completo de entrenamiento |
| WalkForward | ✅ Completado | Validación walk-forward anti-overfitting |
| Backtesting | ✅ Completado | Engine + Metrics + RR Backtester |
| SignalLogger | ✅ Completado | Generador datos para LLM fine-tuning |
| API Endpoints | ✅ Completado | /amd, /backtest, /train, /ws/signals |
| GPU Training | ✅ Completado | XGBoost CUDA (RTX 5060 Ti) |
### OQI-007 LLM Service - Copiloto Trading ✅
| Componente | Estado | Descripción |
|------------|--------|-------------|
| OllamaClient | ✅ Completado | Cliente LLM local con GPU |
| ClaudeClient | ✅ Completado | Fallback a API Anthropic |
| Trading Tools | ✅ Completado | 12 tools implementados |
| System Prompt | ✅ Completado | 1,500+ líneas especializado en trading |
| Context Manager | ✅ Completado | Gestión de conversaciones |
| API REST | ✅ Completado | 8 endpoints + streaming SSE |
| Docker Setup | ✅ Completado | Ollama + GPU en contenedor |
### OQI-004 Trading Agents ✅
| Agente | Estado | Estrategias |
|--------|--------|-------------|
| Atlas | ✅ Completado | Mean Reversion, Grid Trading |
| Orion | ✅ Completado | Trend Following, Momentum |
| Nova | ✅ Completado | Momentum, Scalping |
| RiskManager | ✅ Completado | Position sizing, drawdown control |
| BinanceClient | ✅ Completado | Testnet + Mainnet ready |
| MLSignalConsumer | ✅ Completado | Consumo de señales ML |
| API REST | ✅ Completado | 11 endpoints de control |
Ver: `orchestration/tareas/TASK-2026-01-27-MASTER-ANALYSIS-PLAN/03-PLAN-MAESTRO-JERARQUICO.md`
---
## Resumen de Desarrollo Paralelo
### Tracks Completados
| Track | Agente | Archivos | Líneas Código |
|-------|--------|----------|---------------|
| A | Web Platform | ~20 | ~5,000 |
| B | ML Engine | 24 | ~8,000 |
| C | LLM Agent | 20 | ~5,000 |
| D | Trading Agents | 31 | ~6,500 |
| **Total** | | **~95** | **~24,500** |
---
## Infraestructura de Servicios
Ver: `SERVICES.md` para arquitectura completa.
### Puertos de Desarrollo
| Servicio | Puerto | Estado |
|----------|--------|--------|
| Frontend | 5173 | ✅ |
| Backend | 3000 | ✅ |
| ML Engine | 8001 | ✅ |
| Data Service | 8002 | ⏳ |
| LLM Agent | 8003 | ✅ |
| Trading Agents | 8004 | ✅ |
| MT4 Gateway | 8005 | ✅ |
| MCP Server MT4 | 3605 | ✅ |
| EA Bridge #1 | 8081 | ⏳ (MT4 Terminal) |
| EA Bridge #2 | 8082 | ⏳ (MT4 Terminal) |
| EA Bridge #3 | 8083 | ⏳ (MT4 Terminal) |
| PostgreSQL | 5432 | ✅ |
| Redis | 6379 | ✅ |
| Ollama | 11434 | ✅ |
---
## Próximas Tareas Prioritarias
### Inmediatas (Esta semana)
1. **Instalar dependencias MCP Server MT4**
```bash
cd apps/mcp-mt4-connector
npm install
npm run build
```
2. **Configurar EA Bridge en MT4 Terminals**
- Instalar Expert Advisor "Trading Platform Bridge" en cada terminal
- Configurar puertos 8081, 8082, 8083 según broker
- Habilitar WebRequest y AutoTrading
3. **Instalar dependencias Fine-tuning**
```bash
cd apps/llm-agent/fine-tuning
pip install -r requirements.txt
```
4. **Test de conexión MCP → MT4 Gateway → EA Bridge**
```bash
# Iniciar MT4 Gateway
cd apps/mt4-gateway
uvicorn src.main:app --reload --port 8005
# Iniciar MCP Server
cd apps/mcp-mt4-connector
npm start
```
5. **Generar datos de entrenamiento para Fine-tuning**
```bash
cd apps/llm-agent/fine-tuning
python scripts/prepare_dataset.py --generate-synthetic 100 --output data/processed/
```
### Anteriores (Completadas)
6. ~~Descargar modelo Llama 3 8B en Ollama~~
7. ~~Probar paper trading en Binance Testnet~~
8. ~~Test de integración ML Engine → Trading Agents~~
9. ~~Test de integración LLM Agent → ML Engine~~
### Completado (2025-12-08)
5. **Integración Frontend ↔ LLM Agent (Chat UI)**
- ChatMessage, ChatInput, SignalCard componentes
- Assistant.tsx página principal
- Navegación agregada en MainLayout
6. **Integración Frontend ↔ ML Engine (Señales)**
- mlService.ts - cliente API ML Engine
- MLSignalsPanel componente con AMD, Range Prediction
- Integración en Trading.tsx
7. **Scripts de Operación**
- `scripts/start-all.sh` - Inicio de todos los servicios
- `scripts/stop-all.sh` - Detención de servicios
- `scripts/setup-ollama.sh` - Configuración de Ollama + Llama 3
- `scripts/test_integration.py` - Tests de integración entre servicios
8. **Configuración Backend**
- `LLM_AGENT_URL` agregado a .env
- `TRADING_AGENTS_URL` agregado a .env
- ChatWidget integrado via backend proxy
### Siguientes (Próxima semana)
9. ~~**Módulo Education (OQI-002)**~~ ✅ Completado (2026-01-04)
10. ~~**Integración Stripe (OQI-005)**~~ ✅ Ya estaba completado
11. **Entrenamiento de modelos ML con datos reales**
12. **Testing E2E de integraciones**
13. ~~**Seeds de datos de ejemplo para Education**~~ ✅ Completado (2026-01-04)
14. **Deploy a producción**
### Issues Resueltos (2026-01-04) ✅
| Issue | Solución | Estado |
|-------|----------|--------|
| DDL Loader no carga `00-extensions.sql` | Agregada verificación y carga antes de enums | ✅ Resuelto |
| DDL Loader busca solo `00-enums.sql` | Búsqueda en `00-enums.sql` y `01-enums.sql` | ✅ Resuelto |
| Inconsistencia nombre BD | Defaults unificados: `trading_platform`, puerto `5433` | ✅ Resuelto |
| Constraint circular `auth.users` | Removido (PostgreSQL no soporta subqueries en CHECK) | ✅ Resuelto |
| Seeds education columnas incorrectas | Corregidas 28 lecciones, 5 quizzes, 14 preguntas | ✅ Resuelto |
#### Archivos Modificados
- `apps/database/scripts/create-database.sh` - DDL loader corregido
- `apps/database/ddl/schemas/auth/tables/01-users.sql` - Constraint removido
- `apps/database/ddl/schemas/auth/tables/99-deferred-constraints.sql` - Documentación (nuevo)
- `apps/database/seeds/prod/education/01-education-courses.sql` - Columnas corregidas
#### Comando de Recreación (Validado)
```bash
# Ahora funciona con defaults correctos
DB_PORT=5433 ./drop-and-recreate-database.sh
# O con todas las variables explícitas
DB_NAME=trading_platform DB_USER=trading DB_PASSWORD=trading_dev_2025 DB_PORT=5433 ./drop-and-recreate-database.sh
```
#### Validación Final
```
Categories: 5 ✓
Courses: 1 ✓
Modules: 7 ✓
Lessons: 28 ✓
Quizzes: 5 ✓
Questions: 14 ✓
```
---
## Comandos para Iniciar
### Servicios Python (ML/LLM/Trading)
```bash
# Terminal 1 - Ollama (LLM)
docker-compose -f apps/llm-agent/docker-compose.ollama.yml up -d
docker exec trading-ollama ollama pull llama3:8b
# Terminal 2 - ML Engine (puerto 8001)
cd apps/ml-engine
pip install -r requirements.txt
uvicorn src.api.main:app --reload --port 8001
# Terminal 3 - LLM Agent (puerto 8003)
cd apps/llm-agent
pip install -r requirements.txt
uvicorn src.main:app --reload --port 8003
# Terminal 4 - Trading Agents (puerto 8004)
cd apps/trading-agents
pip install -r requirements.txt
uvicorn src.api.main:app --reload --port 8004
```
### Servicios Node.js
```bash
# Terminal 5 - Backend (puerto 3000)
cd apps/backend && npm install && npm run dev
# Terminal 6 - Frontend (puerto 5173)
cd apps/frontend && npm install && npm run dev
```
### Docker Compose (Todo junto)
```bash
docker-compose -f docker-compose.services.yml up -d
```
---
## Estructura Final del Proyecto
```
apps/
├── database/schemas/ # 8 archivos SQL
├── ml-engine/ # ML Models + FastAPI (OQI-006) ✅
│ ├── src/models/ # AMDDetector, RangePredictor, TPSLClassifier
│ ├── src/pipelines/ # Phase2Pipeline
│ ├── src/training/ # Walk-forward
│ ├── src/backtesting/ # Engine + Metrics + RR
│ └── src/api/ # FastAPI endpoints
├── llm-agent/ # LLM Copilot (OQI-007) ✅
│ ├── src/core/ # LLM Client, Prompts, Context
│ ├── src/tools/ # 17 Trading Tools (12 + 5 Strategy)
│ ├── src/prompts/ # System prompts + templates
│ ├── src/api/ # FastAPI REST
│ └── fine-tuning/ # QLoRA Pipeline (NUEVO) ✅
│ ├── config/ # training_config.yaml
│ ├── scripts/ # prepare_dataset, train_lora, evaluate
│ ├── prompts/ # training_examples.jsonl
│ └── data/ # raw + processed
├── trading-agents/ # Agentes IA (OQI-004) ✅
│ ├── src/agents/ # Atlas, Orion, Nova
│ ├── src/strategies/ # Mean Reversion, Trend, Grid, Momentum
│ ├── src/exchange/ # Binance Client
│ └── config/ # YAML configs
├── mt4-gateway/ # MT4 Bridge FastAPI (NUEVO) ✅
│ ├── src/api/ # routes.py, endpoints MT4
│ ├── src/config.py # Pydantic settings
│ └── src/providers/ # mt4_bridge_client.py
├── mcp-mt4-connector/ # MCP Server MT4 (NUEVO) ✅
│ ├── src/index.ts # Express server
│ ├── src/services/ # mt4-client.ts
│ ├── src/tools/ # 6 MCP tools
│ └── docs/ # ARCHITECTURE.md, MCP-TOOLS-SPEC.md
├── backend/ # Express.js API ✅
└── frontend/ # React + Trading Charts ✅
```
---
## Documentación
| Documento | Ubicación |
|-----------|-----------|
| Arquitectura MT4-MCP-LLM | `docs/01-arquitectura/ARQUITECTURA-INTEGRACION-MT4-MCP-LLM.md` |
| Integración MetaTrader4 | `docs/01-arquitectura/INTEGRACION-METATRADER4.md` |
| MCP Server Architecture | `apps/mcp-mt4-connector/docs/ARCHITECTURE.md` |
| MCP Tools Spec | `apps/mcp-mt4-connector/docs/MCP-TOOLS-SPEC.md` |
| Fine-tuning Guide | `apps/llm-agent/fine-tuning/README.md` |
| Servicios y Puertos | `SERVICES.md` |
| Plan ML/LLM/Trading | `orchestration/planes/PLAN-ML-LLM-TRADING.md` |
| Reporte de Sesión | `orchestration/reportes/REPORTE-SESION-2025-12-07.md` |
| Paper Trading Guide | `apps/trading-agents/PAPER_TRADING_GUIDE.md` |
| LLM Deployment | `apps/llm-agent/DEPLOYMENT.md` |
| ML Migration Report | `apps/ml-engine/MIGRATION_REPORT.md` |
---
## Recursos del Sistema
| Recurso | Especificación | Uso |
|---------|----------------|-----|
| GPU | NVIDIA RTX 5060 Ti (16GB VRAM) | ML + LLM |
| CUDA | 13.0 | XGBoost, PyTorch |
| Modelo LLM | Llama 3 8B | ~10GB VRAM |
---
*Actualizado: 2026-01-04 (Sesión 2)*
*Tech Leader: Agente Orquestador*
*Database: Validada y funcionando correctamente*
---
## Archivos Creados (2026-01-04)
### MCP Server MT4 (`apps/mcp-mt4-connector/`)
| Archivo | Descripción |
|---------|-------------|
| `package.json` | Configuración npm con dependencias MCP |
| `tsconfig.json` | Configuración TypeScript |
| `src/index.ts` | Express server en puerto 3605 |
| `src/services/mt4-client.ts` | Cliente HTTP para MT4 Gateway |
| `src/tools/account.ts` | Tool: mt4_get_account |
| `src/tools/positions.ts` | Tools: mt4_get_positions, mt4_close_position |
| `src/tools/trading.ts` | Tools: mt4_execute_trade, mt4_modify_position |
| `src/tools/quotes.ts` | Tool: mt4_get_quote |
| `src/tools/index.ts` | Registry de tools |
| `docs/ARCHITECTURE.md` | Documentación de arquitectura |
| `docs/MCP-TOOLS-SPEC.md` | Especificación de tools |
### MT4 Gateway (`apps/mt4-gateway/src/`)
| Archivo | Descripción |
|---------|-------------|
| `config.py` | Pydantic settings para MT4 Bridge |
| `api/__init__.py` | Módulo API |
| `api/routes.py` | FastAPI endpoints MT4 |
| `main.py` | Modificado para puerto 8005 |
### Fine-tuning Pipeline (`apps/llm-agent/fine-tuning/`)
| Archivo | Descripción |
|---------|-------------|
| `README.md` | Guía completa de fine-tuning QLoRA |
| `requirements.txt` | Dependencias (transformers, peft, bitsandbytes) |
| `config/training_config.yaml` | Configuración QLoRA para 16GB VRAM |
| `scripts/prepare_dataset.py` | Convierte SignalLogger → JSONL |
| `scripts/train_lora.py` | Script de entrenamiento QLoRA |
| `scripts/evaluate_model.py` | Evaluación del modelo |
| `prompts/training_examples.jsonl` | 10 ejemplos de entrenamiento |
### Strategy Analysis Tools (`apps/llm-agent/src/`)
| Archivo | Descripción |
|---------|-------------|
| `tools/strategy_analysis.py` | 5 tools para Trading Agents |
| `prompts/strategy_analysis.py` | Prompts y templates ICT/SMC |
| `tools/base.py` | Agregado ToolResult class |
| `tools/__init__.py` | Actualizado exports |
---
## Archivos Creados Anteriormente (2025-12-08)
### Frontend - Chat UI
| Archivo | Descripción |
|---------|-------------|
| `src/modules/assistant/pages/Assistant.tsx` | Página principal del chat |
| `src/modules/assistant/components/ChatMessage.tsx` | Componente de mensajes |
| `src/modules/assistant/components/ChatInput.tsx` | Input con quick actions |
| `src/modules/assistant/components/SignalCard.tsx` | Tarjeta de señales trading |
| `src/services/mlService.ts` | Cliente API ML Engine |
| `src/modules/trading/components/MLSignalsPanel.tsx` | Panel señales ML |
| `.env` y `.env.example` | Variables de entorno |
### Scripts de Operación
| Script | Descripción |
|--------|-------------|
| `scripts/start-all.sh` | Inicia todos los servicios (tmux/docker) |
| `scripts/stop-all.sh` | Detiene todos los servicios |
| `scripts/setup-ollama.sh` | Configura Ollama con Llama 3 8B |
| `scripts/test_integration.py` | Tests de integración entre servicios |
### Modificaciones
| Archivo | Cambio |
|---------|--------|
| `src/App.tsx` | Agregada ruta /assistant |
| `src/components/layout/MainLayout.tsx` | Agregado enlace AI Assistant |
| `src/modules/trading/pages/Trading.tsx` | Integrado MLSignalsPanel |
| `scripts/README.md` | Documentación actualizada |
---
## Archivos Creados (2026-01-04) - Sesión 2
### Visualización ML (`apps/frontend/src/modules/trading/`)
| Archivo | Descripción | Líneas |
|---------|-------------|--------|
| `components/CandlestickChartWithML.tsx` | Chart con overlays de predicciones ML | ~566 |
### Education Frontend (`apps/frontend/src/modules/education/pages/`)
| Archivo | Descripción | Líneas |
|---------|-------------|--------|
| `Lesson.tsx` | Página de lección con video player | ~450 |
| `Quiz.tsx` | Página de quiz interactivo | ~380 |
### Education Seeds (`apps/database/seeds/prod/education/`)
| Archivo | Descripción |
|---------|-------------|
| `01-education-courses.sql` | Curso ICT completo: 7 módulos, 28 lecciones, 5 quizzes |
### Modificaciones (2026-01-04 - Sesión 1)
| Archivo | Cambio |
|---------|--------|
| `apps/frontend/src/App.tsx` | Rutas para Lesson y Quiz, import CandlestickChartWithML |
| `apps/frontend/src/modules/trading/pages/Trading.tsx` | Integración ML overlays, dropdown de controles |
| `apps/frontend/src/types/education.types.ts` | Props xpReward, maxScore, xpAwarded añadidas |
| `docs/02-definicion-modulos/OQI-002-education/implementacion/TRACEABILITY.yml` | Documentación de implementación |
| `docs/02-definicion-modulos/OQI-006-ml-signals/implementacion/TRACEABILITY.yml` | Documentación de implementación |
---
## Archivos Modificados (2026-01-04 - Sesión 2)
### Database Scripts
| Archivo | Cambio |
|---------|--------|
| `apps/database/scripts/create-database.sh` | DDL loader: extensiones, enums flexibles, defaults unificados |
| `apps/database/scripts/drop-and-recreate-database.sh` | Ya usa create-database.sh (sin cambios necesarios) |
### Database DDL
| Archivo | Cambio |
|---------|--------|
| `apps/database/ddl/schemas/auth/tables/01-users.sql` | Removido constraint password_or_oauth |
| `apps/database/ddl/schemas/auth/tables/99-deferred-constraints.sql` | **NUEVO** - Documentación de constraint diferido |
### Database Seeds
| Archivo | Cambio |
|---------|--------|
| `apps/database/seeds/prod/education/01-education-courses.sql` | Corregidas columnas: lessons (9 cols), quizzes, questions |
### Documentación
| Archivo | Cambio |
|---------|--------|
| `docs/02-definicion-modulos/OQI-002-education/implementacion/TRACEABILITY.yml` | Agregada sesión 2 con fixes de BD |
| `orchestration/PROXIMA-ACCION.md` | Issues resueltos, archivos modificados |
**Actualizado:** 2026-01-27
**Agente:** Claude Code (Opus 4.5)

View File

@ -1,243 +0,0 @@
# Reporte de Ejecucion Sprint 1
## Trading Platform - ML Engine Stabilization
**Fecha:** 2026-01-07
**Sprint:** 1 - Estabilizacion ML Engine
**Estado:** EN PROGRESO (Implementacion Completada, Pendiente Reentrenamiento)
**Ejecutor:** Claude Opus 4.5 (Technical Lead / ML-SPECIALIST)
---
## 1. RESUMEN EJECUTIVO
### 1.1 Objetivo del Sprint
Resolver los problemas criticos del ML Engine, especificamente el R^2 negativo en RangePredictor.
### 1.2 Estado de Tareas
| ID | Tarea | Estado | Cambios Realizados |
|----|-------|--------|-------------------|
| S1-T1 | Analizar features RangePredictor | COMPLETADO | Reporte creado |
| S1-T2 | Implementar normalizacion ATR | COMPLETADO | Codigo modificado |
| S1-T3 | Verificar data leakage | COMPLETADO | Verificado - OK |
| S1-T4a | Reducir sample weighting | COMPLETADO | Parametros ajustados |
| S1-T4b | Ajustar hiperparametros | COMPLETADO | XGBoost optimizado |
| S1-T5 | Auto-load modelos API | COMPLETADO | Servicio mejorado |
| S1-T6 | Reentrenar modelos | PENDIENTE | Requiere datos |
| S1-T7 | Validacion OOS | PENDIENTE | Post-reentrenamiento |
| S1-T8 | Tests unitarios | PENDIENTE | Proxima tarea |
---
## 2. CAMBIOS IMPLEMENTADOS
### 2.1 Normalizacion de Targets por ATR
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
**Cambios:**
1. **Nuevo metodo `_compute_atr()`** (lineas 426-460)
- Calcula ATR con `shift(1)` para evitar data leakage
- Periodo configurable (default: 14)
```python
def _compute_atr(self, df: pd.DataFrame, period: int = 14) -> np.ndarray:
"""Compute ATR with shift(1) to avoid data leakage."""
# True Range calculation
tr1 = high - low
tr2 = abs(high - close.shift(1))
tr3 = abs(low - close.shift(1))
true_range = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
atr = true_range.rolling(period).mean().shift(1)
return atr.values
```
2. **Modificacion de `_compute_targets()`** (lineas 462-534)
- Ahora acepta parametro `normalize=True`
- Retorna targets normalizados por ATR
- Clip de valores extremos (±5 ATR)
```python
# Antes: target en USD (ej: 0.0005 para GBPUSD)
# Ahora: target en ATR multiples (ej: 1.2 ATR)
target_high_norm = target_high / atr_safe
target_low_norm = target_low / atr_safe
```
**Beneficio:** Targets ahora estan en escala [-5, 5] en lugar de [0, 0.001]
---
### 2.2 Reduccion de Agresividad de Sample Weighting
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
**Cambios en TrainerConfig** (lineas 124-128):
| Parametro | Valor Anterior | Valor Nuevo | Razon |
|-----------|---------------|-------------|-------|
| `softplus_beta` | 4.0 | 2.0 | Menos agresivo |
| `softplus_w_max` | 3.0 | 2.0 | Cap mas bajo |
**Beneficio:**
- Mas samples incluidos en entrenamiento
- Menor sesgo hacia movimientos extremos
- Mejor generalizacion
---
### 2.3 Optimizacion de Hiperparametros XGBoost
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
**Cambios en xgb_params** (lineas 109-122):
| Parametro | Anterior | Nuevo | Efecto |
|-----------|----------|-------|--------|
| `n_estimators` | 300 | 150 | Menos overfitting |
| `max_depth` | 6 | 4 | Arboles mas simples |
| `learning_rate` | 0.03 | 0.02 | Aprendizaje mas lento |
| `subsample` | 0.8 | 0.7 | Mas regularizacion |
| `colsample_bytree` | 0.8 | 0.7 | Menos features |
| `min_child_weight` | 10 | 20 | Hojas mas grandes |
| `gamma` | 0.1 | 0.3 | Mas poda |
| `reg_alpha` | 0.1 | 0.5 | L1 mas fuerte |
| `reg_lambda` | 1.0 | 5.0 | L2 mas fuerte |
**Beneficio:** Modelo mas robusto, menos propenso a overfitting
---
### 2.4 Mejora de Auto-Load de Modelos
**Archivo:** `apps/ml-engine/src/services/prediction_service.py`
**Cambios en `_load_symbol_trainers()`** (lineas 200-282):
1. **Busqueda en multiples directorios:**
- `models/symbol_timeframe_models/` (prioridad 1 - nuevos modelos)
- `models/ml_first/` (prioridad 2 - modelos legacy)
2. **Soporte para estructura plana y jerarquica:**
- Detecta automaticamente el tipo de estructura
- Carga metadata si existe
3. **Logging mejorado:**
- Indica de donde se cargaron los modelos
- Warnings si no hay modelos disponibles
**Beneficio:** API carga modelos automaticamente al iniciar
---
### 2.5 Actualizacion del Script de Entrenamiento
**Archivo:** `apps/ml-engine/scripts/train_symbol_timeframe_models.py`
**Cambios** (lineas 374-408):
- Parametros actualizados para consistencia
- Comentarios explicativos de las mejoras
---
## 3. ARCHIVOS MODIFICADOS
| Archivo | Lineas Modificadas | Tipo de Cambio |
|---------|-------------------|----------------|
| `src/training/symbol_timeframe_trainer.py` | ~150 lineas | Mejoras mayores |
| `src/services/prediction_service.py` | ~80 lineas | Mejora de carga |
| `scripts/train_symbol_timeframe_models.py` | ~40 lineas | Sincronizacion |
---
## 4. DOCUMENTACION CREADA
| Documento | Ubicacion | Proposito |
|-----------|-----------|-----------|
| REPORTE-ANALISIS-RANGEPREDICTOR-2026-01-07.md | orchestration/reportes/ | Root cause analysis |
| REPORTE-EJECUCION-SPRINT1-2026-01-07.md | orchestration/reportes/ | Este reporte |
---
## 5. PROXIMOS PASOS
### 5.1 Reentrenamiento de Modelos (S1-T6)
Para reentrenar los modelos con las nuevas correcciones:
```bash
cd /home/isem/workspace-v1/projects/trading-platform/apps/ml-engine
python scripts/train_symbol_timeframe_models.py \
--symbols XAUUSD,EURUSD,GBPUSD,BTCUSD \
--timeframes 5m,15m \
--use-attention
```
**Requisitos:**
- Base de datos MySQL con datos historicos
- Configuracion de conexion en `data_config.yaml`
### 5.2 Validacion OOS (S1-T7)
Despues del reentrenamiento, validar:
```bash
# Verificar metricas
python scripts/evaluate_models.py --holdout-only
# Criterios de exito:
# - R^2 > 0.05 (minimo aceptable)
# - R^2 > 0.15 (objetivo)
```
### 5.3 Tests Unitarios (S1-T8)
Crear tests para:
- Normalizacion de targets
- Calculo de ATR con shift
- Sample weighting
- Prediccion con modelos cargados
---
## 6. RIESGOS Y MITIGACION
| Riesgo | Estado | Mitigacion |
|--------|--------|-----------|
| R^2 sigue negativo | Pendiente verificacion | Plan B: modelo baseline |
| Datos no disponibles | Posible | Mock data para tests |
| Integracion con API | Mitigado | Auto-load implementado |
---
## 7. METRICAS ESPERADAS POST-REENTRENAMIENTO
| Metrica | Valor Actual | Minimo | Objetivo |
|---------|--------------|--------|----------|
| RangePredictor R^2 | -0.65 | > 0.05 | > 0.15 |
| MAE (ATR normalizado) | N/A | < 0.5 | < 0.3 |
| Direction Accuracy | 98% | > 60% | > 65% |
| Win Rate Backtest | 42% | > 50% | > 55% |
---
## 8. CONCLUSION
Sprint 1 ha completado la implementacion de todas las correcciones identificadas:
1. **Normalizacion de targets** - Implementada con ATR shift(1)
2. **Sample weighting** - Reducida agresividad
3. **Hiperparametros** - Optimizados para regularizacion
4. **Auto-load** - Mejorado para multiples directorios
**Estado:** LISTO PARA REENTRENAMIENTO
El siguiente paso critico es ejecutar el reentrenamiento y validar que R^2 sea positivo.
---
**Reporte generado:** 2026-01-07
**Autor:** Claude Opus 4.5 (Technical Lead)
**Siguiente paso:** Ejecutar reentrenamiento de modelos

View File

@ -1,267 +0,0 @@
# Reporte de Ejecucion Sprint 2
## Trading Platform - Backend Integration
**Fecha:** 2026-01-07
**Sprint:** 2 - Integracion Backend
**Estado:** COMPLETADO
**Ejecutor:** Claude Opus 4.5 (Technical Lead)
---
## 1. RESUMEN EJECUTIVO
### 1.1 Objetivo del Sprint
Completar servicios de integracion backend y seguridad basica.
### 1.2 Estado de Tareas
| ID | Tarea | Estado | Notas |
|----|-------|--------|-------|
| S2-T1 | ml-integration.service.ts | COMPLETADO | Ya estaba implementado correctamente |
| S2-T2 | Auth paper trading | COMPLETADO | 13 rutas protegidas |
| S2-T3 | Auth investment | COMPLETADO | 10 rutas protegidas |
| S2-T4 | agents.service.ts | COMPLETADO | Ya estaba implementado correctamente |
| S2-T5 | Users module | COMPLETADO | Controller y routes implementados |
| S2-T6 | Tests integracion | PENDIENTE | Requiere infraestructura de test |
---
## 2. HALLAZGOS PREVIOS A IMPLEMENTACION
Durante la exploracion del backend se encontro que:
### 2.1 Servicios Ya Implementados
| Servicio | Estado | Calidad |
|----------|--------|---------|
| `ml-integration.service.ts` | Completo | Alta - 800+ LOC |
| `agents.service.ts` | Completo | Alta - Integracion con trading-agents |
| Auth Guards | Completo | Alta - RBAC, JWT, 2FA |
| Auth Middleware | Completo | Alta - OAuth, Email verification |
### 2.2 Gaps Identificados
| Gap | Prioridad | Resuelto |
|-----|-----------|----------|
| Paper trading sin auth | ALTA | SI |
| Investment sin auth | ALTA | SI |
| Users module vacio | MEDIA | SI |
---
## 3. CAMBIOS IMPLEMENTADOS
### 3.1 Trading Routes - Autenticacion
**Archivo:** `apps/backend/src/modules/trading/trading.routes.ts`
**Rutas Protegidas (13 endpoints):**
| Metodo | Ruta | Middleware |
|--------|------|------------|
| POST | `/paper/initialize` | requireAuth |
| GET | `/paper/balances` | requireAuth |
| POST | `/paper/orders` | requireAuth |
| DELETE | `/paper/orders/:orderId` | requireAuth |
| GET | `/paper/orders` | requireAuth |
| GET | `/paper/positions` | requireAuth |
| POST | `/paper/positions/:positionId/close` | requireAuth |
| GET | `/paper/trades` | requireAuth |
| GET | `/paper/portfolio` | requireAuth |
| POST | `/paper/reset` | requireAuth |
| GET | `/paper/settings` | requireAuth |
| PATCH | `/paper/settings` | requireAuth |
| GET | `/paper/stats` | requireAuth |
**Watchlist Routes (10 endpoints):**
| Metodo | Ruta | Middleware |
|--------|------|------------|
| GET | `/watchlists` | requireAuth |
| GET | `/watchlists/default` | requireAuth |
| GET | `/watchlists/:watchlistId` | requireAuth |
| POST | `/watchlists` | requireAuth |
| PATCH | `/watchlists/:watchlistId` | requireAuth |
| DELETE | `/watchlists/:watchlistId` | requireAuth |
| POST | `/watchlists/:watchlistId/symbols` | requireAuth |
| PATCH | `/watchlists/:watchlistId/symbols/:symbol` | requireAuth |
| DELETE | `/watchlists/:watchlistId/symbols/:symbol` | requireAuth |
| POST | `/watchlists/:watchlistId/reorder` | requireAuth |
---
### 3.2 Investment Routes - Autenticacion
**Archivo:** `apps/backend/src/modules/investment/investment.routes.ts`
**Cambios:**
1. Agregado import de `requireAuth`
2. Aplicado middleware a todas las rutas autenticadas
**Rutas Protegidas (10 endpoints):**
| Metodo | Ruta | Middleware |
|--------|------|------------|
| GET | `/accounts` | requireAuth |
| GET | `/accounts/summary` | requireAuth |
| POST | `/accounts` | requireAuth |
| GET | `/accounts/:accountId` | requireAuth |
| POST | `/accounts/:accountId/close` | requireAuth |
| GET | `/accounts/:accountId/transactions` | requireAuth |
| POST | `/accounts/:accountId/deposit` | requireAuth |
| POST | `/accounts/:accountId/withdraw` | requireAuth |
| GET | `/accounts/:accountId/distributions` | requireAuth |
| GET | `/withdrawals` | requireAuth |
---
### 3.3 Users Module - Implementacion Completa
**Archivos Creados/Modificados:**
1. `apps/backend/src/modules/users/controllers/users.controller.ts` (NUEVO)
2. `apps/backend/src/modules/users/users.routes.ts` (ACTUALIZADO)
**Funcionalidades Implementadas:**
| Funcion | Descripcion | Auth |
|---------|-------------|------|
| `getCurrentUser` | Obtener perfil del usuario actual | requireAuth |
| `updateCurrentUser` | Actualizar perfil propio | requireAuth |
| `listUsers` | Listar usuarios (paginado) | requireAuth + requireAdmin |
| `getUserById` | Obtener usuario por ID | requireAuth + requireAdmin |
| `updateUser` | Actualizar rol/status de usuario | requireAuth + requireAdmin |
| `deleteUser` | Soft delete de usuario | requireAuth + requireAdmin |
**Endpoints Disponibles:**
| Metodo | Ruta | Middleware | Descripcion |
|--------|------|------------|-------------|
| GET | `/me` | requireAuth | Perfil actual |
| PATCH | `/me` | requireAuth | Actualizar perfil |
| GET | `/` | requireAuth, requireAdmin | Listar usuarios |
| GET | `/:id` | requireAuth, requireAdmin | Obtener usuario |
| PATCH | `/:id` | requireAuth, requireAdmin | Actualizar usuario |
| DELETE | `/:id` | requireAuth, requireAdmin | Eliminar usuario |
---
## 4. ARCHIVOS MODIFICADOS
| Archivo | Tipo | Lineas |
|---------|------|--------|
| `src/modules/trading/trading.routes.ts` | Modificado | ~50 |
| `src/modules/investment/investment.routes.ts` | Modificado | ~30 |
| `src/modules/users/users.routes.ts` | Reescrito | 64 |
| `src/modules/users/controllers/users.controller.ts` | Nuevo | ~350 |
---
## 5. VALIDACION DE SEGURIDAD
### 5.1 Endpoints Protegidos
| Modulo | Total Endpoints | Con Auth | Sin Auth (Publico) |
|--------|-----------------|----------|-------------------|
| Trading (Market) | 8 | 0 | 8 (correcto) |
| Trading (Indicators) | 9 | 0 | 9 (correcto) |
| Trading (Paper) | 13 | 13 | 0 |
| Trading (Watchlists) | 10 | 10 | 0 |
| Trading (Alerts) | 8 | 8 | 0 |
| Investment (Products) | 3 | 0 | 3 (correcto) |
| Investment (Accounts) | 10 | 10 | 0 |
| Users | 6 | 6 | 0 |
| **TOTAL** | **67** | **47** | **20** |
### 5.2 Roles y Permisos
| Endpoint Group | Roles Permitidos |
|----------------|-----------------|
| /users/me | Cualquier autenticado |
| /users/* (admin) | admin, superadmin |
| /paper/* | Cualquier autenticado |
| /investment/accounts/* | Cualquier autenticado |
| /watchlists/* | Cualquier autenticado |
---
## 6. SERVICIOS YA COMPLETADOS (CONFIRMADOS)
### 6.1 ML Integration Service
**Archivo:** `src/modules/ml/services/ml-integration.service.ts`
**Funcionalidades:**
- Signal generation con confidence scoring
- Price predictions (range prediction)
- AMD phase detection
- Backtesting con metricas detalladas
- Model health monitoring
- Error handling con retry mechanism
### 6.2 Agents Service
**Archivo:** `src/modules/agents/services/agents.service.ts`
**Funcionalidades:**
- Health checks y monitoring
- Agent lifecycle (start, stop, pause, resume)
- Metrics retrieval
- Position management
- Signal broadcasting
---
## 7. METRICAS DEL SPRINT
| Metrica | Valor |
|---------|-------|
| Tareas Completadas | 5/6 (83%) |
| Endpoints Protegidos | 23 nuevos |
| Archivos Modificados | 4 |
| Lineas de Codigo | ~500 |
| Tests Unitarios | Pendiente |
---
## 8. PENDIENTES PARA SIGUIENTE SPRINT
### 8.1 Tests de Integracion (S2-T6)
- Tests Backend-ML Engine
- Tests de autenticacion
- Tests de permisos RBAC
### 8.2 Sprint 3 - LLM y Trading Agents
| ID | Tarea | Prioridad |
|----|-------|-----------|
| S3-T0 | Documentar EA Bridge | MEDIA |
| S3-T1 | MCPOrchestrator completo | CRITICA |
| S3-T2 | Live trading execution | ALTA |
| S3-T3 | Persistencia decisiones | ALTA |
| S3-T4 | Rate limiting | ALTA |
| S3-T5 | Scalping strategy | ALTA |
| S3-T6 | Persistencia trades | ALTA |
| S3-T7 | WebSocket signals | MEDIA |
---
## 9. CONCLUSION
Sprint 2 completado exitosamente con todos los objetivos principales alcanzados:
1. **Seguridad Backend** - Todos los endpoints de paper trading, investment y watchlists ahora estan protegidos con autenticacion JWT
2. **Users Module** - Implementado CRUD completo con soporte para perfiles y administracion
3. **Servicios Existentes** - Confirmado que ml-integration.service.ts y agents.service.ts ya estaban correctamente implementados
**Estado:** LISTO PARA SPRINT 3
---
**Reporte generado:** 2026-01-07
**Autor:** Claude Opus 4.5 (Technical Lead)
**Siguiente paso:** Sprint 3 - LLM y Trading Agents

View File

@ -1,351 +0,0 @@
# Reporte de Ejecucion Sprint 3
## Trading Platform - LLM y Trading Agents
**Fecha:** 2026-01-07
**Sprint:** 3 - LLM y Trading Agents
**Estado:** COMPLETADO
**Ejecutor:** Claude Opus 4.5 (Technical Lead)
---
## 1. RESUMEN EJECUTIVO
### 1.1 Objetivo del Sprint
Completar integracion de MCPOrchestrator, persistencia de decisiones, rate limiting y estrategia de scalping.
### 1.2 Estado de Tareas
| ID | Tarea | Estado | Notas |
|----|-------|--------|-------|
| S3-T0 | Documentar EA Bridge | COMPLETADO | docs/architecture/EA-BRIDGE-ARCHITECTURE.md |
| S3-T1 | MCPOrchestrator completo | COMPLETADO | Integrado en AutoTradeService |
| S3-T2 | Live trading execution | COMPLETADO | Soporta MT4 + Binance |
| S3-T3 | Persistencia decisiones | COMPLETADO | Repository + DB integration |
| S3-T4 | Rate limiting | COMPLETADO | Token bucket implementado |
| S3-T5 | Scalping strategy | COMPLETADO | Estrategia + AMD variant |
---
## 2. CAMBIOS IMPLEMENTADOS
### 2.1 EA Bridge Documentation (S3-T0)
**Archivo Creado:** `docs/architecture/EA-BRIDGE-ARCHITECTURE.md`
**Contenido:**
- Diagrama de arquitectura completo
- Descripcion de componentes (MCP Connector, MT4 Gateway, EA Bridge)
- Flujo de datos para ejecucion de trades
- Configuracion de agentes (Atlas, Orion, Nova)
- Gestion de riesgos
- Troubleshooting guide
---
### 2.2 MCPOrchestrator Integration (S3-T1 + S3-T2)
**Archivos Modificados:**
| Archivo | Cambios |
|---------|---------|
| `apps/llm-agent/src/config.py` | Agregado: mcp_mt4_url, mcp_binance_url, mcp_timeout |
| `apps/llm-agent/src/main.py` | Inicializacion del MCPOrchestrator en startup |
| `apps/llm-agent/src/services/auto_trade_service.py` | Integracion con orchestrator |
**Nuevo Archivo:** `apps/llm-agent/src/api/orchestrator_routes.py`
**Endpoints Implementados:**
| Metodo | Ruta | Descripcion |
|--------|------|-------------|
| GET | `/api/v1/orchestrator/health` | Estado de salud de connectors |
| GET | `/api/v1/orchestrator/portfolio` | Portfolio combinado MT4 + Binance |
| GET | `/api/v1/orchestrator/portfolio/summary` | Resumen formateado |
| GET | `/api/v1/orchestrator/positions` | Posiciones abiertas |
| GET | `/api/v1/orchestrator/quote/{symbol}` | Cotizacion de simbolo |
| GET | `/api/v1/orchestrator/venue/{symbol}` | Venue para simbolo |
| POST | `/api/v1/orchestrator/trade` | Ejecutar trade |
| POST | `/api/v1/orchestrator/close` | Cerrar posicion |
| GET | `/api/v1/orchestrator/symbols` | Simbolos soportados |
| GET | `/api/v1/orchestrator/rate-limits` | Estadisticas de rate limiting |
| POST | `/api/v1/orchestrator/rate-limits/reset` | Reset estadisticas |
**AutoTradeService Actualizaciones:**
- Nuevo metodo `_execute_via_orchestrator()` para multi-venue trading
- Routing automatico basado en simbolo (XAUUSD -> MT4, BTCUSDT -> Binance)
- Manejo de errores mejorado
---
### 2.3 Persistencia de Decisiones (S3-T3)
**Archivos Creados:**
| Archivo | Lineas | Descripcion |
|---------|--------|-------------|
| `src/repositories/database.py` | ~120 | Conexion asyncpg con pool |
| `src/repositories/decisions_repository.py` | ~250 | CRUD para llm_decisions |
**Clases Implementadas:**
```python
Database # Singleton con connection pool
DecisionsRepository # CRUD para ml.llm_decisions
LLMDecision # Dataclass para decisiones
```
**Enums Definidos:**
- `DecisionType`: TRADE, ALERT, WAIT, CLOSE, PARTIAL_CLOSE, etc.
- `ActionTaken`: BUY, SELL, HOLD, CLOSE_LONG, CLOSE_SHORT, etc.
- `RiskLevel`: minimal, conservative, moderate, aggressive, high_risk
- `ExecutionVenue`: MT4, MT5, BINANCE, PAPER
**Metodos del Repository:**
| Metodo | Descripcion |
|--------|-------------|
| `create_decision()` | Crear nueva decision |
| `update_execution()` | Actualizar con resultado de ejecucion |
| `get_decision()` | Obtener por ID |
| `get_recent_decisions()` | Listar recientes con filtros |
| `get_decisions_by_prediction()` | Por prediction_id |
| `get_decision_stats()` | Estadisticas agregadas |
**Integracion en AutoTradeService:**
- Nuevo metodo `_persist_decision()`
- Cada decision se guarda automaticamente en `ml.llm_decisions`
- Mapeo de confidence a risk_level
---
### 2.4 Rate Limiting (S3-T4)
**Archivo Creado:** `apps/llm-agent/src/core/rate_limiter.py`
**Algoritmo:** Token Bucket con configuracion por venue
**Limites por Venue:**
| Venue | Req/Min | Req/Sec | Burst |
|-------|---------|---------|-------|
| MT4 | 100 | 10 | 20 |
| Binance | 1200 | 20 | 50 |
| Default | 60 | 5 | 10 |
**Clases Implementadas:**
```python
RateLimitConfig # Configuracion de limites
RateLimitBucket # Token bucket por endpoint
RateLimiter # Gestor principal
```
**Metodos:**
- `acquire(venue, endpoint)` - Adquirir permiso sin espera
- `wait_and_acquire(venue, endpoint, max_wait)` - Esperar por permiso
- `get_stats()` - Estadisticas de uso
- `reset_stats()` - Resetear contadores
**Decorador:**
```python
@rate_limited("mt4", "trade")
async def execute_trade(...):
...
```
**Integracion:**
- MCPOrchestrator.call_tool() ahora usa rate_limiter.wait_and_acquire()
- Endpoint `/api/v1/orchestrator/rate-limits` para monitoreo
---
### 2.5 Scalping Strategy (S3-T5)
**Archivo Creado:** `apps/trading-agents/src/strategies/scalping.py`
**Estrategias Implementadas:**
#### ScalpingStrategy (Base)
| Parametro | Default | Descripcion |
|-----------|---------|-------------|
| fast_ema | 5 | EMA rapida |
| slow_ema | 13 | EMA lenta |
| rsi_period | 7 | Periodo RSI |
| rsi_oversold | 30 | Nivel sobreventa |
| rsi_overbought | 70 | Nivel sobrecompra |
| atr_period | 14 | Periodo ATR |
| atr_multiplier_sl | 1.5 | Multiplicador SL |
| atr_multiplier_tp | 2.0 | Multiplicador TP |
| volume_threshold | 1.2 | Umbral volumen |
| min_confidence | 0.6 | Confianza minima |
**Logica de Senales:**
LONG CONDITIONS:
1. Fast EMA > Slow EMA (o cross up)
2. RSI saliendo de sobreventa (30-60)
3. Precio > VWAP
4. Volumen confirmado (>1.2x MA)
SHORT CONDITIONS:
1. Fast EMA < Slow EMA (o cross down)
2. RSI saliendo de sobrecompra (40-70)
3. Precio < VWAP
4. Volumen confirmado (>1.2x MA)
**Indicadores Calculados:**
- Fast/Slow EMA
- RSI (7 periodos)
- ATR (14 periodos)
- Volume Ratio
- VWAP
#### AMDScalpingStrategy (Extended)
Extiende ScalpingStrategy con awareness de fases AMD:
| Fase | Bias | Efecto |
|------|------|--------|
| ACCUMULATION | LONG | +10% confidence para longs, -15% para shorts |
| MANIPULATION | AVOID | Evita senales (configurable) |
| DISTRIBUTION | SHORT | +10% confidence para shorts, -15% para longs |
**Metodo Adicional:**
```python
set_amd_phase(phase: str, confidence: float)
```
---
## 3. ARCHIVOS MODIFICADOS/CREADOS
### 3.1 Archivos Nuevos
| Archivo | Tipo | Lineas |
|---------|------|--------|
| `docs/architecture/EA-BRIDGE-ARCHITECTURE.md` | Doc | ~400 |
| `src/api/orchestrator_routes.py` | API | ~360 |
| `src/repositories/database.py` | Repo | ~120 |
| `src/repositories/decisions_repository.py` | Repo | ~250 |
| `src/core/rate_limiter.py` | Core | ~200 |
| `strategies/scalping.py` | Strategy | ~350 |
### 3.2 Archivos Modificados
| Archivo | Cambios |
|---------|---------|
| `src/config.py` | +5 lineas (MCP config) |
| `src/main.py` | +10 lineas (init/shutdown) |
| `src/services/auto_trade_service.py` | +80 lineas (orchestrator + persist) |
| `src/services/mcp_orchestrator.py` | +5 lineas (rate limit import) |
| `src/core/__init__.py` | Exports rate_limiter |
| `src/repositories/__init__.py` | Exports completos |
| `strategies/__init__.py` | +2 lineas (scalping exports) |
---
## 4. VALIDACION DE SINTAXIS
```bash
# Todos los archivos validados sin errores
python -m py_compile src/config.py
python -m py_compile src/main.py
python -m py_compile src/api/orchestrator_routes.py
python -m py_compile src/repositories/database.py
python -m py_compile src/repositories/decisions_repository.py
python -m py_compile src/services/auto_trade_service.py
python -m py_compile src/services/mcp_orchestrator.py
python -m py_compile src/core/rate_limiter.py
python -m py_compile strategies/scalping.py
```
---
## 5. METRICAS DEL SPRINT
| Metrica | Valor |
|---------|-------|
| Tareas Completadas | 6/6 (100%) |
| Archivos Nuevos | 6 |
| Archivos Modificados | 7 |
| Lineas de Codigo | ~1,700 |
| Endpoints Nuevos | 11 |
| Tests Unitarios | Pendiente |
---
## 6. DEPENDENCIAS ENTRE TAREAS
```
S3-T0 (EA Bridge Doc)
S3-T1 (MCPOrchestrator) → S3-T2 (Live Trading)
↓ ↓
S3-T3 (Persistencia) S3-T4 (Rate Limiting)
↓ ↓
└──────────┬───────────────┘
S3-T5 (Scalping Strategy)
```
---
## 7. INTEGRACION CON COMPONENTES EXISTENTES
### 7.1 Base de Datos
- Usa tabla existente `ml.llm_decisions`
- Conexion via asyncpg con pool
- Configuracion desde `database_url` en settings
### 7.2 MCP Connectors
- Integra con mcp-mt4-connector (:3605)
- Integra con mcp-binance-connector (:3606)
- Rate limiting por venue
### 7.3 Trading Agents
- ScalpingStrategy hereda de BaseStrategy
- Compatible con todos los agentes (Atlas, Orion, Nova)
- Exportada en strategies/__init__.py
---
## 8. PENDIENTES PARA SIGUIENTE SPRINT
### 8.1 Tests de Integracion
- Tests para MCPOrchestrator endpoints
- Tests para DecisionsRepository
- Tests para ScalpingStrategy
### 8.2 Sprint 4 - Refinamiento
| ID | Tarea | Prioridad |
|----|-------|-----------|
| S4-T1 | Tests unitarios Sprint 3 | ALTA |
| S4-T2 | WebSocket para signals | MEDIA |
| S4-T3 | Dashboard metricas | MEDIA |
| S4-T4 | Optimizacion scalping params | BAJA |
---
## 9. CONCLUSION
Sprint 3 completado exitosamente con todos los objetivos alcanzados:
1. **EA Bridge Documentado** - Arquitectura completa documentada
2. **MCPOrchestrator Integrado** - Multi-venue trading funcional
3. **Persistencia** - Decisiones guardadas en PostgreSQL
4. **Rate Limiting** - Proteccion contra API limits
5. **Scalping Strategy** - Estrategia lista para produccion
**Estado:** LISTO PARA SPRINT 4
---
**Reporte generado:** 2026-01-07
**Autor:** Claude Opus 4.5 (Technical Lead)
**Siguiente paso:** Sprint 4 - Refinamiento y Tests

View File

@ -1,221 +0,0 @@
# Reporte de Sesión Tech-Leader
**Fecha:** 2025-12-07
**Proyecto:** Trading Platform - Trading Platform
**Tech Leader:** Agente Orquestador
**Duración:** ~1 sesión
---
## Resumen Ejecutivo
Se orquestó el desarrollo paralelo de 3 tracks críticos para la plataforma de trading:
- **Track B:** ML Engine - Migración avanzada de modelos
- **Track C:** LLM Service - Copiloto de trading con IA local
- **Track D:** Trading Agents - Agentes Atlas/Orion/Nova
**Resultado:** ✅ COMPLETADO - Los 3 subagentes completaron sus tareas exitosamente.
---
## Subagentes Ejecutados
### 1. ML-Engine Development Agent ✅
**Tarea:** Migrar modelos avanzados del TradingAgent original
**Componentes Migrados:**
| Componente | Estado | Descripción |
|------------|--------|-------------|
| AMDDetector | ✅ 100% | Detección de fases Accumulation/Manipulation/Distribution |
| AMDModels | ✅ 100% | 3 redes neuronales especializadas + Ensemble |
| Phase2Pipeline | ✅ Listo | Pipeline completo de entrenamiento (requiere copia manual) |
| Walk-Forward | ✅ Listo | Validación robusta anti-overfitting (requiere copia manual) |
| Backtesting | ✅ Listo | Engine con 20+ métricas (requiere copia manual) |
| SignalLogger | ✅ Listo | Generador de datos para LLM fine-tuning (requiere copia manual) |
| API Endpoints | ✅ 100% | 4 nuevos endpoints + WebSocket |
**Archivos Nuevos:**
- `apps/ml-engine/src/models/amd_detector.py` (679 líneas)
- `apps/ml-engine/src/models/amd_models.py` (659 líneas)
- `apps/ml-engine/tests/test_amd_detector.py` (189 líneas)
- `apps/ml-engine/tests/test_api.py` (181 líneas)
- `apps/ml-engine/MIGRATION_REPORT.md`
**GPU:** Configurado para RTX 5060 Ti (16GB VRAM) con XGBoost CUDA
---
### 2. LLM Integration Agent ✅
**Tarea:** Implementar copiloto de trading con LLM local
**Componentes Implementados:**
| Componente | Estado | Descripción |
|------------|--------|-------------|
| OllamaClient | ✅ 100% | Cliente para LLM local con GPU |
| ClaudeClient | ✅ 100% | Fallback a API de Anthropic |
| Trading Tools | ✅ 12 tools | get_signal, analyze, portfolio, trading, education |
| System Prompt | ✅ 1500+ líneas | Especializado en trading con AMD framework |
| Context Manager | ✅ 100% | Gestión de conversaciones |
| API REST | ✅ 8 endpoints | Chat, análisis, estrategias, explicaciones |
**Archivos Nuevos:**
- `apps/llm-agent/src/core/llm_client.py` (450+ líneas)
- `apps/llm-agent/src/core/prompt_manager.py` (200+ líneas)
- `apps/llm-agent/src/core/context_manager.py` (180+ líneas)
- `apps/llm-agent/src/tools/` (5 archivos, 1000+ líneas total)
- `apps/llm-agent/src/prompts/system.txt` (1500+ líneas)
- `apps/llm-agent/docker-compose.ollama.yml`
- `apps/llm-agent/DEPLOYMENT.md` (600+ líneas)
**Modelo Recomendado:** Llama 3 8B (~10GB VRAM)
---
### 3. Trading Agents Development ✅
**Tarea:** Implementar agentes de trading automático
**Agentes Implementados:**
| Agente | Perfil | Estrategias | Max Drawdown | Target |
|--------|--------|-------------|--------------|--------|
| Atlas | Conservador | Mean Reversion, Grid | 5% | 3-5%/mes |
| Orion | Moderado | Trend Following, Momentum | 10% | 5-10%/mes |
| Nova | Agresivo | Momentum, Scalping | 20% | 10%+/mes |
**Componentes Implementados:**
| Componente | Estado | Descripción |
|------------|--------|-------------|
| BaseAgent | ✅ 100% | Clase base con gestión de posiciones |
| RiskManager | ✅ 100% | Position sizing, drawdown control |
| 4 Estrategias | ✅ 100% | Mean Reversion, Trend Following, Grid, Momentum |
| BinanceClient | ✅ 100% | Testnet + Production |
| MLSignalConsumer | ✅ 100% | Consume señales del ML Engine |
| API REST | ✅ 11 endpoints | Control de agentes |
**Archivos Nuevos:** 31 archivos totales
- `apps/trading-agents/src/agents/` (4 archivos)
- `apps/trading-agents/src/strategies/` (5 archivos)
- `apps/trading-agents/src/execution/` (risk_manager.py)
- `apps/trading-agents/src/exchange/` (binance_client.py)
- `apps/trading-agents/config/` (3 YAML files)
- `apps/trading-agents/PAPER_TRADING_GUIDE.md`
---
## Estadísticas Totales
| Métrica | Valor |
|---------|-------|
| Subagentes ejecutados | 3 |
| Archivos nuevos creados | ~50+ |
| Líneas de código generadas | ~15,000+ |
| Trading Tools implementados | 12 |
| Agentes IA implementados | 3 (Atlas, Orion, Nova) |
| Estrategias de trading | 4 |
| API Endpoints nuevos | 23+ |
---
## Acciones Requeridas (Post-sesión)
### Copias Manuales ML Engine
```bash
cd [LEGACY: apps/ml-engine - migrado desde TradingAgent]/src
cp pipelines/phase2_pipeline.py \
/home/isem/workspace/projects/trading-platform/apps/ml-engine/src/pipelines/
cp training/walk_forward.py \
/home/isem/workspace/projects/trading-platform/apps/ml-engine/src/training/
cp utils/signal_logger.py \
/home/isem/workspace/projects/trading-platform/apps/ml-engine/src/utils/
cp backtesting/engine.py backtesting/metrics.py backtesting/rr_backtester.py \
/home/isem/workspace/projects/trading-platform/apps/ml-engine/src/backtesting/
```
### Configurar Ollama
```bash
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
docker-compose -f docker-compose.ollama.yml up -d
docker exec trading-ollama ollama pull llama3:8b
```
### Paper Trading
```bash
cd /home/isem/workspace/projects/trading-platform/apps/trading-agents
cp .env.example .env
# Configurar API keys de Binance Testnet
python example_usage.py
```
---
## Estructura Final del Proyecto
```
apps/
├── database/schemas/ # 8 archivos SQL
├── ml-engine/ # ML Models + FastAPI (OQI-006)
│ ├── src/models/ # AMDDetector, RangePredictor, TPSLClassifier
│ ├── src/pipelines/ # Phase2Pipeline
│ ├── src/training/ # Walk-forward
│ ├── src/backtesting/ # Engine + Metrics
│ └── src/api/ # FastAPI con nuevos endpoints
├── llm-agent/ # LLM Copilot (OQI-007) [NUEVO]
│ ├── src/core/ # LLM Client, Prompts, Context
│ ├── src/tools/ # 12 Trading Tools
│ └── src/api/ # FastAPI REST
├── trading-agents/ # Agentes IA (OQI-004) [NUEVO]
│ ├── src/agents/ # Atlas, Orion, Nova
│ ├── src/strategies/ # Mean Reversion, Trend, Grid, Momentum
│ ├── src/exchange/ # Binance Client
│ └── config/ # YAML configs
├── backend/ # Express.js API
└── frontend/ # React + Tailwind
```
---
## Próximos Pasos
### Inmediatos
1. Ejecutar copias manuales de archivos pendientes
2. Configurar Ollama con Llama 3 8B
3. Probar paper trading en Binance Testnet
### Corto Plazo
1. Integrar ML Engine con Trading Agents
2. Integrar LLM Agent con Frontend
3. Tests de integración end-to-end
### Mediano Plazo
1. Entrenar modelos con walk-forward validation
2. Backtesting completo de estrategias
3. Fine-tuning del LLM con datos de trading
---
## Documentación Generada
| Documento | Ubicación |
|-----------|-----------|
| Plan ML/LLM/Trading | `orchestration/planes/PLAN-ML-LLM-TRADING.md` |
| ML Engine Migration | `apps/ml-engine/MIGRATION_REPORT.md` |
| LLM Deployment Guide | `apps/llm-agent/DEPLOYMENT.md` |
| Paper Trading Guide | `apps/trading-agents/PAPER_TRADING_GUIDE.md` |
| Integration Guide | `apps/trading-agents/INTEGRATION.md` |
---
## Registro de Subagentes
Actualizado en: `orchestration/estados/REGISTRO-SUBAGENTES.json`
---
*Reporte generado: 2025-12-07*
*Tech Leader: Agente Orquestador*

View File

@ -1,277 +0,0 @@
# Validacion Plan vs Analisis
## Trading Platform - Fase 3 del Proceso de Planeacion
**Fecha:** 2026-01-07
**Documento Base Analisis:** ANALISIS-CONSOLIDADO-FASE1-2026-01-07.md
**Documento Base Plan:** PLAN-DESARROLLO-2026-01-FASE2.md
---
## 1. MATRIZ DE COBERTURA - GAPS CRITICOS
| # | Gap Identificado | Sprint | Tarea | Cobertura |
|---|-----------------|--------|-------|-----------|
| 1 | ML RangePredictor R^2 negativo | Sprint 1 | S1-T1, S1-T2, S1-T3 | CUBIERTO |
| 2 | ML API no carga modelos | Sprint 1 | S1-T4 | CUBIERTO |
| 3 | Backend ml-integration.service incompleto | Sprint 2 | S2-T1 | CUBIERTO |
| 4 | LLM MCPOrchestrator incompleto | Sprint 3 | S3-T1 | CUBIERTO |
**Resultado:** 4/4 gaps CRITICOS cubiertos (100%)
---
## 2. MATRIZ DE COBERTURA - GAPS ALTA PRIORIDAD
| # | Gap Identificado | Sprint | Tarea | Cobertura |
|---|-----------------|--------|-------|-----------|
| 5 | Auth en paper trading endpoints | Sprint 2 | S2-T2 | CUBIERTO |
| 6 | Auth en investment endpoints | Sprint 2 | S2-T3 | CUBIERTO |
| 7 | WebSocket real-time Frontend | Sprint 4 | S4-T1 | CUBIERTO |
| 8 | Scalping strategy Trading Agents | Sprint 3 | S3-T5 | CUBIERTO |
| 9 | Live trading execution LLM | Sprint 3 | S3-T2 | CUBIERTO |
| 10 | Persistencia BD Trading Agents | Sprint 3 | S3-T6 | CUBIERTO |
| 11 | RLS Database | Sprint 5 | S5-T1 | CUBIERTO |
**Resultado:** 7/7 gaps ALTA prioridad cubiertos (100%)
---
## 3. MATRIZ DE COBERTURA - GAPS MEDIA PRIORIDAD
| # | Gap Identificado | Sprint | Tarea | Cobertura |
|---|-----------------|--------|-------|-----------|
| 12 | Testing E2E | Sprint 5 | S5-T4 | CUBIERTO |
| 13 | Certificados PDF Frontend | Sprint 4 | S4-T3 | CUBIERTO |
| 14 | Validacion OOS ML | Sprint 1 | S1-T6 | CUBIERTO |
| 15 | Rate limiting LLM | Sprint 3 | S3-T4 | CUBIERTO |
| 16 | Auth MCP servers | Sprint 5 | S5-T3 | CUBIERTO |
| 17 | Users module Backend | Sprint 2 | S2-T5 | CUBIERTO |
| 18 | Agents service Backend | Sprint 2 | S2-T4 | CUBIERTO |
| 19 | Investment frontend conectado | Sprint 4 | S4-T4 | CUBIERTO |
| 20 | Streaming LLM responses | Sprint 4 | S4-T2 | CUBIERTO |
| 21 | WebSocket signals Trading Agents | Sprint 3 | S3-T7 | CUBIERTO |
| 22 | Rate limiting Backend | Sprint 5 | S5-T2 | CUBIERTO |
| 23 | Tests unitarios ML | Sprint 1 | S1-T7 | CUBIERTO |
| 24 | Tests integracion Backend | Sprint 2 | S2-T6 | CUBIERTO |
| 25 | Persistencia decisiones LLM | Sprint 3 | S3-T3 | CUBIERTO |
**Resultado:** 14/14 gaps MEDIA prioridad cubiertos (100%)
---
## 4. GAPS NO CUBIERTOS EN PLAN ACTUAL
### 4.1 Gaps de Baja Prioridad (Diferidos)
| # | Gap | Razon de Diferimiento | Impacto |
|---|-----|----------------------|---------|
| 26 | Dark mode Frontend | No critico para MVP | Bajo |
| 27 | Breakout strategy | Nova tiene otras estrategias | Bajo |
| 28 | pgvector extension | Solo para RAG avanzado | Bajo |
| 29 | EA Bridge documentacion | Dependencia externa | Medio |
| 30 | Vistas materializadas BD | Optimizacion futura | Bajo |
| 31 | Particionamiento BD | Optimizacion futura | Bajo |
**Recomendacion:** Diferir a Fase 3 (Optimizacion)
### 4.2 Gaps Adicionales Identificados (No en Analisis Original)
| # | Gap Nuevo | Sprint Sugerido | Prioridad |
|---|-----------|-----------------|-----------|
| 32 | Dashboard module Frontend | Sprint 4 | BAJA |
| 33 | Settings module Frontend | Sprint 4 | BAJA |
| 34 | Admin controllers Backend | Sprint 2 | MEDIA |
| 35 | Tests educacion Backend | Sprint 5 | MEDIA |
| 36 | Tests payments Backend | Sprint 5 | MEDIA |
**Accion:** Agregar al Sprint correspondiente como tareas opcionales
---
## 5. VALIDACION DE DEPENDENCIAS
### 5.1 Cadena de Dependencias Criticas
```
S1-T4 (ML API auto-load)
|
v
S2-T1 (ml-integration.service) --> Validado: Depende de ML funcional
|
v
S3-T1 (MCPOrchestrator) --> Validado: Necesita Backend integrado
|
v
S3-T2 (Live trading) --> Validado: Requiere MCPOrchestrator
|
v
S5-T4 (E2E tests) --> Validado: Todo debe estar funcional
```
**Resultado:** Cadena de dependencias correctamente secuenciada
### 5.2 Dependencias Paralelas Posibles
| Tareas en Paralelo | Sprint | Validacion |
|-------------------|--------|------------|
| S1-T1, S1-T2, S1-T3 | 1 | OK - Sin dependencia entre si |
| S2-T2, S2-T3 | 2 | OK - Independientes |
| S3-T5, S3-T6, S3-T7 | 3 | OK - Diferentes componentes |
| S4-T1, S4-T2, S4-T3 | 4 | OK - Diferentes modulos |
| S5-T1, S5-T2, S5-T3 | 5 | OK - Diferentes capas |
**Resultado:** Paralelizacion correctamente identificada
---
## 6. VALIDACION DE ESFUERZO
### 6.1 Distribucion de Tareas por Sprint
| Sprint | Tareas | Dias Estimados | Criticas | Altas | Medias |
|--------|--------|----------------|----------|-------|--------|
| 1 | 7 | 5-7 | 4 | 2 | 1 |
| 2 | 6 | 5 | 1 | 2 | 3 |
| 3 | 7 | 5-7 | 1 | 5 | 1 |
| 4 | 5 | 5 | 0 | 2 | 3 |
| 5 | 6 | 5-7 | 0 | 4 | 2 |
| **TOTAL** | **31** | **25-31** | **6** | **15** | **10** |
### 6.2 Validacion de Carga
- Sprint 1: CRITICO - Concentra mayor riesgo tecnico
- Sprint 2: BALANCEADO - Tareas de implementacion
- Sprint 3: COMPLEJO - Multiples componentes
- Sprint 4: MODERADO - Frontend changes
- Sprint 5: NECESARIO - Testing y seguridad
**Resultado:** Distribucion razonable, Sprint 1 y 3 requieren atencion especial
---
## 7. VALIDACION DE CRITERIOS DE ACEPTACION
### 7.1 Sprint 1
| Criterio | Medible | Verificable | Alcanzable |
|----------|---------|-------------|------------|
| RangePredictor R^2 > 0.10 | Si | Si | Incierto |
| API ML < 500ms | Si | Si | Si |
| Tests > 70% | Si | Si | Si |
**Riesgo:** R^2 > 0.10 puede no ser alcanzable. Plan B requerido.
### 7.2 Sprint 2
| Criterio | Medible | Verificable | Alcanzable |
|----------|---------|-------------|------------|
| ml-integration completo | Si | Si | Si |
| Endpoints protegidos | Si | Si | Si |
| Users CRUD | Si | Si | Si |
**Resultado:** Criterios realistas
### 7.3 Sprint 3
| Criterio | Medible | Verificable | Alcanzable |
|----------|---------|-------------|------------|
| Portfolio consolidado | Si | Si | Si |
| Live trading OK | Si | Si | Requiere acceso MT4 |
| Rate limiting | Si | Si | Si |
| Scalping funcional | Si | Si | Si |
**Riesgo:** Live trading depende de EA Bridge funcional
### 7.4 Sprint 4
| Criterio | Medible | Verificable | Alcanzable |
|----------|---------|-------------|------------|
| WebSocket prices | Si | Si | Si |
| Streaming chat | Si | Si | Si |
| PDF certificates | Si | Si | Si |
**Resultado:** Criterios realistas
### 7.5 Sprint 5
| Criterio | Medible | Verificable | Alcanzable |
|----------|---------|-------------|------------|
| RLS habilitado | Si | Si | Si |
| Rate limiting | Si | Si | Si |
| E2E > 50 casos | Si | Si | Requiere esfuerzo |
**Resultado:** Criterios realistas
---
## 8. RIESGOS NO MITIGADOS
### 8.1 Riesgos Identificados sin Mitigacion Completa
| Riesgo | Plan Actual | Gap en Mitigacion |
|--------|-------------|-------------------|
| EA Bridge no disponible | Mock service | No hay plan para obtener EA Bridge real |
| ML no mejora | Simplificar modelo | No hay metricas minimas aceptables |
| Integraciones complejas | Buffer dias | No hay criterio de escalation |
### 8.2 Acciones Correctivas Recomendadas
1. **EA Bridge:** Agregar tarea S3-T0 para documentar/obtener EA Bridge
2. **ML Minimos:** Definir R^2 minimo aceptable (propuesto: > 0.05)
3. **Escalation:** Definir proceso si Sprint 1 falla
---
## 9. CONCLUSIONES DE VALIDACION
### 9.1 Cobertura de Gaps
| Prioridad | Total | Cubiertos | % |
|-----------|-------|-----------|---|
| CRITICA | 4 | 4 | 100% |
| ALTA | 7 | 7 | 100% |
| MEDIA | 14 | 14 | 100% |
| BAJA | 6 | 0 | 0% (diferidos) |
| **TOTAL** | **31** | **25** | **81%** |
### 9.2 Resultado de Validacion
- Plan cubre TODOS los gaps CRITICOS y ALTOS
- Gaps de baja prioridad correctamente diferidos
- Dependencias bien secuenciadas
- Esfuerzo distribuido razonablemente
- Criterios de aceptacion en general alcanzables
- Riesgos identificados requieren atencion adicional
### 9.3 Recomendaciones
1. **APROBAR** el plan con las siguientes condiciones:
- Agregar tarea S3-T0 para EA Bridge
- Definir metricas minimas ML
- Establecer proceso de escalation
2. **MONITOREAR** especialmente:
- Sprint 1 (riesgo tecnico alto)
- Sprint 3 (dependencia EA Bridge)
3. **REVISAR** al final de Sprint 1:
- Si ML no mejora, replantear estrategia
---
## 10. DECISION
| Estado | Descripcion |
|--------|-------------|
| **VALIDADO CON OBSERVACIONES** | Plan aprobado para ejecucion con condiciones listadas |
**Observaciones pendientes de resolver antes de Sprint 1:**
- [ ] Definir metrica minima aceptable para ML
- [ ] Plan de contingencia si EA Bridge no disponible
- [ ] Proceso de escalation documentado
---
**Validacion completada:** 2026-01-07
**Validador:** Technical Lead (Claude Opus 4.5)
**Siguiente paso:** Fase 4 - Analisis de Dependencias

View File

@ -0,0 +1,97 @@
# 01-CONTEXTO - Analisis Maestro Trading Platform
**Fecha:** 2026-01-27
**Agente:** Claude Code (Opus 4.5) - Perfil Tech-Leader/Architect
**Modo:** @ANALYSIS (C+A+P sin ejecutar)
---
## ESTADO ACTUAL DEL PROYECTO
### Metricas Generales
- **Archivos totales:** 2,305 (excluyendo node_modules, venv, .git)
- **Archivos fuente:** 1,490 (TypeScript/Python/SQL)
- **Backend:** 171 TS files, 11 modulos, 113+ endpoints
- **Frontend:** 189 TSX files, 13 modulos, 7 stores, 7 services
- **ML Engine:** 109 PY files, 3 niveles de modelos, backtesting framework
- **Database:** 89 tablas, 10 schemas, 50+ enums, 31+ funciones, 60+ triggers
- **Documentacion:** 280+ archivos markdown/yaml
- **Tareas completadas:** 19/20 (95%)
### Tareas Previas Completadas (19)
Las tareas Jan 25-27 implementaron:
- Token refresh improvements (BLOCKER-001)
- E2E video upload tests (153 tests)
- Frontend comprehensive audit (9 epics)
- ML training enhancement (29,769 LOC)
- Portfolio manager implementation
- Investment account detail pages
- Trading panels (indicators, drawing tools, screener)
- Education advanced (video upload, certificates)
- Payments advanced (Stripe Elements, refunds)
- Notification system complete
- ML data migration MySQL->PostgreSQL
- LLM assistant panels
- ML utility panels
### Tarea Previa EN_PROGRESO
- **TASK-2026-01-26-ANALYSIS-INTEGRATION-PLAN:** Fases C+A+P completadas, V+E+D pendientes
- Hallazgos: 7 gaps coherencia, 4 blockers P0, 58 docs faltantes, 2,457h trabajo pendiente
---
## DISCREPANCIAS ENCONTRADAS EN ESTA SESION
### D1: Puertos Python Services (PROJECT-PROFILE.yml vs Realidad)
| Servicio | PROJECT-PROFILE.yml | Real (docker-compose/env) |
|----------|--------------------|-----------------------------|
| ml-engine | 8000 | 3083 |
| data-service | 8001 | 3084 |
| mt4-gateway | 8002 | 3085 (llm-agent) / 3086 (agents) |
### D2: Schemas listados (CLAUDE.md vs DDL real)
- **CLAUDE.md dice:** core, trading, ml, portfolio (4)
- **DDL real:** auth, education, trading, investment, financial, portfolio, market_data, ml, llm, audit (10)
### D3: Password BD
- **CLAUDE.md:** trading_dev_2026
- **.env.example:** trading_dev_2025
- **WORKSPACE-INTEGRATION.yml:** trading_dev_2025
### D4: ML Frameworks
- **PROJECT-PROFILE.yml:** TensorFlow, scikit-learn, pandas
- **Codigo real:** PyTorch, XGBoost, scikit-learn, pandas
### D5: Progreso OQI Modules (CLAUDE.md desactualizado)
- No refleja los 19 tasks completados Jan 25-27
- Porcentajes originales vs realidad post-tareas
### D6: Trading Agents Port
- **Backend client:** 8004
- **DEVENV-PORTS-INVENTORY:** 3086
### D7: pgvector Extension
- **llm schema DDL:** Referencia embeddings con vector type
- **00-extensions.sql:** NO incluye pgvector
### D8: Missing in LOCAL-WSL-ENVIRONMENT.yml
- trading-platform NO esta listado en seccion bases_de_datos
### D9: Gitea Repository
- **DEPLOYMENT-INVENTORY.yml:** status: "pendiente_crear"
- Repositorio en Gitea no creado
---
## ALCANCE DEL ANALISIS
Este analisis cubre las siguientes areas con N niveles de subtareas:
1. **DDL & Data Layer** - Validacion completa de objetos, seeds, funciones, triggers
2. **Backend Integration** - Coherencia endpoints-entities-DDL
3. **Frontend Integration** - Coherencia components-services-endpoints
4. **ML Pipeline** - Training, backtesting, 12-month OOS exclusion
5. **Infrastructure** - WSL, Docker, puertos, credenciales
6. **Documentation** - Purga, actualizacion, definiciones faltantes
7. **Cross-Layer Coherence** - DDL->Backend->Frontend pipeline
8. **Execution Order** - Dependencias y orden logico

View File

@ -0,0 +1,397 @@
# 02-ANALISIS-HALLAZGOS - Trading Platform
**Fecha:** 2026-01-27
**Subagentes utilizados:** 8 (paralelo)
---
## AREA 1: DATABASE & DDL
### 1.1 Inventario de Objetos DDL
| Schema | Tablas | Enums | Functions | Triggers | Estado |
|--------|--------|-------|-----------|----------|--------|
| auth | 14 | 6 | 4 | 6 | COMPLETO |
| education | 15 | 6 | 8+ | 12+ | COMPLETO |
| trading | 10 | 9 | 6 | 4 | COMPLETO |
| financial | 10 | 11 | 13 | 15+ | COMPLETO |
| investment | 9 | 6 | 1 | 1 | COMPLETO |
| portfolio | 5 | 4 | 2 | 4 | COMPLETO |
| market_data | 4 | 2 | 2 | 0 | COMPLETO |
| ml | 11 | 7 | 5 | 1 | COMPLETO |
| llm | 5 | 7 | 0 | 0 | INCOMPLETO |
| audit | 7 | 5 | 0 | 0 | COMPLETO |
| **TOTAL** | **89** | **63** | **41+** | **43+** | |
### 1.2 Hallazgos DDL
**H-DDL-001 (CRITICO): pgvector extension faltante**
- `llm.embeddings` usa tipo `vector` pero `CREATE EXTENSION pgvector` no esta en 00-extensions.sql
- **Impacto:** LLM embeddings y busqueda por similitud no funcionaran
- **Fix:** Agregar `CREATE EXTENSION IF NOT EXISTS vector;` a extensions
**H-DDL-002 (MEDIO): Migration sin schema prefix**
- `2026-01-27_add_token_rotation.sql` referencia `sessions` sin `auth.sessions`
- **Impacto:** Puede fallar si hay tablas sessions en otros schemas
- **Fix:** Agregar prefijo `auth.`
**H-DDL-003 (BAJO): Enums duplicados entre schemas**
- `timeframe` definido en trading, market_data y ml schemas
- `risk_profile` definido en investment y portfolio schemas
- **Fix:** Crear schema `shared_types` o consolidar en `public`
**H-DDL-004 (MEDIO): Sin down migrations**
- Solo hay forward migrations, sin rollback capability
- **Fix:** Crear companion down migrations
**H-DDL-005 (BAJO): Particiones auth_logs sin mantenimiento automatico**
- Solo current + next month partitions creadas
- No hay pg_cron job para crear futuras particiones
- **Fix:** Agregar script pg_cron o migration periodica
### 1.3 Analisis Seeds vs Triggers/Functions
**Seeds existentes:**
- `seeds/prod/education/01-education-courses.sql`: 5 categorias, 1 curso, 7 modulos, 28 lecciones, 5 quizzes
**Redundancia detectada: NINGUNA**
- Los seeds proveen datos de contenido (cursos, lecciones, preguntas)
- Las funciones/triggers proveen logica (auto-enrollment, auto-certificates, XP calculation)
- No hay overlap entre datos seed y datos generables por triggers
- Seeds usan `ON CONFLICT DO NOTHING` (idempotentes)
**Seeds faltantes:**
- S-SEED-001: Symbols base (trading.symbols) - No hay seed para pares forex/crypto
- S-SEED-002: Rate limiting defaults (auth.rate_limiting_config) - Estan en DDL, no en seed (CORRECTO)
- S-SEED-003: Subscription plans (financial.subscriptions) - No hay seed para plans (free/basic/pro/premium)
- S-SEED-004: Investment products (investment.products) - No hay seed para Atlas/Orion/Nova products
- S-SEED-005: Market data tickers (market_data.tickers) - No hay seed para symbols base
- S-SEED-006: Default admin user - Solo existe en education seed, deberia estar en auth seed
**Funciones que PODRIAN reemplazar seeds:**
- `trading.create_user_trading_defaults()` - YA crea watchlist default por trigger (CORRECTO)
- `education.create_user_profile()` - YA crea profile por trigger (CORRECTO)
- `financial.generate_invoice_number()` - YA genera numeros (CORRECTO)
- Rate limiting configs: Insertados directamente en DDL (CORRECTO, no redundante)
---
## AREA 2: BACKEND - COHERENCIA CON DDL
### 2.1 Estado por Modulo
| Modulo Backend | Endpoints | Entities/Models | Services | Completitud |
|----------------|-----------|-----------------|----------|-------------|
| auth | 40+ | SQL directo | 7 services | 90% |
| users | 7 | SQL directo | 1 service | 30% |
| trading | 40+ | SQL directo | 8 services | 50% |
| education | 60+ | SQL directo | 5 services | 40% |
| investment | 15 | SQL directo | parcial | 35% |
| payments | 16 | SQL directo | parcial | 50% |
| portfolio | 13 | SQL directo | parcial | 45% |
| ml | 16 | ML Engine client | 1 client | 70% |
| llm | 5 | LLM Agent client | 1 client | 40% |
| agents | 15 | Agents client | 1 client | 75% |
| admin | 7 | MOCK data | 0 real | 20% |
| notifications | 8 | SQL directo | parcial | 35% |
### 2.2 Hallazgos Backend
**H-BE-001 (CRITICO): Sin capa de entities/models**
- Backend usa SQL raw queries con `db.query<unknown>()`
- No hay ORM ni type-safe database access
- **Impacto:** Sin validacion de tipos entre DDL y queries
- **Fix:** Implementar entities o usar query builder tipado
**H-BE-002 (CRITICO): Admin module retorna MOCK data**
- Dashboard, users, audit - todo es hardcoded
- **Impacto:** Panel admin completamente no-funcional contra BD
- **Fix:** Conectar a BD real
**H-BE-003 (ALTO): Trading service layer INCOMPLETO**
- Market data, orders, positions - servicios parciales
- Paper trading simulation no conectada a BD
- **Impacto:** Funcionalidad core de trading incompleta
- **Fix:** Implementar services con BD integration
**H-BE-004 (MEDIO): WebSocket implementado pero NO integrado en trading**
- websocket.server.ts funcional con channels
- Trading module NO lo usa para real-time data
- **Impacto:** UI hace polling en vez de websocket
- **Fix:** Integrar WS en trading module
**H-BE-005 (MEDIO): 113+ endpoints definidos, ~50% implementados**
- Muchos endpoints son stubs que retornan mock/placeholder data
- **Fix:** Implementar servicio por servicio
**H-BE-006 (BAJO): Trading Agents client apunta a puerto 8004**
- Deberia ser 3086 segun DEVENV-PORTS-INVENTORY
- **Fix:** Actualizar configuracion
---
## AREA 3: FRONTEND - COHERENCIA CON BACKEND
### 3.1 Estado por Modulo
| Modulo Frontend | Pages | Components | Service | Store | Estado |
|-----------------|-------|------------|---------|-------|--------|
| auth | 8 | 8 | FALTANTE | N/A | 20% ready |
| trading | 1+37 | 37 | FALTANTE | tradingStore | 25% ready |
| ml-dashboard | 1+6 | 6 | mlService | N/A | 95% ready |
| backtesting | 1+4 | 4 | backtestService | N/A | 90% ready |
| education | 6 | 7 | educationService | educationStore | 85% ready |
| payments | 4 | 4 | paymentService | paymentStore | 85% ready |
| admin | 4 | 2 | adminService | N/A | 85% ready |
| portfolio | 0/4 | 0 | FALTANTE | N/A | 0% |
| investment | 0/7 | 0 | FALTANTE | N/A | 0% |
| assistant | 0+3 | 3 | llmAgentService | chatStore | 40% |
| settings | 1 | 0 | FALTANTE | N/A | 5% |
| dashboard | 1 | 0 | FALTANTE | N/A | 5% |
| notifications | 0 | 0 | FALTANTE | N/A | 0% |
### 3.2 Hallazgos Frontend
**H-FE-001 (CRITICO): trading.service.ts NO EXISTE**
- Trading module (core del producto) no tiene service layer
- tradingStore referencia tradingService.getKlines(), getTicker(), etc
- **Impacto:** Pagina /trading CRASHEA al cargar
- **Fix:** Crear trading.service.ts conectando a backend endpoints
**H-FE-002 (CRITICO): auth.service.ts NO EXISTE**
- Se asume delegado a MCP-Auth port 3095
- No hay documentacion de como frontend se autentica
- **Fix:** Crear auth.service.ts o documentar flow MCP-Auth
**H-FE-003 (ALTO): Portfolio module - 4 rutas sin componentes**
- /portfolio, /portfolio/new, /portfolio/goals/new, /portfolio/:id/edit
- Lazy-loaded pero componentes no existen
- **Fix:** Implementar componentes o remover rutas
**H-FE-004 (ALTO): Investment module - 7 rutas sin componentes**
- /investment, /investment/portfolio, /investment/products, etc
- Solo types definidos (investment.types.ts)
- **Fix:** Implementar componentes
**H-FE-005 (MEDIO): Dashboard con MOCK data**
- Stats hardcodeados, grafico "por implementar"
- **Fix:** Conectar a backend endpoints
**H-FE-006 (MEDIO): Notifications module vacio**
- Ruta definida pero no component
- **Fix:** Implementar notification center
**H-FE-007 (BAJO): No Error Boundaries globales**
- Componente ErrorBoundary.tsx creado pero no wrapping global
- **Fix:** Agregar en App.tsx como boundary global
---
## AREA 4: ML PIPELINE & BACKTESTING
### 4.1 Estado del Pipeline
| Componente | Estado | Cobertura |
|------------|--------|-----------|
| Data Loading (PostgreSQL) | FUNCIONAL | XAUUSD, EURUSD, BTCUSD, GBPUSD, USDJPY |
| Feature Engineering | FUNCIONAL | 108 features |
| Temporal Split (OOS) | CONFIGURADO | 2023-2024 train, 2025 test |
| Level 0: Attention | ENTRENADO | 12 modelos (6 symbols x 2 TFs) |
| Level 1: RangePredictor | ENTRENADO | R2: 0.48-0.55 |
| Level 1: AMDDetector | ENTRENADO | Dir. accuracy 92%+ |
| Level 1: MovementMagnitude | ENTRENADO | Functional |
| Level 2: XGBoost Metamodel | CONFIGURADO | Default for most symbols |
| Level 2: Neural Gating | CONFIGURADO | Only XAUUSD |
| Backtesting Engine | FUNCIONAL | Multiple R:R configs |
| Walk-Forward Validation | IMPLEMENTADO | 5 splits |
### 4.2 Hallazgos ML
**H-ML-001 (ALTO): Estandar 12 meses OOS - PARCIALMENTE ALINEADO**
- Config actual: Train 2023-2024, OOS test 2025 (12 meses)
- PERO: El usuario pide excluir "los ultimos 12 meses en la BD"
- Si la BD tiene datos hasta 2026-01, deberia ser:
- Train: 2023-01 a 2024-12
- OOS: 2025-01 a 2025-12 (o 2025-02 a 2026-01)
- **Fix:** Parametrizar OOS dynamically basado en max(fecha) en BD - 12 meses
**H-ML-002 (ALTO): Backtesting OOS no ejecutado recientemente**
- Scripts existen pero no hay evidencia de ejecucion reciente con 2025 data
- Performance targets definidos (80% WR, PF 4.0, Sharpe 2.5) pero no validados
- **Fix:** Ejecutar backtesting OOS completo y validar metricas
**H-ML-003 (MEDIO): Neural Gating solo para XAUUSD**
- Otros 4 symbols usan XGBoost metamodel
- Config muestra EURUSD neural R2=-157 (terriblemente malo)
- **Fix:** Investigar por que neural falla en EURUSD, optimizar o mantener XGBoost
**H-ML-004 (MEDIO): Data Service 20% completo**
- Real-time data aggregation INCOMPLETO
- Dependencia para datos frescos de mercado
- **Fix:** Completar data-service o usar alternativa (Binance WS directo)
**H-ML-005 (BAJO): Modelo accuracy R2 bajo en regression**
- R2: 0.48-0.55 para range prediction (mediocre)
- Directional accuracy: 92%+ (excelente)
- **Nota:** Direccion mas facil que magnitud - normal en trading ML
---
## AREA 5: INFRAESTRUCTURA & WSL
### 5.1 Estado de Alineacion
| Configuracion | Estado | Issues |
|---------------|--------|--------|
| DEVENV-PORTS-INVENTORY | DEFINIDO | Puertos asignados 3080-3095 |
| docker-compose.yml | FUNCIONAL | 7 servicios definidos |
| LOCAL-WSL-ENVIRONMENT | DESALINEADO | trading-platform NO listado |
| SHARED-PLATFORM-CONFIG | DESALINEADO | trading-platform NO listado |
| DEPLOYMENT-INVENTORY | PARCIAL | Gitea repo pendiente crear |
| WORKSPACE-INTEGRATION | DEFINIDO | Password inconsistente |
### 5.2 Hallazgos Infraestructura
**H-INFRA-001 (ALTO): trading-platform ausente de LOCAL-WSL-ENVIRONMENT.yml**
- No esta en seccion bases_de_datos del WSL
- Necesario para que infra workspace lo gestione
- **Fix:** Agregar entrada con db_name, user, pass, redis_db
**H-INFRA-002 (ALTO): Password inconsistente**
- CLAUDE.md: trading_dev_2026
- .env.example + WORKSPACE-INTEGRATION: trading_dev_2025
- **Fix:** Estandarizar a trading_dev_2026 en TODOS los archivos
**H-INFRA-003 (MEDIO): SHARED-PLATFORM-CONFIG sin trading**
- No esta en seccion databases del config compartido
- **Fix:** Agregar entrada
**H-INFRA-004 (MEDIO): Gitea repository no creado**
- DEPLOYMENT-INVENTORY: status "pendiente_crear"
- **Fix:** Crear repo en Gitea (72.60.226.4:3000)
**H-INFRA-005 (BAJO): .env.ports referenciado pero puede no existir**
- DEVENV-PORTS-INVENTORY referencia `projects/trading-platform/.env.ports`
- **Fix:** Verificar/crear archivo
---
## AREA 6: DOCUMENTACION
### 6.1 Estado de Documentacion
| Area | Archivos | Estado | Accion |
|------|----------|--------|--------|
| docs/00-vision-general | 5 | ACTUAL | Update port note |
| docs/01-arquitectura | 11 | ACTUAL | Minor updates |
| docs/02-definicion-modulos | 164 | ACTUAL | OQI-009 incomplete |
| orchestration/inventarios | 4 | ACTUAL | 2026-01-26 |
| orchestration/trazas | 3 | ACTUAL | OK |
| orchestration/_archive | 7 folders | OBSOLETO | PURGAR |
| PROJECT-STATUS.md | 1 | DESACTUALIZADO | Update (2026-01-07) |
| PROXIMA-ACCION.md | 1 | DESACTUALIZADO | Update (2026-01-04) |
| PROJECT-PROFILE.yml | 1 | DESACTUALIZADO | Puertos, frameworks |
### 6.2 Documentos a PURGAR
```
orchestration/_archive/reportes/
REPORTE-SESION-2025-12-07.md -> ELIMINAR
REPORTE-EJECUCION-SPRINT1.md -> ELIMINAR
REPORTE-EJECUCION-SPRINT2.md -> ELIMINAR
REPORTE-EJECUCION-SPRINT3.md -> ELIMINAR
VALIDACION-PLAN-VS-ANALISIS-2026-01-07 -> ELIMINAR
orchestration/_archive/analisis/
ANALISIS-GAPS-ML-FIRST-2026-01.md -> CONSOLIDAR en tarea
ANALISIS-DEPENDENCIAS-2026-01-07.md -> CONSOLIDAR en DEPENDENCY-GRAPH
ANALISIS-CONSOLIDADO-FASE1-2026-01-07 -> ARCHIVAR con fecha
docs/00-vision-general/
NOTA-DISCREPANCIA-PUERTOS-2025-12-08 -> ELIMINAR (resuelto)
```
### 6.3 Documentos a ACTUALIZAR
| Documento | Cambios Necesarios |
|-----------|-------------------|
| PROJECT-PROFILE.yml | Puertos (3083/3084/3085), frameworks (PyTorch), schemas (10), progreso OQI |
| CLAUDE.md (proyecto) | Schemas (10 no 4), password (estandarizar) |
| PROJECT-STATUS.md | Reflejar estado post Jan 25-27 tasks |
| PROXIMA-ACCION.md | Nueva proxima accion basada en este plan |
| LOCAL-WSL-ENVIRONMENT.yml | Agregar trading-platform entry |
| SHARED-PLATFORM-CONFIG.yml | Agregar trading-platform databases |
| WORKSPACE-INTEGRATION.yml | Estandarizar password |
### 6.4 Definiciones Faltantes
| Item | Tipo | Modulo | Prioridad |
|------|------|--------|-----------|
| User stories OQI-006 (ML) | US | OQI-006 | MEDIO |
| User stories OQI-007 (LLM) | US | OQI-007 | MEDIO |
| ET specs for OQI-009 (MT4) remaining | ET | OQI-009 | BAJO (module blocked) |
| API contracts comprehensive | ET | ALL | ALTO |
| Deployment guide | DOC | Platform | MEDIO |
| Integration test plan | ET | ALL | ALTO |
---
## AREA 7: COHERENCIA CROSS-LAYER
### 7.1 DDL -> Backend Coherence
| Schema | Tablas DDL | Entities Backend | Gap |
|--------|-----------|-----------------|-----|
| auth (14) | 14 SQL queries | 0 formal entities | 14 faltantes |
| education (15) | 15 SQL queries | 0 formal entities | 15 faltantes |
| trading (10) | partial queries | 0 formal entities | 10 faltantes |
| financial (10) | partial queries | 0 formal entities | 10 faltantes |
| investment (9) | partial queries | 0 formal entities | 9 faltantes |
| portfolio (5) | 5 SQL queries | 0 formal entities | 5 faltantes |
| market_data (4) | via ML Engine | N/A (Python) | N/A |
| ml (11) | via ML Engine | N/A (Python) | N/A |
| llm (5) | partial queries | 0 formal entities | 5 faltantes |
| audit (7) | 0 queries | 0 entities | 7 faltantes |
**GAP TOTAL: 75 entities faltantes en backend TypeScript**
(No hay ORM ni entity layer formal)
### 7.2 Backend -> Frontend Coherence
| Backend Module | Endpoints | Frontend Service | Match |
|----------------|-----------|------------------|-------|
| auth | 40+ | FALTANTE | 0% |
| trading | 40+ | FALTANTE | 0% |
| education | 60+ | educationService | 80% |
| payments | 16 | paymentService | 85% |
| portfolio | 13 | FALTANTE | 0% |
| investment | 15 | PARCIAL (1 file) | 30% |
| ml | 16 | mlService | 90% |
| llm | 5 | chatService | 60% |
| agents | 15 | via adminService | 70% |
| admin | 7 | adminService | 80% |
| notifications | 8 | FALTANTE | 0% |
### 7.3 Gaps Criticos de Coherencia
1. **Auth flow completo** - DDL tiene 14 tablas, backend tiene 40+ endpoints, frontend NO tiene service
2. **Trading flow completo** - DDL tiene 10 tablas, backend tiene 40+ endpoints, frontend NO tiene service
3. **Portfolio flow** - DDL tiene 5 tablas, backend tiene 13 endpoints, frontend tiene 0 pages y 0 service
4. **Investment flow** - DDL tiene 9 tablas, backend tiene 15 endpoints, frontend tiene 0 pages
5. **Notifications flow** - DDL tiene 2 tablas, backend tiene 8 endpoints, frontend tiene 0 components
6. **Audit trail** - DDL tiene 7 tablas, backend tiene 0 queries, frontend tiene 0 views
---
## RESUMEN DE HALLAZGOS
### Por Severidad
| Severidad | Count | IDs |
|-----------|-------|-----|
| CRITICO | 7 | H-DDL-001, H-BE-001, H-BE-002, H-FE-001, H-FE-002, H-FE-003, H-FE-004 |
| ALTO | 8 | H-DDL-002, H-BE-003, H-BE-004, H-ML-001, H-ML-002, H-INFRA-001, H-INFRA-002, coherence gaps |
| MEDIO | 10 | H-DDL-003, H-BE-005, H-BE-006, H-FE-005, H-FE-006, H-ML-003, H-ML-004, H-INFRA-003, H-INFRA-004, docs |
| BAJO | 6 | H-DDL-004, H-DDL-005, H-FE-007, H-ML-005, H-INFRA-005, enums |
**Total: 31 hallazgos**

View File

@ -0,0 +1,693 @@
# 03-PLAN MAESTRO JERARQUICO - Trading Platform
**Fecha:** 2026-01-27
**Modo:** @ANALYSIS (Plan de ejecucion sin ejecutar)
**Metodologia:** CAPVED por cada tarea/subtarea
**Agentes:** Claude Code (orquestador) + subagentes paralelos
---
## ESTRUCTURA DE FASES
```
FASE 0: Fundamentos (sin dependencias)
├── 0.1 Correccion de discrepancias y limpieza
└── 0.2 Infraestructura y alineacion WSL
FASE 1: Data Layer (base para todo)
├── 1.1 DDL fixes y extensiones
├── 1.2 Seeds faltantes
└── 1.3 Recreation de BD en WSL
FASE 2: Backend Core (depende de Fase 1)
├── 2.1 Entity/model layer
├── 2.2 Auth service completion
├── 2.3 Trading service completion
└── 2.4 Remaining services
FASE 3: Frontend Integration (depende de Fase 2)
├── 3.1 Service layers faltantes
├── 3.2 Page implementations
└── 3.3 Real data wiring
FASE 4: ML & Backtesting (paralelo con Fase 2-3)
├── 4.1 OOS dinamico (12 meses)
├── 4.2 Entrenamiento completo
└── 4.3 Backtesting validacion
FASE 5: Integration Testing (depende de Fases 2-4)
├── 5.1 Backend API tests
├── 5.2 Frontend E2E tests
└── 5.3 ML integration tests
FASE 6: Documentation & Cleanup (paralelo)
├── 6.1 Purga documentacion
├── 6.2 Actualizacion definiciones
└── 6.3 Inventarios sync
```
---
## FASE 0: FUNDAMENTOS
### TAREA 0.1: Correccion de Discrepancias
**Prioridad:** P0 | **Paralelizable:** SI | **CAPVED:** Quick
#### 0.1.1 Estandarizar password BD
- **C:** Password inconsistente (2025 vs 2026) en 5+ archivos
- **A:** Afecta .env.example, WORKSPACE-INTEGRATION.yml, docker-compose.yml
- **P:** Cambiar TODO a `trading_dev_2026`
- **E:** Editar archivos
- **V:** grep "trading_dev_20" en todo el workspace
- **D:** Actualizar CREDENTIALS-INVENTORY.yml
- **Archivos:** .env.example, docker-compose.yml, WORKSPACE-INTEGRATION.yml, DATABASE_INVENTORY.yml, CLAUDE.md (proyecto)
#### 0.1.2 Corregir puertos Python services en PROJECT-PROFILE.yml
- **C:** Puertos 8000/8001/8002 en profile vs 3083/3084/3085-3086 reales
- **A:** Solo afecta documentacion/referencia
- **P:** Actualizar PROJECT-PROFILE.yml
- **E:** Editar archivo
- **V:** Comparar con DEVENV-PORTS-INVENTORY.yml
- **D:** N/A
- **Archivos:** PROJECT-PROFILE.yml
#### 0.1.3 Corregir ML frameworks en PROJECT-PROFILE.yml
- **C:** TensorFlow listado pero no se usa; PyTorch y XGBoost faltan
- **P:** Cambiar a PyTorch, XGBoost, scikit-learn, pandas
- **Archivos:** PROJECT-PROFILE.yml
#### 0.1.4 Actualizar schemas en CLAUDE.md proyecto
- **C:** Solo 4 schemas listados (core, trading, ml, portfolio) vs 10 reales
- **P:** Listar los 10 schemas reales
- **Archivos:** CLAUDE.md (proyecto)
#### 0.1.5 Corregir trading-agents port en backend client
- **C:** Backend client apunta a 8004, deberia ser 3086
- **A:** Afecta conexion backend -> trading agents
- **P:** Actualizar configuracion
- **Archivos:** apps/backend/src/shared/clients/trading-agents.client.ts, .env.example
#### 0.1.6 Actualizar progreso OQI modules
- **C:** Porcentajes en CLAUDE.md y PROJECT-PROFILE.yml no reflejan tareas completadas
- **P:** Recalcular basado en estado real post Jan 25-27 tasks
- **Archivos:** CLAUDE.md, PROJECT-PROFILE.yml
---
### TAREA 0.2: Infraestructura y Alineacion WSL
**Prioridad:** P0 | **Paralelizable:** SI | **CAPVED:** Quick
#### 0.2.1 Agregar trading-platform a LOCAL-WSL-ENVIRONMENT.yml
- **C:** No esta en seccion bases_de_datos
- **P:** Agregar entrada completa con db_name, user, pass, redis_db, schemas
- **Archivos:** orchestration/inventarios/LOCAL-WSL-ENVIRONMENT.yml
#### 0.2.2 Agregar trading-platform a SHARED-PLATFORM-CONFIG.yml
- **C:** No esta en seccion databases
- **P:** Agregar entrada con credenciales estandarizadas
- **Archivos:** orchestration/agents/configs/SHARED-PLATFORM-CONFIG.yml
#### 0.2.3 Crear/verificar .env.ports
- **C:** DEVENV-PORTS-INVENTORY referencia archivo que puede no existir
- **P:** Crear si no existe con puertos oficiales
- **Archivos:** projects/trading-platform/.env.ports
#### 0.2.4 Verificar script unified-recreate-db.sh soporte trading
- **C:** Script puede no tener caso para trading-platform
- **P:** Agregar soporte si no existe
- **Archivos:** scripts/database/unified-recreate-db.sh
---
## FASE 1: DATA LAYER
### TAREA 1.1: DDL Fixes y Extensiones
**Prioridad:** P0 | **Bloquea:** Fase 2 | **CAPVED:** Full
#### 1.1.1 Agregar pgvector extension
- **C:** llm.embeddings usa tipo vector sin extension
- **A:** Requiere PostgreSQL con pgvector instalado en WSL
- **P:** Agregar `CREATE EXTENSION IF NOT EXISTS vector;` a 00-extensions.sql
- **E:** Editar DDL, recrear BD
- **V:** Verificar que tabla embeddings se crea correctamente
- **D:** Actualizar DATABASE_INVENTORY.yml
- **Archivos:** apps/database/ddl/00-extensions.sql, apps/database/ddl/schemas/llm/00-extensions.sql
#### 1.1.2 Fix migration schema prefix
- **C:** 2026-01-27_add_token_rotation.sql sin auth. prefix
- **P:** Agregar `auth.` a referencias de sessions
- **V:** Re-ejecutar migration
- **Archivos:** apps/database/migrations/2026-01-27_add_token_rotation.sql
#### 1.1.3 Crear down migrations
- **C:** No hay rollback capability
- **P:** Crear companion down migration para token_rotation
- **Archivos:** apps/database/migrations/2026-01-27_add_token_rotation_DOWN.sql
#### 1.1.4 Agregar partition maintenance para auth_logs
- **C:** Solo current + next month
- **P:** Crear funcion de maintenance automatica
- **Archivos:** apps/database/ddl/schemas/auth/functions/partition_maintenance.sql
---
### TAREA 1.2: Seeds Faltantes
**Prioridad:** P1 | **Bloquea:** Fase 2 (parcial) | **CAPVED:** Full
#### 1.2.1 Seed: trading.symbols (pares forex/crypto base)
- **C:** No hay seed para symbols. Trading necesita symbols base
- **A:** Frontend necesita symbols para watchlists y charts
- **P:** Crear seed con: XAUUSD, EURUSD, GBPUSD, USDJPY, BTCUSD, AUDUSD + info basica
- **V:** Verificar symbols disponibles en Binance connector
- **Archivos:** apps/database/seeds/prod/trading/01-symbols.sql
#### 1.2.2 Seed: investment.products (Atlas/Orion/Nova)
- **C:** No hay seed para productos de inversion
- **A:** Frontend investment pages necesitan products
- **P:** Crear seed con 3 productos (Atlas conservative, Orion moderate, Nova aggressive)
- **Archivos:** apps/database/seeds/prod/investment/01-products.sql
#### 1.2.3 Seed: market_data.tickers
- **C:** market_data.tickers vacio
- **A:** ML Engine y Data Service necesitan tickers base
- **P:** Crear seed sincronizado con trading.symbols
- **Archivos:** apps/database/seeds/prod/market_data/01-tickers.sql
#### 1.2.4 Seed: financial.subscription_plans (planes VIP)
- **C:** No hay planes definidos en BD
- **A:** Payments module necesita plans (free/basic/pro/premium/enterprise)
- **P:** Crear seed con 5 planes y features
- **Archivos:** apps/database/seeds/prod/financial/01-subscription-plans.sql
#### 1.2.5 Seed: auth admin user
- **C:** Solo existe admin en education seed
- **A:** Admin panel necesita usuario admin real
- **P:** Crear seed con admin user (admin@orbiquant.com)
- **Archivos:** apps/database/seeds/prod/auth/01-admin-user.sql
---
### TAREA 1.3: Recreacion de BD en WSL
**Prioridad:** P0 | **Bloquea:** Fase 2 | **CAPVED:** Full
**Depende de:** 1.1, 1.2
#### 1.3.1 Ejecutar script de recreacion
- **C:** BD puede no tener todos los cambios recientes
- **P:** `unified-recreate-db.sh trading-platform --drop`
- **V:** Verificar 89 tablas creadas, seeds ejecutados
- **Archivos:** Script output
#### 1.3.2 Verificar pgvector extension
- **V:** `SELECT * FROM pg_extension WHERE extname = 'vector';`
#### 1.3.3 Verificar seeds ejecutados
- **V:** Contar registros en: trading.symbols, investment.products, market_data.tickers, education.categories
---
## FASE 2: BACKEND CORE
### TAREA 2.1: Entity/Model Layer
**Prioridad:** P1 | **Bloquea:** 2.2-2.4 | **CAPVED:** Full
**Depende de:** Fase 1
#### 2.1.1 Definir patron de entity layer
- **C:** Backend usa raw SQL sin tipo safety
- **A:** 75 entities faltantes formalmente
- **P:** Decidir entre: (a) TypeORM entities, (b) Drizzle ORM, (c) Type-safe query builder, (d) Interfaces TS manuales
- **V:** Evaluar impacto en codigo existente
- **Nota:** Requiere decision arquitectonica del usuario
#### 2.1.2 Crear interfaces TypeScript por schema
- **C:** Representar DDL como interfaces TS
- **P:** 1 archivo de interfaces por schema (10 archivos)
- **Archivos:**
- src/shared/database/entities/auth.entities.ts
- src/shared/database/entities/trading.entities.ts
- src/shared/database/entities/education.entities.ts
- src/shared/database/entities/financial.entities.ts
- src/shared/database/entities/investment.entities.ts
- src/shared/database/entities/portfolio.entities.ts
- src/shared/database/entities/market-data.entities.ts
- src/shared/database/entities/ml.entities.ts
- src/shared/database/entities/llm.entities.ts
- src/shared/database/entities/audit.entities.ts
#### 2.1.3 Crear repository pattern base
- **P:** BaseRepository<T> con CRUD generico tipado
- **Archivos:** src/shared/database/repositories/base.repository.ts
---
### TAREA 2.2: Auth Services Completion
**Prioridad:** P0 | **CAPVED:** Full
**Depende de:** 2.1
#### 2.2.1 Completar token service (ya avanzado por BLOCKER-001)
- **C:** Token rotation implementado
- **V:** Verificar que rate limiting, rotation y proactive refresh funcionan E2E
#### 2.2.2 Integrar auth con entity layer
- **P:** Actualizar queries a usar entities tipadas
#### 2.2.3 Completar OAuth providers
- **C:** Google, Facebook, Apple, GitHub, Microsoft, Twitter definidos
- **V:** Verificar cada provider funciona con credenciales reales
---
### TAREA 2.3: Trading Services Completion
**Prioridad:** P0 | **CAPVED:** Full
**Depende de:** 2.1, 1.2.1 (symbols seed)
#### 2.3.1 Completar market.service.ts
- **C:** Klines, tickers, orderbook - parcialmente implementados
- **P:** Conectar a BD y/o Binance API
- **Archivos:** src/modules/trading/services/market.service.ts
#### 2.3.2 Completar order.service.ts
- **C:** Order execution logic incompleto
- **P:** Implementar create/cancel/fill para paper trading
- **Archivos:** src/modules/trading/services/order.service.ts
#### 2.3.3 Completar paper-trading.service.ts
- **C:** Paper trading simulation no conectada a BD
- **P:** Implementar con BD transactions
- **Archivos:** src/modules/trading/services/paper-trading.service.ts
#### 2.3.4 Integrar WebSocket en trading
- **C:** WS server existe, trading no lo usa
- **P:** Emitir price updates, order fills, position changes via WS
- **Archivos:** src/modules/trading/trading.websocket.ts
#### 2.3.5 Completar watchlist.service.ts
- **P:** CRUD completo con BD
- **Archivos:** src/modules/trading/services/watchlist.service.ts
#### 2.3.6 Completar alerts.service.ts
- **P:** Price alerts con persistence y trigger mechanism
- **Archivos:** src/modules/trading/services/alerts.service.ts
---
### TAREA 2.4: Remaining Backend Services
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** 2.1
#### 2.4.1 Education services (5 services)
- **C:** 60+ endpoints definidos, services parciales
- **P:** Completar course, enrollment, quiz, gamification, video services
- **Paralelizable:** SI (5 subagentes)
#### 2.4.2 Investment services
- **C:** 15 endpoints, implementacion minima
- **P:** Products, accounts, transactions, distributions, withdrawals
#### 2.4.3 Payments services (Stripe)
- **C:** 16 endpoints, Stripe integration started
- **P:** Completar Stripe webhook processing, subscription lifecycle
#### 2.4.4 Portfolio services
- **C:** 13 endpoints, parcial
- **P:** Portfolio CRUD, allocations, rebalancing, goals, snapshots
#### 2.4.5 Notifications services
- **C:** 8 endpoints, parcial
- **P:** Push notifications, preferences, mark read
#### 2.4.6 Admin services (conectar a BD real)
- **C:** Todo retorna MOCK data
- **P:** Conectar dashboard, users, audit a queries reales
#### 2.4.7 LLM services
- **C:** 5 endpoints, parcial
- **P:** Session persistence, chat history, quick analysis
---
## FASE 3: FRONTEND INTEGRATION
### TAREA 3.1: Service Layers Faltantes
**Prioridad:** P0 | **CAPVED:** Full
**Depende de:** Fase 2
#### 3.1.1 Crear auth.service.ts
- **C:** CRITICO - no existe
- **P:** Login, register, OAuth, token refresh, 2FA, sessions
- **V:** Login/register flow funcional
- **Archivos:** src/services/auth.service.ts
#### 3.1.2 Crear trading.service.ts
- **C:** CRITICO - no existe, pagina /trading crashea
- **P:** Klines, tickers, orderbook, orders, positions, paper trading
- **V:** Chart renderiza con datos reales
- **Archivos:** src/services/trading.service.ts
#### 3.1.3 Crear portfolio.service.ts
- **P:** CRUD portfolios, allocations, goals, performance
- **Archivos:** src/services/portfolio.service.ts
#### 3.1.4 Completar investment.service.ts
- **C:** Solo AccountDetail implementado
- **P:** Products, accounts, transactions, distributions, withdrawals
- **Archivos:** src/services/investment.service.ts
#### 3.1.5 Crear notifications.service.ts
- **P:** List, mark read, preferences, push token
- **Archivos:** src/services/notifications.service.ts
#### 3.1.6 Crear settings.service.ts
- **P:** User preferences, profile update, notification settings
- **Archivos:** src/services/settings.service.ts
---
### TAREA 3.2: Page Implementations
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** 3.1
#### 3.2.1 Portfolio pages (4 pages)
- PortfolioDashboard.tsx, CreatePortfolio.tsx, CreateGoal.tsx, EditAllocations.tsx
- **Depende de:** 3.1.3
#### 3.2.2 Investment pages (7 pages)
- Investment.tsx, Portfolio.tsx, Products.tsx, AccountDetail.tsx (existe), Withdrawals.tsx, Transactions.tsx, Reports.tsx
- **Depende de:** 3.1.4
#### 3.2.3 Settings pages
- Profile, Security, Notifications, Trading preferences
- **Depende de:** 3.1.6
#### 3.2.4 Dashboard page (real data)
- Conectar a backend APIs: portfolio summary, recent trades, ML signals
- **Depende de:** 3.1.1-3.1.5
#### 3.2.5 Notifications page
- NotificationCenter.tsx con list, mark read, filters
- **Depende de:** 3.1.5
#### 3.2.6 Assistant page (wrapper)
- AssistantPage.tsx wrapping chat components
- **Depende de:** Backend LLM service
---
### TAREA 3.3: Real Data Wiring
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** 3.1, 3.2
#### 3.3.1 Reemplazar mock data en Dashboard
#### 3.3.2 Reemplazar mock data en Trading stats/orderbook/alerts
#### 3.3.3 Conectar WebSocket para real-time prices
#### 3.3.4 Agregar Error Boundary global en App.tsx
#### 3.3.5 Crear .env.local con URLs de servicios
---
## FASE 4: ML & BACKTESTING (PARALELO con Fases 2-3)
### TAREA 4.1: Parametrizar OOS Dinamico
**Prioridad:** P0 | **CAPVED:** Full
#### 4.1.1 Modificar validation_oos.yaml para OOS dinamico
- **C:** Hardcoded 2025 como OOS period
- **P:** Parametrizar: OOS = max_date_in_db - 12 meses
- **Archivos:** config/validation_oos.yaml
#### 4.1.2 Actualizar TemporalDataSplitter
- **C:** Split dates hardcoded
- **P:** Calcular dinamicamente basado en datos disponibles
- **Archivos:** src/training/data_splitter.py
#### 4.1.3 Verificar datos en BD
- **V:** Contar registros por simbolo y rango de fechas
- **V:** Confirmar que existen datos 2023-2025 (minimo)
---
### TAREA 4.2: Entrenamiento Completo
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** 4.1, 1.3
#### 4.2.1 Entrenar Level 0 (Attention) para todos los symbols
- **Symbols:** XAUUSD, EURUSD, BTCUSD, GBPUSD, USDJPY, AUDUSD
- **Timeframes:** 5m, 15m
- **Output:** 12 modelos attention
- **V:** Attention score distribution reasonable
#### 4.2.2 Entrenar Level 1 (Base Models) para todos los symbols
- **Modelos:** RangePredictorV2, AMDDetectorML, MovementMagnitude
- **V:** R2 >= 0.4 para range, dir_accuracy >= 85%
#### 4.2.3 Entrenar Level 2 (Metamodels)
- **XGBoost:** Para EURUSD, BTCUSD, GBPUSD, USDJPY, AUDUSD
- **Neural Gating:** Para XAUUSD
- **V:** Improvement over single-timeframe models
#### 4.2.4 Guardar modelos y metadata
- **V:** Archivos .joblib/.pth guardados con metadata de entrenamiento
---
### TAREA 4.3: Backtesting y Validacion
**Prioridad:** P0 | **CAPVED:** Full
**Depende de:** 4.2
#### 4.3.1 Ejecutar OOS backtest (12 meses excluidos)
- **P:** Para cada symbol, ejecutar backtest en periodo OOS
- **Config:** Initial capital 10K, risk 2%, multiple R:R configs
- **V:** Resultados vs targets:
- Win Rate >= 75% (target 80%)
- Profit Factor >= 2.0 (target 4.0)
- Sharpe Ratio >= 1.5 (target 2.5)
- Max Drawdown <= 15%
#### 4.3.2 Walk-Forward Validation
- **P:** 5-fold walk-forward para cada symbol/model
- **V:** Consistencia entre folds (std < 10% del mean)
#### 4.3.3 Comparar estrategias
- **P:** R:R 2:1, R:R 3:1, R:R 1:2@80WR, Range Adaptive
- **V:** Identificar mejor estrategia por symbol
#### 4.3.4 Generar reporte de resultados
- **D:** Reporte con metricas por symbol, modelo, estrategia
- **Archivos:** reports/backtesting/OOS-REPORT-{date}.md
#### 4.3.5 Validar integracion ML Engine -> Backend
- **V:** POST /predict retorna signal correcta
- **V:** POST /hierarchical-predict retorna L0->L1->L2
#### 4.3.6 Validar integracion Backend -> Frontend
- **V:** ML Dashboard muestra signals reales
- **V:** Backtesting Dashboard ejecuta backtest real
---
## FASE 5: INTEGRATION TESTING
### TAREA 5.1: Backend API Tests
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** Fase 2
#### 5.1.1 Auth module tests (login, register, OAuth, 2FA)
#### 5.1.2 Trading module tests (orders, positions, paper trading)
#### 5.1.3 Education module tests (courses, enrollment, quizzes)
#### 5.1.4 Payments module tests (Stripe webhook, subscriptions)
#### 5.1.5 ML integration tests (signals, predictions)
#### 5.1.6 WebSocket tests (connection, subscription, broadcast)
---
### TAREA 5.2: Frontend E2E Tests
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** Fase 3
#### 5.2.1 Auth flow E2E (login -> dashboard)
#### 5.2.2 Trading flow E2E (chart -> order -> position)
#### 5.2.3 Education flow E2E (browse -> enroll -> lesson -> quiz)
#### 5.2.4 Payment flow E2E (pricing -> checkout -> subscription)
#### 5.2.5 ML Dashboard E2E (signals -> backtest)
---
### TAREA 5.3: ML Integration Tests
**Prioridad:** P1 | **CAPVED:** Full
**Depende de:** Fase 4
#### 5.3.1 Data pipeline test (DB -> features -> prediction)
#### 5.3.2 Backtesting reproducibility test
#### 5.3.3 Model serving latency test (<500ms per prediction)
---
## FASE 6: DOCUMENTACION & CLEANUP (PARALELO)
### TAREA 6.1: Purga de Documentacion
**Prioridad:** P1 | **Paralelizable:** SI | **CAPVED:** Quick
#### 6.1.1 Eliminar reportes obsoletos
```
ELIMINAR:
- orchestration/_archive/reportes/REPORTE-SESION-2025-12-07.md
- orchestration/_archive/reportes/REPORTE-EJECUCION-SPRINT{1,2,3}.md
- orchestration/_archive/reportes/VALIDACION-PLAN-VS-ANALISIS-2026-01-07.md
- docs/00-vision-general/NOTA-DISCREPANCIA-PUERTOS-2025-12-08.md
```
#### 6.1.2 Consolidar analisis obsoletos
```
MOVER a _archive/consolidated/:
- orchestration/_archive/analisis/ANALISIS-GAPS-ML-FIRST-2026-01.md
- orchestration/_archive/analisis/ANALISIS-DEPENDENCIAS-2026-01-07.md
- orchestration/_archive/analisis/ANALISIS-CONSOLIDADO-FASE1-2026-01-07.md
```
#### 6.1.3 Archivar planes superseded
```
MOVER a _archive/2026-01-planes/:
- orchestration/_archive/planes/ (todo el directorio)
```
---
### TAREA 6.2: Actualizacion de Definiciones
**Prioridad:** P1 | **CAPVED:** Full
#### 6.2.1 Actualizar PROJECT-STATUS.md
- Reflejar estado post Jan 25-27: 19 tareas completadas
- Actualizar metricas de completitud por modulo
#### 6.2.2 Actualizar PROXIMA-ACCION.md
- Apuntar a este plan maestro como referencia
- Definir siguiente tarea a ejecutar
#### 6.2.3 Actualizar PROJECT-PROFILE.yml
- Puertos corregidos (3083/3084/3085-3086)
- Frameworks corregidos (PyTorch/XGBoost)
- Schemas (10)
- Progreso OQI actualizado
#### 6.2.4 Crear user stories faltantes OQI-006 (ML)
- Actualmente 0 user stories
- Crear 8-10 US basadas en funcionalidad ML actual
#### 6.2.5 Crear user stories faltantes OQI-007 (LLM)
- Actualmente 0 user stories
- Crear 6-8 US basadas en funcionalidad LLM actual
#### 6.2.6 Actualizar API contracts document
- Documentar todos los 113+ endpoints con request/response schemas
- Sincronizar con Swagger
---
### TAREA 6.3: Inventarios Sync
**Prioridad:** P1 | **CAPVED:** Quick
#### 6.3.1 Sync MASTER_INVENTORY.yml con estado real
#### 6.3.2 Sync DATABASE_INVENTORY.yml (89 tablas)
#### 6.3.3 Sync BACKEND_INVENTORY.yml (113+ endpoints)
#### 6.3.4 Sync FRONTEND_INVENTORY.yml (189 components)
#### 6.3.5 Actualizar _INDEX.yml de tareas con esta nueva tarea
---
## ORDEN DE EJECUCION Y DEPENDENCIAS
```
PARALELO GRUPO A (sin dependencias):
├── 0.1 Correccion discrepancias ← Puede empezar YA
├── 0.2 Infraestructura WSL ← Puede empezar YA
├── 6.1 Purga documentacion ← Puede empezar YA
└── 4.1 Parametrizar OOS dinamico ← Puede empezar YA
SECUENCIAL GRUPO B (depende de 0.x):
1.1 DDL fixes → 1.2 Seeds → 1.3 Recrear BD
PARALELO GRUPO C (depende de 1.3):
├── 2.1 Entity layer → 2.2 Auth → 2.3 Trading → 2.4 Rest
└── 4.2 Entrenamiento ML (depende tambien de 4.1)
PARALELO GRUPO D (depende de 2.x):
├── 3.1 Frontend services → 3.2 Pages → 3.3 Wiring
└── 4.3 Backtesting (depende tambien de 4.2)
SECUENCIAL GRUPO E (depende de 2.x + 3.x + 4.x):
5.1 Backend tests → 5.2 Frontend E2E → 5.3 ML integration
PARALELO CONTINUO:
6.2 Actualizar definiciones (durante toda ejecucion)
6.3 Sync inventarios (al final de cada fase)
```
---
## DIAGRAMA DE DEPENDENCIAS
```
0.1 ──┐
0.2 ──┼──→ 1.1 ──→ 1.2 ──→ 1.3 ──┬──→ 2.1 ──→ 2.2 ──┬──→ 3.1 ──→ 3.2 ──→ 3.3
6.1 ──┘ │ 2.3 ──┤ 3.2.1-6
│ 2.4 ──┘
4.1 ──────────────────────────────┼──→ 4.2 ──→ 4.3 ──┐
│ │
└───────────────────┼──→ 5.1 ──→ 5.2 ──→ 5.3
6.2 ──────────────────────────────────────────────────┘
6.3 ──────────────────────────────────────────────────── (continuo)
```
---
## RESUMEN CUANTITATIVO
| Fase | Tareas | Subtareas | SubSubtareas | Prioridad |
|------|--------|-----------|--------------|-----------|
| 0 | 2 | 10 | 0 | P0 |
| 1 | 3 | 12 | 0 | P0 |
| 2 | 4 | 17 | 7+ | P0-P1 |
| 3 | 3 | 17 | 5+ | P0-P1 |
| 4 | 3 | 12 | 6 | P0-P1 |
| 5 | 3 | 14 | 0 | P1 |
| 6 | 3 | 11 | 0 | P1 |
| **TOTAL** | **21** | **93** | **18+** | |
**Total items de trabajo:** 132+ (21 tareas + 93 subtareas + 18+ sub-subtareas)
**Cada item cumple CAPVED** (Contexto, Analisis, Planeacion, Validacion, Ejecucion, Documentacion)
---
## CRITERIOS DE ACEPTACION GLOBALES
1. **DDL:** 89 tablas creadas, pgvector funcional, seeds ejecutados, 0 errors en recreacion
2. **Backend:** Todos los 113+ endpoints retornan datos reales (no mock), entity types match DDL
3. **Frontend:** Todas las rutas renderizan sin crash, services conectan a backend real
4. **ML:** Backtesting OOS ejecutado para 6 symbols, metricas documentadas, WR >= 75%
5. **Infra:** trading-platform en LOCAL-WSL-ENVIRONMENT, BD recreable, Docker compose up funcional
6. **Docs:** 0 archivos obsoletos, inventarios 100% sync, progreso OQI actualizado
7. **Coherencia:** DDL->Backend->Frontend pipeline verificado para los 10 schemas
---
## NOTAS DE EJECUCION
### Subagentes Recomendados por Fase
- **Fase 0:** 2 agentes Quick (discrepancias + infra)
- **Fase 1:** 1 agente DDL + 1 agente Seeds (paralelo)
- **Fase 2:** 4 agentes (entity layer + auth + trading + rest) semi-paralelo
- **Fase 3:** 3 agentes (services + pages + wiring) secuencial
- **Fase 4:** 2 agentes (training + backtesting) secuencial
- **Fase 5:** 3 agentes testing (paralelo por capa)
- **Fase 6:** 2 agentes docs (paralelo)
### Perfiles de Agentes
| Agente | Perfil | Tareas |
|--------|--------|--------|
| Claude Code | Tech-Leader/Architect | Orquestacion, decisiones arquitectonicas |
| Subagente 1 | Backend-Developer | Fase 2 (entities, services) |
| Subagente 2 | Frontend-Developer | Fase 3 (services, pages, wiring) |
| Subagente 3 | ML-Specialist | Fase 4 (training, backtesting) |
| Subagente 4 | QA-Engineer | Fase 5 (tests) |
| Subagente 5 | DevOps/Infra | Fase 0.2, 1.3 (WSL, BD recreation) |
| Subagente 6 | Documentation | Fase 6 (purga, updates) |

View File

@ -0,0 +1,45 @@
# METADATA.yml - TASK-2026-01-27-MASTER-ANALYSIS-PLAN
version: "1.0.0"
proyecto: trading-platform
tipo: ANALYSIS
modo: "@ANALYSIS"
prioridad: P0
tarea:
id: "TASK-2026-01-27-MASTER-ANALYSIS-PLAN"
titulo: "Analisis Maestro Integral y Plan de Ejecucion - Trading Platform"
descripcion: |
Analisis exhaustivo de todas las capas del proyecto trading-platform:
DDL, seeds, backend, frontend, ML engine, backtesting, integraciones,
documentacion, y alineacion con WSL/infraestructura.
Incluye plan de ejecucion jerarquico con dependencias.
estado: EN_PROGRESO
fecha_inicio: "2026-01-27"
agente: "Claude Code (Opus 4.5)"
perfil: "Tech-Leader + Architect"
fases_capved:
C: COMPLETADA
A: COMPLETADA
P: EN_PROGRESO
V: PENDIENTE
E: PENDIENTE
D: PENDIENTE
entregables:
- METADATA.yml
- 01-CONTEXTO.md
- 02-ANALISIS-HALLAZGOS.md
- 03-PLAN-MAESTRO-JERARQUICO.md
areas_cubiertas:
- DDL completeness (89 tables, 10 schemas)
- Seeds vs triggers/functions redundancy
- Backend-Frontend coherence (113+ endpoints)
- ML training pipeline & backtesting (12-month OOS)
- WSL/infrastructure alignment
- Documentation cleanup/purge
- Definition completeness (9 OQI modules)
- Cross-layer coherence validation
subagentes_utilizados: 8