--- id: "ARQUITECTURA-UNIFICADA" title: "Arquitectura Unificada - OrbiQuant IA Trading Platform" type: "Documentation" project: "trading-platform" version: "1.0.0" updated_date: "2026-01-04" --- # Arquitectura Unificada - OrbiQuant IA Trading Platform **Versión:** 2.0.0 **Última actualización:** 2025-12-05 **Estado:** Aprobado --- ## Resumen Ejecutivo Este documento define la arquitectura completa de OrbiQuant IA, integrando el sistema TradingAgent existente con la nueva plataforma de trading. Define cómo interactúan todos los componentes para ofrecer una experiencia completa de Money Manager con IA. --- ## Visión de Arquitectura ``` ┌─────────────────────────────────────────────────────────────────────────────────────────────────┐ │ ORBIQUANT IA PLATFORM │ │ │ │ ┌─────────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ FRONTEND LAYER │ │ │ │ (React 18 + TypeScript) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌───────────┐ │ │ │ │ │ Auth UI │ │ Education │ │ TradingView │ │ Money │ │ LLM │ │ │ │ │ │ OAuth │ │ Platform │ │ Clone │ │ Manager │ │ Chat │ │ │ │ │ │ Login │ │ Courses │ │ Charts+ML │ │ Dashboard │ │ Agent │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ └───────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────────────────────────────────▼───────────────────────────────────────────────┐ │ │ │ API GATEWAY │ │ │ │ (Express.js + TypeScript) │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ │ │ Auth │ │ Education│ │ Trading │ │Investment│ │ Payments │ │ ML Proxy │ │ │ │ │ │ Routes │ │ Routes │ │ Routes │ │ Routes │ │ Routes │ │ Routes │ │ │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ SHARED SERVICES │ │ │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐│ │ │ │ │ │ │ Auth │ │ Rate │ │ WebSocket │ │ ML Integration ││ │ │ │ │ │ │ Middleware │ │ Limiter │ │ Manager │ │ Service ││ │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────────────────┘│ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ └───────────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────────────────────────────────▼───────────────────────────────────────────────┐ │ │ │ CORE SERVICES LAYER │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ ML ENGINE (Python/FastAPI) │ │ │ │ │ │ [REUTILIZA TradingAgent EXISTENTE] │ │ │ │ │ │ ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ PREDICTION LAYER │ │ │ │ │ │ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────────────────┐ │ │ │ │ │ │ │ │ │ XGBoost │ │ GRU │ │Transformer │ │ Meta-Model │ │ │ │ │ │ │ │ │ │ GPU │ │ Attention │ │ Flash │ │ (Ensemble) │ │ │ │ │ │ │ │ │ └────────────┘ └────────────┘ └────────────┘ └────────────────────────┘ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ TRADING LAYER │ │ │ │ │ │ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────────────────┐ │ │ │ │ │ │ │ │ │ Range │ │ TPSL │ │ Signal │ │ AMD │ │ │ │ │ │ │ │ │ │ Predictor │ │ Classifier │ │ Generator │ │ Strategy │ │ │ │ │ │ │ │ │ │ (85.9%) │ │ (94% AUC) │ │ │ │ Detection │ │ │ │ │ │ │ │ │ └────────────┘ └────────────┘ └────────────┘ └────────────────────────┘ │ │ │ │ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ LLM STRATEGY AGENT (Claude/GPT) │ │ │ │ │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ ┌──────────────────┐ │ │ │ │ │ │ │ Conversation │ │ Tool │ │ Context │ │ Fine-tuning │ │ │ │ │ │ │ │ Manager │ │ Executor │ │ Builder │ │ Pipeline │ │ │ │ │ │ │ └────────────────┘ └────────────────┘ └────────────────┘ └──────────────────┘ │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ TRADING AGENTS (Execution) │ │ │ │ │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────────────────────┐│ │ │ │ │ │ │ ATLAS │ │ ORION │ │ NOVA ││ │ │ │ │ │ │ Conservative │ │ Moderate │ │ Aggressive ││ │ │ │ │ │ │ 3-5%/month │ │ 5-10%/month │ │ 10%+/month ││ │ │ │ │ │ │ Max DD: 5% │ │ Max DD: 10% │ │ Max DD: 20% ││ │ │ │ │ │ └────────────────┘ └────────────────┘ └────────────────────────────────────────┘│ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ PORTFOLIO MANAGER │ │ │ │ │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ ┌──────────────────┐ │ │ │ │ │ │ │ Allocator │ │ Rebalancer │ │ Distributor │ │ Projections │ │ │ │ │ │ │ │ │ │ │ │ │ │ Monte Carlo │ │ │ │ │ │ │ └────────────────┘ └────────────────┘ └────────────────┘ └──────────────────┘ │ │ │ │ │ └────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ └───────────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────────────────────────────────▼───────────────────────────────────────────────┐ │ │ │ DATA LAYER │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐ │ │ │ │ │ PostgreSQL │ │ Redis │ │ Binance │ │ Stripe │ │ S3/CDN │ │ │ │ │ │ Primary │ │ Cache + │ │ Exchange │ │ Payments │ │ Assets │ │ │ │ │ │ Database │ │ Pub/Sub │ │ API │ │ API │ │ │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────┘ │ │ │ └───────────────────────────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` --- ## Épicas del Sistema (8 Épicas - 400 SP Total) | Código | Épica | SP | Estado | Descripción | |--------|-------|-----|--------|-------------| | OQI-001 | Fundamentos y Auth | 50 | ✅ Completado | OAuth, JWT, 2FA | | OQI-002 | Módulo Educativo | 45 | Parcial | Cursos, quizzes, gamificación | | OQI-003 | Trading y Charts | 55 | Pendiente | TradingView clone con ML | | OQI-004 | Cuentas de Inversión | 57 | Pendiente | Money Manager con agentes | | OQI-005 | Pagos y Stripe | 40 | Parcial | Suscripciones, wallet | | OQI-006 | Señales ML | 40 | ML Engine listo | Predicciones, señales | | **OQI-007** | **LLM Agent** | **55** | **Nuevo** | **Copiloto de trading IA** | | **OQI-008** | **Portfolio Manager** | **65** | **Nuevo** | **Gestión de carteras** | **Total: 407 Story Points** --- ## Flujos de Datos Principales ### 1. Flujo de Predicción ML ``` ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Binance │───▶│ Redis │───▶│ Feature │───▶│ Models │───▶│ Signal │ │ API │ │ Cache │ │ Builder │ │ Ensemble │ │Generator │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ ┌─────────────────────────────────────────────────────────────────┘ │ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Redis │───▶│ Backend │───▶│WebSocket │───▶│ Frontend │ │ Pub/Sub │ │ Express │ │ Server │ │ React │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ ``` ### 2. Flujo de Trading Automático (Agentes) ``` ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ Signal │───▶│ Strategy │───▶│ Risk │───▶│ Order │ │Generator │ │ Router │ │ Manager │ │ Executor │ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ │ ┌───────────┼───────────┐ │ ▼ ▼ ▼ ▼ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌──────────┐ │ ATLAS │ │ ORION │ │ NOVA │ │ Exchange │ │ Agent │ │ Agent │ │ Agent │ │ Binance │ └─────────┘ └─────────┘ └─────────┘ └──────────┘ ``` ### 3. Flujo de LLM Agent ``` ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ User │───▶│ Chat │───▶│ Context │───▶│ LLM │ │ Query │ │ UI │ │ Builder │ │ Claude │ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ ┌─────────────────┼─────────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │get_signal│ │ analyze │ │ execute │ │ Tool │ │ _chart │ │ _trade │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ML Engine │ │ Market │ │ Order │ │ │ │ Data │ │ System │ └──────────┘ └──────────┘ └──────────┘ ``` ### 4. Flujo de Portfolio Management ``` ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ User │───▶│ Risk │───▶│Allocation│───▶│ Accounts │ │ Profile │ │ Profile │ │ Strategy │ │ Creation │ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘ │ ┌─────────────────────────────────────────────────┘ │ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │Rebalance │───▶│ Drift │───▶│ Execute │───▶│ Notify │ │ Engine │ │Detection │ │ Trades │ │ User │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ ▼ ┌──────────────┐ │ Distribution │ │ Monthly │ └──────────────┘ ``` --- ## Componentes por Capa ### Frontend (React 18 + TypeScript + Vite) | Módulo | Componentes Principales | |--------|------------------------| | Auth | Login, Register, OAuth, 2FA, Profile | | Education | CourseList, LessonPlayer, Quiz, Progress | | Trading | Chart (Lightweight), Watchlist, Orders, Positions | | Investment | ProductCard, AccountDashboard, Portfolio | | Payments | PlanSelector, Checkout, Wallet, Transactions | | ML | SignalCard, PredictionOverlay, IndicatorPanel | | LLM | ChatWindow, MessageList, ToolResults | | Portfolio | AllocationChart, RebalanceModal, GoalsTracker | ### Backend (Express.js + TypeScript) | Servicio | Responsabilidad | |----------|-----------------| | AuthService | OAuth, JWT, sessions, 2FA | | EducationService | Cursos, lecciones, progreso | | TradingService | Órdenes, posiciones, paper trading | | InvestmentService | Cuentas, depósitos, retiros | | PaymentService | Stripe, suscripciones, wallet | | MLIntegrationService | Proxy a ML Engine | | WebSocketService | Real-time updates | ### ML Engine (Python + FastAPI) - **TradingAgent** | Componente | Archivo Original | Función | |------------|------------------|---------| | XGBoost Model | `src/models/base/xgboost_model.py` | Predicción GPU | | GRU Model | `src/models/base/gru_model.py` | Secuencias con attention | | Transformer | `src/models/base/transformer_model.py` | Flash attention | | RangePredictor | `src/models/range_predictor.py` | Delta High/Low | | TPSLClassifier | `src/models/tp_sl_classifier.py` | Prob TP first | | SignalGenerator | `src/models/signal_generator.py` | Señales JSON | | AMDDetector | `src/strategies/amd_detector.py` | Fases de mercado | | Dashboard | `src/visualization/dashboard.py` | Charts real-time | ### LLM Agent Layer | Componente | Tecnología | |------------|------------| | LLM Provider | Claude 3.5 Sonnet / GPT-4 Turbo | | Orchestration | LangChain / Claude SDK | | Memory | Redis (conversation history) | | Vector Store | Pinecone (RAG context) | | Tools | Function calling nativo | ### Data Layer | Store | Tecnología | Uso | |-------|------------|-----| | Primary DB | PostgreSQL 15 | Datos transaccionales | | Cache | Redis 7 | Sessions, rate limits, pub/sub | | Market Data | Binance API | Precios real-time | | Payments | Stripe API | Procesamiento de pagos | | Files | S3 / Cloudflare R2 | Videos, assets | --- ## Modelo de Datos Unificado ### Diagrama ER Simplificado ``` ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ users │────<│subscriptions│ │ courses │ └─────────────┘ └─────────────┘ └──────┬──────┘ │ │ │ ┌─────────────┐ ┌─────┴─────┐ ├────<│ accounts │ │ lessons │ │ │ (investment)│ └───────────┘ │ └──────┬──────┘ │ │ │ ┌──────┴──────┐ ┌─────────────┐ │ │ trades │ │ signals │ │ └─────────────┘ └─────────────┘ │ │ ┌─────────────┐ ┌─────────────┐ └────<│ wallets │────<│transactions │ └─────────────┘ └─────────────┘ ``` ### Schemas Principales ```sql -- Usuario y autenticación users (id, email, password_hash, plan, created_at) sessions (id, user_id, token, expires_at) oauth_connections (id, user_id, provider, provider_id) -- Educación courses (id, title, description, difficulty, price) lessons (id, course_id, title, type, content_url) enrollments (id, user_id, course_id, progress) quiz_results (id, user_id, lesson_id, score) -- Trading watchlists (id, user_id, symbols[]) paper_accounts (id, user_id, balance, equity) paper_trades (id, account_id, symbol, side, quantity, price) -- Investment (Money Manager) investment_products (id, name, risk_profile, target_return) investment_accounts (id, user_id, product_id, balance, status) investment_trades (id, account_id, symbol, side, pnl) distributions (id, account_id, amount, paid_at) -- Pagos stripe_customers (id, user_id, stripe_customer_id) subscriptions (id, user_id, plan, status, current_period_end) wallets (id, user_id, balance) transactions (id, wallet_id, type, amount, status) -- ML/Signals predictions (id, symbol, horizon, predicted_high, predicted_low) signals (id, symbol, type, confidence, created_at) signal_outcomes (id, signal_id, result, pnl) -- LLM Agent conversations (id, user_id, created_at) messages (id, conversation_id, role, content, tools_used) -- Portfolio Manager risk_profiles (id, user_id, answers, profile_type) portfolio_allocations (id, user_id, atlas_pct, orion_pct, nova_pct) rebalance_events (id, user_id, from_allocation, to_allocation) investment_goals (id, user_id, name, target_amount, deadline) ``` --- ## APIs y Endpoints ### Backend Express (Puerto 3001) ``` # Auth POST /api/auth/register POST /api/auth/login POST /api/auth/oauth/:provider POST /api/auth/logout POST /api/auth/2fa/setup POST /api/auth/2fa/verify # Education GET /api/courses GET /api/courses/:id POST /api/courses/:id/enroll GET /api/lessons/:id POST /api/lessons/:id/complete POST /api/quizzes/:id/submit # Trading GET /api/trading/symbols GET /api/trading/chart/:symbol WS /api/trading/stream/:symbol POST /api/trading/paper/order GET /api/trading/paper/positions # Investment GET /api/investment/products POST /api/investment/accounts GET /api/investment/accounts/:id POST /api/investment/deposits POST /api/investment/withdrawals GET /api/investment/portfolio # Payments GET /api/payments/plans POST /api/payments/subscribe POST /api/payments/wallet/deposit POST /api/payments/wallet/withdraw GET /api/payments/transactions # ML Proxy GET /api/ml/signals/:symbol GET /api/ml/predictions/:symbol GET /api/ml/indicators/:symbol # LLM Agent POST /api/agent/chat GET /api/agent/conversations GET /api/agent/conversations/:id # Portfolio Manager POST /api/portfolio/profile GET /api/portfolio/allocation POST /api/portfolio/rebalance GET /api/portfolio/projections POST /api/portfolio/goals ``` ### ML Engine FastAPI (Puerto 8000) ``` # Predictions (TradingAgent) POST /predictions GET /predictions/history/:symbol # Signals POST /signals GET /signals/history # Indicators GET /indicators/:symbol # Models GET /models/status GET /models/:name/metrics # Health GET /health GET /health/detailed # WebSocket WS /ws/:symbol ``` --- ## Seguridad ### Autenticación | Método | Uso | |--------|-----| | JWT | Access tokens (15 min) | | Refresh Token | Renovación (7 días) | | OAuth 2.0 | Google, Facebook, Apple, GitHub | | 2FA | TOTP con Google Authenticator | | API Keys | ML Engine authentication | ### Autorización ```typescript // Roles y permisos enum Plan { FREE = 'free', BASIC = 'basic', PRO = 'pro', PREMIUM = 'premium' } // Middleware de autorización const requirePlan = (minPlan: Plan) => { return (req, res, next) => { if (planLevel(req.user.plan) < planLevel(minPlan)) { return res.status(403).json({ error: 'Upgrade required' }); } next(); }; }; ``` ### Rate Limiting | Endpoint | Free | Basic | Pro | Premium | |----------|------|-------|-----|---------| | /api/ml/* | 3/día | 10/día | 100/día | Ilimitado | | /api/agent/* | 10/día | 50/día | 200/día | Ilimitado | | /api/trading/* | 10/min | 30/min | 100/min | 300/min | --- ## Deployment ### Infraestructura ``` ┌─────────────────────────────────────────────────────────────────┐ │ PRODUCTION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Cloudflare │ │ │ │ (CDN + DDoS + SSL) │ │ │ └────────────────────────┬─────────────────────────────────┘ │ │ │ │ │ ┌────────────────────────▼─────────────────────────────────┐ │ │ │ Load Balancer │ │ │ │ (Nginx/HAProxy) │ │ │ └────────────┬───────────────────────────┬─────────────────┘ │ │ │ │ │ │ ┌────────────▼────────────┐ ┌───────────▼────────────────┐ │ │ │ Backend Cluster │ │ ML Engine Cluster │ │ │ │ (Express x 3) │ │ (FastAPI x 2) │ │ │ │ Port: 3001 │ │ Port: 8000 │ │ │ │ Node.js 20 │ │ Python 3.11 │ │ │ └────────────┬────────────┘ └───────────┬────────────────┘ │ │ │ │ │ │ ┌────────────▼───────────────────────────▼────────────────┐ │ │ │ Data Layer │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ PostgreSQL │ │ Redis │ │ S3/R2 │ │ │ │ │ │ Primary │ │ Cluster │ │ Storage │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ └──────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` ### Docker Compose (Desarrollo) ```yaml version: '3.8' services: frontend: build: ./apps/frontend ports: - "3000:3000" environment: - VITE_API_URL=http://localhost:3001 backend: build: ./apps/backend ports: - "3001:3001" environment: - DATABASE_URL=postgresql://... - REDIS_URL=redis://redis:6379 - ML_ENGINE_URL=http://ml-engine:8000 depends_on: - postgres - redis - ml-engine ml-engine: build: ./apps/ml-engine ports: - "8000:8000" environment: - REDIS_URL=redis://redis:6379 volumes: - ./models:/app/models deploy: resources: reservations: devices: - capabilities: [gpu] postgres: image: postgres:15 ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:7-alpine ports: - "6379:6379" volumes: postgres_data: ``` --- ## Roadmap de Implementación ### Fase 1: Fundamentos (Sprints 1-4) ✅ - OQI-001: Autenticación completa - OQI-002: Educación básica - OQI-005: Pagos y suscripciones ### Fase 2: Trading Core (Sprints 5-8) - OQI-003: Trading y Charts - OQI-004: Cuentas de Inversión - OQI-006: Integración ML Engine ### Fase 3: IA Avanzada (Sprints 9-11) - OQI-007: LLM Strategy Agent - Agentes de trading automático ### Fase 4: Portfolio Pro (Sprints 12-14) - OQI-008: Portfolio Manager - Rebalanceo y distribuciones - Proyecciones Monte Carlo ### Fase 5: Producción (Sprints 15-16) - Testing E2E completo - Security audit - Performance optimization - Launch --- ## Referencias - [TradingAgent Source]([LEGACY: apps/ml-engine - migrado desde TradingAgent]/) - [CONTEXTO-PROYECTO](../../../orchestration/00-guidelines/CONTEXTO-PROYECTO.md) - [OQI-001 a OQI-008](../02-definicion-modulos/)