# ============================================================================
# MATRIZ-DEPENDENCIAS.yml - Trading Platform Trading Platform
# ============================================================================
# Proposito: Mapa completo de dependencias entre todos los componentes
# Ultima actualizacion: 2025-12-05
# Version: 1.0.0
# ============================================================================

version: "1.0.0"
project: "Trading Platform Trading Platform"
last_updated: "2025-12-05"

# ============================================================================
# DEPENDENCIAS POR COMPONENTE
# ============================================================================

components:
  # --------------------------------------------------------------------------
  # FRONTEND
  # --------------------------------------------------------------------------
  frontend:
    name: "Frontend Web App"
    tech_stack: "React 18 + TypeScript + Vite"
    port: 3000

    depends_on:
      services:
        - backend-api

      external:
        - stripe-js
        - tradingview-lightweight-charts
        - claude-code-widgets

    integrations:
      - name: backend-api
        protocol: REST + WebSocket
        endpoints:
          - /auth/*
          - /education/*
          - /trading/*
          - /investment/*
          - /payments/*
          - /ml/*
          - /agent/*

      - name: stripe-checkout
        protocol: HTTPS
        usage: "Hosted checkout page"

      - name: websocket-server
        protocol: WSS
        channels:
          - ticker:{symbol}
          - signals:{symbol}
          - user:{id}:trades
          - chat:{conversation_id}

    environment_variables:
      - VITE_API_URL: "http://localhost:3001"
      - VITE_WS_URL: "ws://localhost:3001"
      - VITE_STRIPE_PUBLIC_KEY: "pk_test_..."

    deploys_to:
      - cloudflare-pages
      - vercel
      - netlify

    criticidad: ALTA
    epic_mapping: [OQI-001, OQI-002, OQI-003, OQI-004, OQI-005, OQI-006, OQI-007, OQI-008]

  # --------------------------------------------------------------------------
  # BACKEND API
  # --------------------------------------------------------------------------
  backend-api:
    name: "Backend API (Express.js)"
    tech_stack: "Express.js + TypeScript + Node.js 20"
    port: 3001

    depends_on:
      databases:
        - postgresql
        - redis

      services:
        - ml-engine
        - data-service

      external:
        - stripe-api
        - claude-api
        - twilio-api

    integrations:
      - name: postgresql
        protocol: TCP (libpq)
        port: 5432
        schemas:
          - public
          - education
          - trading
          - investment
          - financial
          - ml
          - audit

      - name: redis
        protocol: TCP (RESP)
        port: 6379
        usage:
          - "Session storage"
          - "Rate limiting"
          - "Cache (predictions, prices)"
          - "Pub/Sub (signals, trades)"

      - name: ml-engine
        protocol: HTTP (REST)
        port: 8000
        endpoints:
          - POST /predictions
          - POST /signals
          - GET /indicators

      - name: stripe-api
        protocol: HTTPS
        endpoints:
          - POST /v1/checkout/sessions
          - POST /v1/customers
          - POST /v1/subscriptions
        webhooks:
          - checkout.session.completed
          - invoice.payment_succeeded
          - customer.subscription.deleted

      - name: claude-api
        protocol: HTTPS
        endpoint: "https://api.anthropic.com/v1/messages"
        usage: "LLM Agent (OQI-007)"

    environment_variables:
      - DATABASE_URL: "postgresql://..."
      - REDIS_URL: "redis://..."
      - JWT_SECRET: "..."
      - STRIPE_SECRET_KEY: "sk_test_..."
      - STRIPE_WEBHOOK_SECRET: "whsec_..."
      - ML_ENGINE_URL: "http://ml-engine:8000"
      - CLAUDE_API_KEY: "sk-ant-..."
      - TWILIO_ACCOUNT_SID: "..."
      - TWILIO_AUTH_TOKEN: "..."

    modules:
      - auth
      - users
      - education
      - trading
      - investment
      - payments
      - admin
      - llm-agent

    criticidad: CRITICA
    epic_mapping: [OQI-001, OQI-002, OQI-003, OQI-004, OQI-005, OQI-006, OQI-007, OQI-008]

  # --------------------------------------------------------------------------
  # ML ENGINE
  # --------------------------------------------------------------------------
  ml-engine:
    name: "ML Engine (TradingAgent)"
    tech_stack: "Python 3.11 + FastAPI + XGBoost"
    port: 8000

    depends_on:
      databases:
        - postgresql
        - redis

      services:
        - data-service

      hardware:
        - nvidia-gpu

    integrations:
      - name: postgresql
        protocol: TCP (asyncpg)
        port: 5432
        schemas:
          - market_data
          - ml_predictions
          - ml
        usage:
          - "Read OHLCV data for features"
          - "Write predictions"
          - "Write signals"

      - name: redis
        protocol: TCP (aioredis)
        port: 6379
        usage:
          - "Cache predictions (TTL 5min)"
          - "Publish signals to channel signals:{symbol}"

      - name: data-service
        protocol: HTTP
        port: 8001
        dependency: "Requires fresh OHLCV data"

    models:
      - name: "XGBoost Range Predictor"
        files:
          - models/phase2/range_predictor/15m/model_high.json
          - models/phase2/range_predictor/15m/model_low.json
        metrics:
          mae: 0.0024
          accuracy: 0.693

      - name: "TPSL Classifier"
        files:
          - models/phase2/tpsl_classifier/15m_rr_2_1.json
          - models/phase2/tpsl_classifier/15m_rr_3_1.json
        metrics:
          auc: 0.94

      - name: "AMD Detector"
        source: src/strategies/amd_detector.py
        phases: [accumulation, manipulation, distribution, unknown]

    environment_variables:
      - DATABASE_URL: "postgresql://..."
      - REDIS_URL: "redis://..."
      - MODEL_PATH: "/app/models"
      - CUDA_VISIBLE_DEVICES: "0"
      - SUPPORTED_SYMBOLS: "BTCUSDT,ETHUSDT,XAUUSD"

    criticidad: CRITICA
    epic_mapping: [OQI-006]

  # --------------------------------------------------------------------------
  # DATA SERVICE
  # --------------------------------------------------------------------------
  data-service:
    name: "Data Service (Sync + Spreads)"
    tech_stack: "Python 3.11 + APScheduler"
    port: 8001

    depends_on:
      databases:
        - postgresql

      external:
        - polygon-api
        - metaapi

    integrations:
      - name: postgresql
        protocol: TCP (asyncpg)
        port: 5432
        schemas:
          - market_data
          - data_sources
          - broker_integration
        usage:
          - "Insert OHLCV from Polygon"
          - "Track sync status"
          - "Log spreads from MT4"

      - name: polygon-api
        protocol: HTTPS
        endpoint: "https://api.polygon.io"
        endpoints:
          - GET /v2/aggs/ticker/{ticker}/range/5/minute/{from}/{to}
          - GET /v2/snapshot/locale/global/markets/forex/tickers/{ticker}
        rate_limit: "5 req/min (basic plan)"

      - name: metaapi
        protocol: HTTPS + WebSocket
        endpoint: "https://mt-client-api-v1.new-york.agiliumtrade.ai"
        usage:
          - "Get broker prices (bid/ask)"
          - "Execute trades"
          - "Track spread statistics"

    scheduled_jobs:
      - name: "sync_ohlcv_5m"
        schedule: "*/5 * * * *"
        description: "Sincronizar datos cada 5 minutos"

      - name: "calculate_spreads_daily"
        schedule: "0 0 * * *"
        description: "Calcular estadisticas de spread diarias"

      - name: "backfill_historical"
        schedule: "Manual"
        description: "Rellenar datos historicos"

    environment_variables:
      - DATABASE_URL: "postgresql://..."
      - POLYGON_API_KEY: "..."
      - METAAPI_TOKEN: "..."
      - METAAPI_ACCOUNT_ID: "..."
      - SYNC_INTERVAL_MINUTES: "5"

    criticidad: ALTA
    epic_mapping: [OQI-006, OQI-008]

  # --------------------------------------------------------------------------
  # POSTGRESQL
  # --------------------------------------------------------------------------
  postgresql:
    name: "PostgreSQL Primary Database"
    tech_stack: "PostgreSQL 15"
    port: 5432

    depends_on:
      external:
        - backup-storage

    schemas:
      - name: public
        tables: 7
        purpose: "Usuarios, perfiles, sesiones"

      - name: education
        tables: 11
        purpose: "Cursos, lecciones, quizzes"

      - name: trading
        tables: 10
        purpose: "Bots, signals, paper trading"

      - name: investment
        tables: 8
        purpose: "Cuentas de inversion, productos"

      - name: financial
        tables: 11
        purpose: "Pagos, suscripciones, wallets"

      - name: ml
        tables: 8
        purpose: "Modelos, predicciones, metricas"

      - name: audit
        tables: 7
        purpose: "Logs de auditoria"

      - name: market_data
        tables: 4
        purpose: "OHLCV, indicadores tecnicos"
        partitioned: true

      - name: ml_predictions
        tables: 3
        purpose: "Predicciones, senales"

      - name: data_sources
        tables: 3
        purpose: "Configuracion de APIs externas"

      - name: broker_integration
        tables: 5
        purpose: "Integracion con MT4/MT5"

    extensions:
      - uuid-ossp
      - pgcrypto
      - pg_trgm

    backup_strategy:
      full_backup: "Daily 2am"
      incremental: "Every 6 hours"
      retention: "30 days"
      destination: "S3/Cloudflare R2"

    replication:
      type: "Streaming replication"
      replicas: 1
      lag_threshold: "5s"

    environment_variables:
      - POSTGRES_DB: "trading_platform"
      - POSTGRES_USER: "trading_user"
      - POSTGRES_PASSWORD: "..."

    criticidad: CRITICA
    epic_mapping: [OQI-001, OQI-002, OQI-003, OQI-004, OQI-005, OQI-006, OQI-007, OQI-008]

  # --------------------------------------------------------------------------
  # REDIS
  # --------------------------------------------------------------------------
  redis:
    name: "Redis Cache + Pub/Sub"
    tech_stack: "Redis 7"
    port: 6379

    depends_on: []

    use_cases:
      - name: "Session storage"
        pattern: "session:{userId}:{sessionId}"
        ttl: "7 days"

      - name: "Rate limiting"
        pattern: "ratelimit:{ip}:{endpoint}"
        ttl: "15 minutes"

      - name: "ML predictions cache"
        pattern: "ml:prediction:{symbol}:{horizon}"
        ttl: "5 minutes"

      - name: "Real-time prices"
        pattern: "realtime:{symbol}"
        ttl: "1 second"

      - name: "Pub/Sub signals"
        channels:
          - signals:{symbol}
          - trades:{user_id}

    persistence:
      enabled: true
      strategy: "RDB + AOF"
      snapshot: "Every 1 hour"

    environment_variables:
      - REDIS_PASSWORD: "..."
      - REDIS_MAXMEMORY: "2gb"
      - REDIS_MAXMEMORY_POLICY: "allkeys-lru"

    criticidad: ALTA
    epic_mapping: [OQI-001, OQI-003, OQI-006]

