# TRACEABILITY.yml - OQI-003 Trading y Charts
# Mapeo de requerimientos a implementación

version: "1.0.0"
epic: OQI-003
name: "Trading Charts y Paper Trading"
updated: "2025-12-05"
status: pending

# Resumen de trazabilidad
summary:
  total_requirements: 8
  total_specs: 8
  total_user_stories: 18
  total_files_to_implement: 50
  test_coverage: "TBD"
  story_points: 55

# Mapeo de Requerimientos Funcionales
requirements:
  RF-TRD-001:
    name: "Charts de Trading"
    status: pending
    specs:
      - ET-TRD-001
      - ET-TRD-005
    user_stories:
      - US-TRD-001
      - US-TRD-002
      - US-TRD-016
      - US-TRD-017
      - US-TRD-018
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/market-data.service.ts
          description: "Servicio de datos de mercado"
          methods:
            - getSymbols
            - getCandles
            - getTicker
            - getQuote
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getSymbols
            - getCandles
            - getTicker
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/symbols"
            - "GET /trading/candles/:symbol"
            - "GET /trading/ticker/:symbol"
      frontend:
        - path: apps/frontend/src/modules/trading/pages/Trading.tsx
          description: "Página principal de trading"
        - path: apps/frontend/src/modules/trading/components/TradingChart.tsx
          description: "Chart con Lightweight Charts"
        - path: apps/frontend/src/modules/trading/components/ChartToolbar.tsx
          description: "Barra de herramientas del chart"
        - path: apps/frontend/src/modules/trading/components/TimeframeSelector.tsx
          description: "Selector de timeframe"
        - path: apps/frontend/src/modules/trading/components/SymbolSearch.tsx
          description: "Búsqueda de símbolos"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - symbols
            - candles
            - symbol_favorites
          enums:
            - market_type_enum
            - timeframe_enum
    external:
      - service: "Alpaca Markets"
        usage: "Market data real-time y histórico"
      - service: "Twelve Data"
        usage: "Datos alternativos"
    tests:
      - path: apps/backend/tests/trading/market-data.service.test.ts
        status: pending

  RF-TRD-002:
    name: "Indicadores Técnicos"
    status: pending
    specs:
      - ET-TRD-006
    user_stories:
      - US-TRD-003
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/indicator.service.ts
          description: "Servicio de cálculo de indicadores"
          methods:
            - calculateSMA
            - calculateEMA
            - calculateRSI
            - calculateMACD
            - calculateBollingerBands
            - calculateATR
            - calculateVWAP
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getIndicator
            - getIndicators
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/indicators/:symbol"
            - "POST /trading/indicators/calculate"
      frontend:
        - path: apps/frontend/src/modules/trading/components/IndicatorPanel.tsx
          description: "Panel de indicadores"
        - path: apps/frontend/src/modules/trading/components/IndicatorSettings.tsx
          description: "Configuración de indicadores"
        - path: apps/frontend/src/modules/trading/lib/indicators.ts
          description: "Cálculos de indicadores en frontend"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - user_indicators
          enums:
            - indicator_type_enum
    tests:
      - path: apps/backend/tests/trading/indicator.service.test.ts
        status: pending

  RF-TRD-003:
    name: "Gestión de Watchlists"
    status: pending
    specs:
      - ET-TRD-003
    user_stories:
      - US-TRD-004
      - US-TRD-005
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/watchlist.service.ts
          description: "Servicio de watchlists"
          methods:
            - createWatchlist
            - getWatchlists
            - getWatchlist
            - updateWatchlist
            - deleteWatchlist
            - addSymbol
            - removeSymbol
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - createWatchlist
            - getWatchlists
            - updateWatchlist
            - deleteWatchlist
            - addSymbolToWatchlist
            - removeSymbolFromWatchlist
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/watchlists"
            - "POST /trading/watchlists"
            - "GET /trading/watchlists/:id"
            - "PUT /trading/watchlists/:id"
            - "DELETE /trading/watchlists/:id"
            - "POST /trading/watchlists/:id/symbols"
            - "DELETE /trading/watchlists/:id/symbols/:symbol"
      frontend:
        - path: apps/frontend/src/modules/trading/components/WatchlistPanel.tsx
          description: "Panel de watchlists"
        - path: apps/frontend/src/modules/trading/components/WatchlistItem.tsx
          description: "Item de watchlist"
        - path: apps/frontend/src/modules/trading/components/WatchlistManager.tsx
          description: "Gestión de watchlists"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - watchlists
            - watchlist_symbols
    tests:
      - path: apps/backend/tests/trading/watchlist.service.test.ts
        status: pending

  RF-TRD-004:
    name: "Paper Trading"
    status: pending
    specs:
      - ET-TRD-007
    user_stories:
      - US-TRD-014
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/paper-trading.service.ts
          description: "Motor de paper trading"
          methods:
            - initializeAccount
            - getBalance
            - placeOrder
            - cancelOrder
            - getOrders
            - resetAccount
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getPaperBalance
            - placePaperOrder
            - cancelPaperOrder
            - resetPaperAccount
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/paper/balance"
            - "POST /trading/paper/orders"
            - "DELETE /trading/paper/orders/:id"
            - "POST /trading/paper/reset"
      frontend:
        - path: apps/frontend/src/modules/trading/pages/PaperTrading.tsx
          description: "Página de paper trading"
        - path: apps/frontend/src/modules/trading/components/PaperAccountSummary.tsx
          description: "Resumen de cuenta paper"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - paper_accounts
            - paper_orders
            - paper_positions
            - paper_transactions
          enums:
            - paper_order_type_enum
            - paper_order_status_enum
    tests:
      - path: apps/backend/tests/trading/paper-trading.service.test.ts
        status: pending

  RF-TRD-005:
    name: "Sistema de Órdenes"
    status: pending
    specs:
      - ET-TRD-004
      - ET-TRD-007
    user_stories:
      - US-TRD-006
      - US-TRD-007
      - US-TRD-012
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/order.service.ts
          description: "Servicio de órdenes"
          methods:
            - createMarketOrder
            - createLimitOrder
            - createStopOrder
            - createOCOOrder
            - setTakeProfit
            - setStopLoss
            - modifyOrder
            - cancelOrder
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - createOrder
            - modifyOrder
            - cancelOrder
            - getOrders
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "POST /trading/orders"
            - "PUT /trading/orders/:id"
            - "DELETE /trading/orders/:id"
            - "GET /trading/orders"
      frontend:
        - path: apps/frontend/src/modules/trading/components/OrderPanel.tsx
          description: "Panel de órdenes"
        - path: apps/frontend/src/modules/trading/components/OrderForm.tsx
          description: "Formulario de orden"
        - path: apps/frontend/src/modules/trading/components/OrderBook.tsx
          description: "Libro de órdenes"
        - path: apps/frontend/src/modules/trading/components/TPSLModal.tsx
          description: "Modal de Take Profit / Stop Loss"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - orders
          enums:
            - order_type_enum
            - order_side_enum
            - order_status_enum
    tests:
      - path: apps/backend/tests/trading/order.service.test.ts
        status: pending

  RF-TRD-006:
    name: "Gestión de Posiciones"
    status: pending
    specs:
      - ET-TRD-004
    user_stories:
      - US-TRD-008
      - US-TRD-009
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/position.service.ts
          description: "Servicio de posiciones"
          methods:
            - getPositions
            - getPosition
            - closePosition
            - updatePosition
            - calculatePnL
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getPositions
            - closePosition
            - modifyPosition
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/positions"
            - "GET /trading/positions/:id"
            - "DELETE /trading/positions/:id"
            - "PUT /trading/positions/:id"
      frontend:
        - path: apps/frontend/src/modules/trading/components/PositionsTable.tsx
          description: "Tabla de posiciones"
        - path: apps/frontend/src/modules/trading/components/PositionCard.tsx
          description: "Tarjeta de posición"
        - path: apps/frontend/src/modules/trading/components/PnLDisplay.tsx
          description: "Display de P&L"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - positions
    tests:
      - path: apps/backend/tests/trading/position.service.test.ts
        status: pending

  RF-TRD-007:
    name: "Historial de Trades"
    status: pending
    specs:
      - ET-TRD-008
    user_stories:
      - US-TRD-010
      - US-TRD-015
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/trade-history.service.ts
          description: "Servicio de historial"
          methods:
            - getTrades
            - getTradeById
            - exportTrades
            - getTradesByPeriod
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getTradeHistory
            - getTrade
            - exportTradeHistory
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/trades"
            - "GET /trading/trades/:id"
            - "GET /trading/trades/export"
      frontend:
        - path: apps/frontend/src/modules/trading/components/TradeHistory.tsx
          description: "Historial de trades"
        - path: apps/frontend/src/modules/trading/components/TradeDetail.tsx
          description: "Detalle de trade"
        - path: apps/frontend/src/modules/trading/components/ExportModal.tsx
          description: "Modal de exportación"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - trades
    tests:
      - path: apps/backend/tests/trading/trade-history.service.test.ts
        status: pending

  RF-TRD-008:
    name: "Métricas y Estadísticas"
    status: pending
    specs:
      - ET-TRD-008
    user_stories:
      - US-TRD-011
    implementation:
      backend:
        - path: apps/backend/src/modules/trading/services/statistics.service.ts
          description: "Servicio de estadísticas"
          methods:
            - calculateWinRate
            - calculateSharpeRatio
            - calculateMaxDrawdown
            - calculateProfitFactor
            - getDailyPnL
            - getMonthlyStats
        - path: apps/backend/src/modules/trading/controllers/trading.controller.ts
          methods:
            - getStatistics
            - getDailyPnL
            - getPerformance
        - path: apps/backend/src/modules/trading/trading.routes.ts
          routes:
            - "GET /trading/statistics"
            - "GET /trading/statistics/daily"
            - "GET /trading/statistics/performance"
      frontend:
        - path: apps/frontend/src/modules/trading/components/StatisticsPanel.tsx
          description: "Panel de estadísticas"
        - path: apps/frontend/src/modules/trading/components/PerformanceChart.tsx
          description: "Gráfico de rendimiento"
        - path: apps/frontend/src/modules/trading/components/MetricsCard.tsx
          description: "Tarjeta de métricas"
      database:
        - path: apps/database/schemas/03_trading_schema.sql
          tables:
            - trading_statistics
            - daily_pnl
    tests:
      - path: apps/backend/tests/trading/statistics.service.test.ts
        status: pending

