# 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()` - 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**