# ============================================================================
# DEPENDENCIAS EXTERNAS
# ============================================================================

external_services:
  # --------------------------------------------------------------------------
  # STRIPE
  # --------------------------------------------------------------------------
  - name: stripe-api
    provider: "Stripe"
    purpose: "Procesamiento de pagos y suscripciones"
    protocol: HTTPS
    endpoint: "https://api.stripe.com"

    used_by:
      - backend-api
      - frontend (Stripe.js)

    webhooks:
      endpoint: "https://api.trading.com/payments/webhook"
      events:
        - checkout.session.completed
        - invoice.payment_succeeded
        - invoice.payment_failed
        - customer.subscription.deleted

    api_keys:
      - STRIPE_SECRET_KEY (backend)
      - STRIPE_PUBLIC_KEY (frontend)
      - STRIPE_WEBHOOK_SECRET (webhook verification)

    pricing: "$0.029 + 2.9% per transaction"
    epic_mapping: [OQI-005]

  # --------------------------------------------------------------------------
  # CLAUDE API
  # --------------------------------------------------------------------------
  - name: claude-api
    provider: "Anthropic"
    purpose: "LLM Strategy Agent"
    protocol: HTTPS
    endpoint: "https://api.anthropic.com/v1/messages"

    used_by:
      - backend-api (LLM Service)

    model: "claude-3-5-sonnet-20250929"

    features:
      - Function calling (tools)
      - Streaming responses
      - Vision (future)

    rate_limits:
      - "50 req/min (tier 1)"
      - "500k tokens/min"

    api_keys:
      - CLAUDE_API_KEY

    pricing: "$0.003/1k input tokens, $0.015/1k output tokens"
    epic_mapping: [OQI-007]

  # --------------------------------------------------------------------------
  # POLYGON.IO
  # --------------------------------------------------------------------------
  - name: polygon-api
    provider: "Polygon.io"
    purpose: "Market data (Forex, Crypto, Stocks)"
    protocol: HTTPS
    endpoint: "https://api.polygon.io"

    used_by:
      - data-service

    plans:
      - name: "Currencies Basic"
        price: "$0/month"
        rate_limit: "5 req/min"

      - name: "Currencies Starter"
        price: "$29/month"
        rate_limit: "100 req/min"

    api_keys:
      - POLYGON_API_KEY

    epic_mapping: [OQI-006]

  # --------------------------------------------------------------------------
  # METAAPI
  # --------------------------------------------------------------------------
  - name: metaapi
    provider: "MetaAPI.cloud"
    purpose: "MT4/MT5 broker integration"
    protocol: HTTPS + WebSocket
    endpoint: "https://mt-client-api-v1.new-york.agiliumtrade.ai"

    used_by:
      - data-service
      - ml-engine (indirectly)

    features:
      - Cloud MT4 (no terminal needed)
      - REST API + WebSocket
      - Trade execution
      - Price streaming

    plans:
      - name: "Free"
        price: "$0/month"
        accounts: 1

      - name: "Premium"
        price: "$49/month"
        accounts: 10

    api_keys:
      - METAAPI_TOKEN
      - METAAPI_ACCOUNT_ID

    epic_mapping: [OQI-004, OQI-006, OQI-008]

  # --------------------------------------------------------------------------
  # TWILIO
  # --------------------------------------------------------------------------
  - name: twilio-api
    provider: "Twilio"
    purpose: "SMS, WhatsApp OTP"
    protocol: HTTPS
    endpoint: "https://api.twilio.com"

    used_by:
      - backend-api (Phone verification)

    features:
      - SMS sending
      - WhatsApp Business API
      - Verify API (OTP)

    api_keys:
      - TWILIO_ACCOUNT_SID
      - TWILIO_AUTH_TOKEN

    pricing: "$0.0075 per SMS"
    epic_mapping: [OQI-001]