# WebSocket Endpoints
websocket_endpoints:
  - channel: "ticker"
    description: "Precios en tiempo real"
    events:
      - "subscribe"
      - "unsubscribe"
      - "price_update"
  - channel: "candles"
    description: "Velas en tiempo real"
    events:
      - "subscribe"
      - "unsubscribe"
      - "candle_update"
  - channel: "orders"
    description: "Estado de órdenes"
    events:
      - "order_created"
      - "order_filled"
      - "order_cancelled"
  - channel: "positions"
    description: "Actualizaciones de posiciones"
    events:
      - "position_opened"
      - "position_closed"
      - "pnl_update"

# Mapeo de archivos de configuración
config_files:
  backend:
    - path: apps/backend/src/modules/trading/trading.module.ts
      description: "Módulo de trading"
    - path: apps/backend/src/modules/trading/validators/trading.validators.ts
      description: "Validadores Zod"
    - path: apps/backend/src/modules/trading/types/trading.types.ts
      description: "Tipos TypeScript"
    - path: apps/backend/src/modules/trading/gateways/trading.gateway.ts
      description: "WebSocket gateway"
  frontend:
    - path: apps/frontend/src/modules/trading/stores/trading.store.ts
      description: "Store de trading Zustand"
    - path: apps/frontend/src/modules/trading/hooks/useTrading.ts
      description: "Hook principal de trading"
    - path: apps/frontend/src/modules/trading/hooks/useWebSocket.ts
      description: "Hook de WebSocket"
    - path: apps/frontend/src/modules/trading/services/trading.api.ts
      description: "Cliente API de trading"

# Dependencias externas
external_dependencies:
  npm_backend:
    - name: ws
      version: "^8.14.0"
      usage: "WebSocket server"
    - name: technicalindicators
      version: "^3.1.0"
      usage: "Cálculo de indicadores"
    - name: alpaca-trade-api
      version: "^3.0.0"
      usage: "Alpaca Markets API"
  npm_frontend:
    - name: lightweight-charts
      version: "^4.1.0"
      usage: "Charts de trading"
    - name: socket.io-client
      version: "^4.7.0"
      usage: "WebSocket client"
    - name: "@tanstack/react-query"
      version: "^5.0.0"
      usage: "Data fetching"

# APIs de terceros
third_party_apis:
  - name: Alpaca Markets
    docs: https://alpaca.markets/docs/
    usage:
      - Market data (stocks, crypto)
      - Historical data
      - Real-time streaming
  - name: Twelve Data
    docs: https://twelvedata.com/docs
    usage:
      - Forex data
      - Technical indicators
      - Time series

# Endpoints API
api_endpoints:
  base_path: /api/v1/trading
  endpoints:
    # Market Data
    - method: GET
      path: /symbols
      requirement: RF-TRD-001
      auth: false
    - method: GET
      path: /candles/:symbol
      requirement: RF-TRD-001
      auth: true
    - method: GET
      path: /ticker/:symbol
      requirement: RF-TRD-001
      auth: true
    # Indicadores
    - method: GET
      path: /indicators/:symbol
      requirement: RF-TRD-002
      auth: true
    # Watchlists
    - method: GET
      path: /watchlists
      requirement: RF-TRD-003
      auth: true
    - method: POST
      path: /watchlists
      requirement: RF-TRD-003
      auth: true
    - method: PUT
      path: /watchlists/:id
      requirement: RF-TRD-003
      auth: true
    - method: DELETE
      path: /watchlists/:id
      requirement: RF-TRD-003
      auth: true
    # Paper Trading
    - method: GET
      path: /paper/balance
      requirement: RF-TRD-004
      auth: true
    - method: POST
      path: /paper/orders
      requirement: RF-TRD-004
      auth: true
    - method: POST
      path: /paper/reset
      requirement: RF-TRD-004
      auth: true
    # Órdenes
    - method: GET
      path: /orders
      requirement: RF-TRD-005
      auth: true
    - method: POST
      path: /orders
      requirement: RF-TRD-005
      auth: true
    - method: DELETE
      path: /orders/:id
      requirement: RF-TRD-005
      auth: true
    # Posiciones
    - method: GET
      path: /positions
      requirement: RF-TRD-006
      auth: true
    - method: DELETE
      path: /positions/:id
      requirement: RF-TRD-006
      auth: true
    # Historial
    - method: GET
      path: /trades
      requirement: RF-TRD-007
      auth: true
    - method: GET
      path: /trades/export
      requirement: RF-TRD-007
      auth: true
    # Estadísticas
    - method: GET
      path: /statistics
      requirement: RF-TRD-008
      auth: true

# Dependencias de épicas
dependencies:
  blocks:
    - epic: OQI-006
      reason: "ML Signals usa datos de trading"
  blocked_by:
    - epic: OQI-001
      reason: "Requiere autenticación de usuarios"

# Notas y decisiones
notes:
  - "Lightweight Charts v4 para renderizado de charts"
  - "WebSocket para datos en tiempo real con reconexión automática"
  - "Paper trading con $100,000 USD virtuales iniciales"
  - "Datos históricos cacheados en Redis con TTL de 5 minutos"
  - "Indicadores calculados en backend para consistencia"
  - "Timeframes soportados: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w"