# ============================================================================
# DEPENDENCIAS DE DESARROLLO
# ============================================================================

development:
  # --------------------------------------------------------------------------
  # DOCKER
  # --------------------------------------------------------------------------
  - name: docker-compose
    purpose: "Orquestacion de servicios locales"
    file: "docker-compose.yml"

    services:
      - frontend (port 3000)
      - backend (port 3001)
      - ml-engine (port 8000)
      - data-service (port 8001)
      - postgresql (port 5432)
      - redis (port 6379)

    networks:
      - trading-network

    volumes:
      - postgres_data
      - redis_data
      - ml_models

  # --------------------------------------------------------------------------
  # JENKINS
  # --------------------------------------------------------------------------
  - name: jenkins
    purpose: "CI/CD pipeline"

    pipelines:
      - name: "frontend-build"
        trigger: "Push to main"
        steps:
          - npm install
          - npm run build
          - npm run test
          - Deploy to Cloudflare Pages

      - name: "backend-build"
        trigger: "Push to main"
        steps:
          - npm install
          - npm run build
          - npm run test
          - Build Docker image
          - Push to registry
          - Deploy to production

      - name: "ml-engine-deploy"
        trigger: "Manual"
        steps:
          - pip install -r requirements.txt
          - pytest tests/
          - Build Docker image (GPU)
          - Deploy to GPU instance

      - name: "database-migration"
        trigger: "Manual"
        steps:
          - Backup database
          - Run migrations
          - Verify schema

# ============================================================================
# DEPENDENCIAS POR EPICA
# ============================================================================

epic_dependencies:
  OQI-001:
    name: "Fundamentos y Auth"
    status: "Completado"
    depends_on: []
    blocks:
      - OQI-002
      - OQI-003
      - OQI-004
      - OQI-005

    components:
      - frontend (Auth UI)
      - backend-api (Auth module)
      - postgresql (public schema)
      - redis (sessions)
      - stripe-api (customer creation)

    external_apis:
      - Google OAuth
      - Facebook OAuth
      - Apple OAuth
      - GitHub OAuth
      - Twilio (SMS)

  OQI-002:
    name: "Modulo Educativo"
    status: "En Progreso"
    depends_on:
      - OQI-001
    blocks:
      - OQI-007

    components:
      - frontend (Education pages)
      - backend-api (Education module)
      - postgresql (education schema)

    external_apis:
      - YouTube API (embeds)
      - Vimeo API (optional)

  OQI-003:
    name: "Trading y Charts"
    status: "Pendiente"
    depends_on:
      - OQI-001
    blocks:
      - OQI-006
      - OQI-007

    components:
      - frontend (Chart component)
      - backend-api (Trading module)
      - postgresql (trading schema, market_data)
      - redis (WebSocket pub/sub)
      - data-service

    external_apis:
      - Polygon.io (historical data)

  OQI-004:
    name: "Cuentas de Inversion"
    status: "Pendiente"
    depends_on:
      - OQI-001
      - OQI-005
    blocks:
      - OQI-006
      - OQI-008

    components:
      - frontend (Investment dashboard)
      - backend-api (Investment module)
      - postgresql (investment schema)
      - metaapi

    external_apis:
      - MetaAPI (broker connection)

  OQI-005:
    name: "Pagos y Stripe"
    status: "Pendiente"
    depends_on:
      - OQI-001
    blocks:
      - OQI-004

    components:
      - frontend (Checkout UI)
      - backend-api (Payment module)
      - postgresql (financial schema)
      - stripe-api

    webhooks:
      - Stripe webhook handler

  OQI-006:
    name: "ML Signals"
    status: "Pendiente"
    depends_on:
      - OQI-003
      - OQI-004
    blocks:
      - OQI-007
      - OQI-008

    components:
      - frontend (Signal cards)
      - backend-api (ML proxy)
      - ml-engine
      - data-service
      - postgresql (ml, ml_predictions schemas)
      - redis (cache, pub/sub)

    external_apis:
      - Polygon.io (data source)
      - MetaAPI (broker prices)

  OQI-007:
    name: "LLM Strategy Agent"
    status: "Pendiente"
    depends_on:
      - OQI-002
      - OQI-003
      - OQI-006
    blocks: []

    components:
      - frontend (Chat UI)
      - backend-api (LLM module)
      - ml-engine (tools)
      - postgresql (llm schema - future)
      - redis (conversation cache)
      - claude-api

    tools:
      - get_ml_signal
      - analyze_chart
      - execute_paper_trade
      - search_education

  OQI-008:
    name: "Portfolio Manager"
    status: "Pendiente"
    depends_on:
      - OQI-004
      - OQI-006
    blocks: []

    components:
      - frontend (Portfolio dashboard)
      - backend-api (Portfolio module)
      - postgresql (investment schema)
      - ml-engine (projections)

    algorithms:
      - Rebalancing optimizer
      - Monte Carlo simulation
      - Risk metrics (Sharpe, Sortino)

# ============================================================================
# GRAFOS DE DEPENDENCIAS
# ============================================================================

dependency_graph:
  critical_path:
    - OQI-001 (Auth)
    - OQI-005 (Payments)
    - OQI-004 (Investment Accounts)
    - OQI-006 (ML Signals)
    - OQI-008 (Portfolio Manager)

  parallel_tracks:
    education_track:
      - OQI-001 (Auth)
      - OQI-002 (Education)
      - OQI-007 (LLM Agent)

    trading_track:
      - OQI-001 (Auth)
      - OQI-003 (Charts)
      - OQI-006 (ML Signals)
      - OQI-007 (LLM Agent)

# ============================================================================
# MATRIZ DE RIESGOS
# ============================================================================

risks:
  - risk_id: RISK-001
    description: "Fallo en ML Engine afecta senales"
    probability: MEDIA
    impact: ALTO
    mitigation: "Cache de predicciones en Redis (TTL 1h)"
    affected_epics: [OQI-006, OQI-007, OQI-008]

  - risk_id: RISK-002
    description: "Stripe webhook no llega"
    probability: BAJA
    impact: CRITICO
    mitigation: "Polling manual cada 5 min como fallback"
    affected_epics: [OQI-005]

  - risk_id: RISK-003
    description: "Rate limit de Polygon.io"
    probability: ALTA
    impact: MEDIO
    mitigation: "Usar datos MySQL legacy como fallback"
    affected_epics: [OQI-006]

  - risk_id: RISK-004
    description: "Claude API timeout/error"
    probability: MEDIA
    impact: MEDIO
    mitigation: "Respuestas template, fallback a GPT-4"
    affected_epics: [OQI-007]

  - risk_id: RISK-005
    description: "MetaAPI conexion falla"
    probability: MEDIA
    impact: ALTO
    mitigation: "Switch a modo investor (solo tracking)"
    affected_epics: [OQI-004, OQI-008]

# ============================================================================
# FIN DE MATRIZ DE DEPENDENCIAS
# ============================================================================
