# Diagrama de Integraciones - OrbiQuant IA Trading Platform

**Version:** 1.0.0
**Fecha:** 2025-12-05
**Autor:** Agente de Documentacion y Planificacion
**Estado:** Aprobado

---

## 1. Resumen Ejecutivo

Este documento detalla todos los flujos de integracion entre componentes del sistema OrbiQuant IA, incluyendo:
- **Flujos de datos** entre servicios
- **APIs y endpoints** disponibles
- **Eventos y webhooks** para comunicacion asincrona
- **Protocolos** utilizados (REST, WebSocket, gRPC)

---

## 2. Arquitectura de Integracion Global

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                              FRONTEND LAYER                                  │
│                          React 18 + TypeScript + Vite                        │
│                                                                              │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────┐│
│  │  Auth UI   │  │ Education  │  │  Trading   │  │ Investment │  │  LLM   ││
│  │  Pages     │  │  Platform  │  │  Charts    │  │ Dashboard  │  │  Chat  ││
│  └──────┬─────┘  └──────┬─────┘  └──────┬─────┘  └──────┬─────┘  └───┬────┘│
│         │                │                │                │            │     │
│         └────────────────┴────────────────┴────────────────┴────────────┘     │
│                                      │                                        │
│                              REST + WebSocket                                 │
└──────────────────────────────────────┼────────────────────────────────────────┘
                                       │
┌──────────────────────────────────────▼────────────────────────────────────────┐
│                              API GATEWAY                                      │
│                         Express.js + TypeScript                               │
│                              Port: 3001                                       │
│                                                                              │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────┐│
│  │   /auth    │  │ /education │  │  /trading  │  │/investment │  │ /agent ││
│  │   Routes   │  │   Routes   │  │   Routes   │  │   Routes   │  │ Routes ││
│  └──────┬─────┘  └──────┬─────┘  └──────┬─────┘  └──────┬─────┘  └───┬────┘│
│         │                │                │                │            │     │
│         │        ┌───────┴────────────────┴────────────────┴───────┐    │     │
│         │        │         SHARED SERVICES                         │    │     │
│         │        │  ┌──────────┐  ┌──────────┐  ┌──────────────┐  │    │     │
│         │        │  │  Redis   │  │WebSocket │  │    Rate      │  │    │     │
│         │        │  │  Client  │  │  Server  │  │   Limiter    │  │    │     │
│         │        │  └──────────┘  └──────────┘  └──────────────┘  │    │     │
│         │        └─────────────────────────────────────────────────┘    │     │
│         │                                                                │     │
│         ▼                                                                ▼     │
│  ┌──────────────────┐                                        ┌────────────────┐│
│  │  Auth Service    │                                        │  LLM Service   ││
│  │  ┌────────────┐  │                                        │  Claude 3.5    ││
│  │  │ JWT, OAuth │  │                                        │  / GPT-4       ││
│  │  │ 2FA, RBAC  │  │                                        │  + Tools       ││
│  │  └────────────┘  │                                        └────────────────┘│
│  └──────────────────┘                                                         │
└────────────────────┬──────────────────┬──────────────────┬───────────────────┘
                     │                  │                  │
         ┌───────────┼──────────────────┼──────────────────┼───────────┐
         │           │                  │                  │           │
         ▼           ▼                  ▼                  ▼           ▼
┌─────────────┐ ┌─────────┐  ┌──────────────┐  ┌──────────────┐ ┌──────────┐
│ PostgreSQL  │ │  Redis  │  │  ML Engine   │  │ Data Service │ │  Stripe  │
│   Primary   │ │ Cache + │  │   FastAPI    │  │    Python    │ │   API    │
│  Database   │ │ Pub/Sub │  │  Port: 8000  │  │  Port: 8001  │ │  HTTPS   │
│ Port: 5432  │ │Port:6379│  │              │  │              │ │          │
└─────────────┘ └─────────┘  └──────┬───────┘  └──────┬───────┘ └──────────┘
                                    │                  │
                             ┌──────┴──────────────────┴──────┐
                             │                                 │
                             ▼                                 ▼
                    ┌─────────────────┐            ┌─────────────────────┐
                    │  Polygon.io API │            │  MetaAPI / MT4      │
                    │  Market Data    │            │  Broker Integration │
                    │  HTTPS          │            │  HTTPS + WebSocket  │
                    └─────────────────┘            └─────────────────────┘
```

---

## 3. Flujos de Datos Criticos

### 3.1 Flujo de Inversion (Usuario → Wallet → Agente → MT4 → Trading)

```
┌──────────┐
│  USUARIO │ "Quiero invertir $1000 en Atlas (conservador)"
└────┬─────┘
     │ POST /investment/accounts
     ▼
┌─────────────────┐
│ Backend Express │ 1. Verifica KYC aprobado
│  Investment     │ 2. Valida saldo wallet >= $1000
│   Service       │ 3. Crea registro en investment.accounts
└────┬────────────┘
     │ SQL INSERT
     ▼
┌─────────────────┐
│  PostgreSQL     │ accounts table:
│  investment     │ - user_id
│  schema         │ - product_id (Atlas)
└────┬────────────┘ - initial_balance: $1000
     │              - status: pending_deposit
     │
     │ 4. Transferir desde wallet
     ▼
┌─────────────────┐
│  Financial      │ wallet_transactions:
│  Schema         │ - type: investment_deposit
└────┬────────────┘ - amount: -$1000
     │              - status: completed
     │
     │ 5. Asignar trading agent
     ▼
┌─────────────────┐
│  Trading        │ bots table:
│  Schema         │ - name: "Atlas Conservative"
└────┬────────────┘ - strategy_id: 1
     │              - status: active
     │
     │ 6. Conectar con broker
     ▼
┌─────────────────┐
│ Broker          │ broker_accounts:
│ Integration     │ - metaapi_account_id
│ Schema          │ - balance: $1000
└────┬────────────┘ - equity: $1000
     │
     │ 7. Esperar señal ML
     ▼
┌─────────────────┐
│  ML Engine      │ POST /signals
│  FastAPI        │ Returns: {
└────┬────────────┘   "signal": "LONG",
     │                 "symbol": "EURUSD",
     │                 "entry": 1.0550,
     │                 "sl": 1.0500,
     │                 "tp": 1.0650
     │               }
     │
     │ 8. Agent evalua señal
     ▼
┌─────────────────┐
│ Atlas Agent     │ Risk check:
│ Python          │ - Max position size: 1%
└────┬────────────┘ - Correlation check: OK
     │              - Drawdown check: OK
     │
     │ 9. Ejecutar orden
     ▼
┌─────────────────┐
│ MetaAPI Client  │ POST /accounts/{id}/trade
│ HTTP            │ {
└────┬────────────┘   "actionType": "POSITION_TYPE_BUY",
     │                 "symbol": "EURUSD",
     │                 "volume": 0.01,
     │                 "stopLoss": 1.0500,
     │                 "takeProfit": 1.0650
     │               }
     │
     │ 10. Confirmar ejecución
     ▼
┌─────────────────┐
│ MT4 Broker      │ Order filled:
│ Server          │ - Ticket: #123456789
└────┬────────────┘ - Entry: 1.05502 (slippage)
     │              - Spread: 0.00003
     │
     │ 11. Log trade execution
     ▼
┌─────────────────┐
│ broker_integration
│ trade_execution │ - signal_id
│ table           │ - broker_account_id
└────┬────────────┘ - entry_price: 1.05502
     │              - pnl: 0 (open)
     │
     │ 12. Notificar usuario
     ▼
┌─────────────────┐
│  WebSocket      │ Event: "trade_executed"
│  Server         │ → Frontend
└────┬────────────┘ → Notification UI
     │
     ▼
┌──────────┐
│  USUARIO │ "Trade ejecutado: EURUSD LONG @ 1.05502"
└──────────┘
```

**Protocolo:** REST (pasos 1-9, 11) + WebSocket (paso 12)
**Latencia Total:** ~2-5 segundos

---

### 3.2 Flujo de Predicciones (Data Service → PostgreSQL → ML Engine → Señales → Frontend)

```
┌─────────────────┐
│  Polygon.io API │ GET /v2/aggs/ticker/C:EURUSD/range/5/minute/...
└────┬────────────┘
     │ JSON Response
     ▼
┌─────────────────┐
│  Data Service   │ 1. Parse OHLCV data
│  Python         │ 2. Transform to internal format
└────┬────────────┘ 3. Bulk insert
     │
     │ SQL INSERT (batch 10k records)
     ▼
┌─────────────────┐
│  PostgreSQL     │ market_data.ohlcv_5m:
│  market_data    │ - ticker_id: 2 (EURUSD)
│  schema         │ - timestamp: 2025-12-05 10:00
└────┬────────────┘ - open, high, low, close, volume
     │
     │ 4. Trigger: Calculate technical indicators
     ▼
┌─────────────────┐
│  PostgreSQL     │ market_data.technical_indicators:
│  Function       │ - sma_10, sma_20, sma_50
└────┬────────────┘ - rsi_14, macd, atr
     │
     │ 5. ML Engine scheduled job (every 15 min)
     ▼
┌─────────────────┐
│  ML Engine      │ SELECT FROM market_data.ohlcv_5m
│  FastAPI        │ WHERE timestamp > NOW() - INTERVAL '6 hours'
└────┬────────────┘
     │ FeatureBuilder
     ▼
┌─────────────────┐
│  XGBoost Model  │ Features (21):
│  GPU            │ - volatility_10, volatility_20
└────┬────────────┘ - rsi, momentum, sma_ratios, etc.
     │
     │ 6. Predict delta_high, delta_low
     ▼
┌─────────────────┐
│  RangePredictor │ Prediction:
│  Python         │ - predicted_high: +0.0042 (0.42%)
└────┬────────────┘ - predicted_low: -0.0031 (0.31%)
     │              - confidence: 0.759
     │
     │ 7. TPSL Classifier
     ▼
┌─────────────────┐
│  TPSL Classifier│ prob_tp_first:
│  Model          │ - RR 2:1 → 0.68
└────┬────────────┘ - RR 3:1 → 0.54
     │
     │ 8. Signal Generator
     ▼
┌─────────────────┐
│  SignalGenerator│ Signal:
│  Python         │ {
└────┬────────────┘   "type": "LONG",
     │                 "entry": 1.0550,
     │                 "sl": 1.0500,
     │                 "tp": 1.0650,
     │                 "rr_ratio": 2.0,
     │                 "prob_tp": 0.68
     │               }
     │
     │ SQL INSERT
     ▼
┌─────────────────┐
│  PostgreSQL     │ ml_predictions.entry_signals:
│  ml_predictions │ - ticker_id: 2
│  schema         │ - signal_timestamp
└────┬────────────┘ - entry, sl, tp
     │
     │ 9. Publish to Redis
     ▼
┌─────────────────┐
│  Redis Pub/Sub  │ PUBLISH signals:EURUSD
│                 │ { signal JSON }
└────┬────────────┘
     │
     │ 10. Backend subscribes
     ▼
┌─────────────────┐
│  Express        │ Redis subscriber
│  WebSocket      │ ON MESSAGE: broadcast to clients
│  Service        │
└────┬────────────┘
     │ WebSocket emit
     ▼
┌─────────────────┐
│  Frontend       │ Event: "ml_signal_new"
│  React          │ → Show notification
└────┬────────────┘ → Update chart overlay
     │
     ▼
┌──────────┐
│  USUARIO │ "Nueva señal: EURUSD LONG con R:R 2:1"
└──────────┘
```

**Protocolo:** HTTP (Data Service → DB) + SQL (ML queries) + Redis Pub/Sub + WebSocket
**Frecuencia:** Cada 15 minutos
**Latencia Signal:** <2 segundos (desde insert en DB hasta frontend)

---

### 3.3 Flujo de Pagos (Usuario → Stripe → Webhook → Backend → Wallet)

```
┌──────────┐
│  USUARIO │ "Comprar plan Pro - $49/mes"
└────┬─────┘
     │ POST /payments/checkout
     ▼
┌─────────────────┐
│ Backend Express │ 1. Crear Stripe customer (si no existe)
│  Payment        │ 2. Crear Checkout Session
│   Service       │
└────┬────────────┘
     │ Stripe API call
     ▼
┌─────────────────┐
│  Stripe API     │ POST /v1/checkout/sessions
│  HTTPS          │ {
└────┬────────────┘   "mode": "subscription",
     │                 "line_items": [{ price: "price_pro" }],
     │                 "success_url": "https://app.orbiquant.com/success",
     │                 "cancel_url": "https://app.orbiquant.com/cancel"
     │               }
     │
     │ Response: { url: "checkout.stripe.com/..." }
     ▼
┌─────────────────┐
│ Backend Express │ Return: { checkout_url }
│                 │
└────┬────────────┘
     │ 3. Redirect frontend
     ▼
┌─────────────────┐
│  Frontend       │ window.location = checkout_url
│  React          │
└────┬────────────┘
     │
     ▼
┌─────────────────┐
│  Stripe Hosted  │ Usuario ingresa tarjeta
│  Checkout Page  │ - Card number
└────┬────────────┘ - CVC, expiry
     │              - Billing info
     │
     │ 4. Payment submitted
     ▼
┌─────────────────┐
│  Stripe         │ Process payment
│  Payment Engine │ → Success
└────┬────────────┘
     │
     │ 5. Webhook trigger (async)
     ▼
┌─────────────────┐
│  Stripe         │ POST https://api.orbiquant.com/payments/webhook
│  Webhook        │ Headers:
└────┬────────────┘   Stripe-Signature: t=...,v1=...
     │              Body:
     │                {
     │                  "type": "checkout.session.completed",
     │                  "data": { subscription_id, customer_id }
     │                }
     │
     ▼
┌─────────────────┐
│ Backend Express │ 6. Verify webhook signature
│  Webhook        │ 7. Parse event type
│  Handler        │
└────┬────────────┘
     │ 8. Process subscription.created
     ▼
┌─────────────────┐
│  PostgreSQL     │ financial.subscriptions:
│  financial      │ - user_id
│  schema         │ - stripe_subscription_id
└────┬────────────┘ - plan: "pro"
     │              - status: "active"
     │              - current_period_end
     │
     │ 9. Update user role
     ▼
┌─────────────────┐
│  PostgreSQL     │ UPDATE public.users
│  public.users   │ SET plan = 'pro'
└────┬────────────┘ WHERE id = user_id
     │
     │ 10. Grant access
     ▼
┌─────────────────┐
│  Cache          │ SET user:{id}:plan = "pro"
│  Redis          │ EXPIRE 3600
└────┬────────────┘
     │
     │ 11. Notify user
     ▼
┌─────────────────┐
│  Email Service  │ Send "Welcome to Pro" email
│  (Twilio/SES)   │
└────┬────────────┘
     │
     │ 12. WebSocket notification
     ▼
┌─────────────────┐
│  Frontend       │ Event: "subscription_activated"
│  React          │ → Refresh UI
└────┬────────────┘ → Show Pro features
     │
     ▼
┌──────────┐
│  USUARIO │ "Ahora eres usuario Pro!"
└──────────┘
```

**Protocolo:** REST (checkout) + Webhook (confirmacion)
**Seguridad:** Stripe-Signature verification (HMAC SHA256)
**Latencia:** 2-5 segundos (checkout) + 1-3 segundos (webhook processing)

---

### 3.4 Flujo LLM Agent (Usuario → Chat → LLM → Tools → MT4/ML → Respuesta)

```
┌──────────┐
│  USUARIO │ "Analiza EURUSD y dame una señal"
└────┬─────┘
     │ POST /agent/chat
     ▼
┌─────────────────┐
│ Backend Express │ 1. Validate auth
│  LLM Service    │ 2. Load conversation history
└────┬────────────┘ 3. Rate limit check (10 msg/min)
     │
     │ 4. Build context
     ▼
┌─────────────────┐
│  Context        │ System prompt + conversation history
│  Builder        │ User profile + risk preferences
└────┬────────────┘ Available tools definition
     │
     │ 5. Call LLM API
     ▼
┌─────────────────┐
│  Claude 3.5 API │ POST /v1/messages
│  (Anthropic)    │ {
└────┬────────────┘   "model": "claude-3-5-sonnet-20250929",
     │                 "messages": [...],
     │                 "tools": [
     │                   { "name": "get_ml_signal", ... },
     │                   { "name": "analyze_chart", ... }
     │                 ]
     │               }
     │
     │ 6. LLM decides to use tool
     ▼
┌─────────────────┐
│  Claude Response│ {
│                 │   "content": [
└────┬────────────┘     {
     │                    "type": "tool_use",
     │                    "name": "get_ml_signal",
     │                    "input": { "symbol": "EURUSD", "horizon": 18 }
     │                  }
     │                ]
     │              }
     │
     │ 7. Execute tool
     ▼
┌─────────────────┐
│  Tool Executor  │ Call: get_ml_signal("EURUSD", 18)
│  Backend        │
└────┬────────────┘
     │ HTTP request to ML Engine
     ▼
┌─────────────────┐
│  ML Engine      │ POST /signals
│  FastAPI        │ {
└────┬────────────┘   "symbol": "EURUSD",
     │                 "horizon": 18
     │               }
     │
     │ 8. Get prediction
     ▼
┌─────────────────┐
│  XGBoost +      │ Prediction result:
│  TPSL Classifier│ {
└────┬────────────┘   "signal": "LONG",
     │                 "entry": 1.0550,
     │                 "sl": 1.0500,
     │                 "tp": 1.0650,
     │                 "prob_tp_first": 0.68,
     │                 "amd_phase": "accumulation"
     │               }
     │
     │ 9. Return tool result
     ▼
┌─────────────────┐
│  Tool Executor  │ Format tool result:
│  Backend        │ {
└────┬────────────┘   "type": "tool_result",
     │                 "tool_use_id": "...",
     │                 "content": [{ ML signal JSON }]
     │               }
     │
     │ 10. Send back to Claude
     ▼
┌─────────────────┐
│  Claude 3.5 API │ POST /v1/messages (continuation)
│                 │ {
└────┬────────────┘   "messages": [..., tool_result]
     │               }
     │
     │ 11. Claude generates final response
     ▼
┌─────────────────┐
│  Claude Response│ {
│                 │   "content": [
└────┬────────────┘     {
     │                    "type": "text",
     │                    "text": "Análisis de EURUSD:
     │                             - Fase AMD: Acumulación
     │                             - Señal: LONG @ 1.0550
     │                             - R:R 2:1 con prob 68%
     │                             - Recomiendo entrada con 1% del capital"
     │                  }
     │                ]
     │              }
     │
     │ 12. Save conversation
     ▼
┌─────────────────┐
│  PostgreSQL     │ INSERT INTO llm.messages
│  llm schema     │ - conversation_id
└────┬────────────┘ - role: "assistant"
     │              - content
     │              - tools_used: ["get_ml_signal"]
     │
     │ 13. Stream response
     ▼
┌─────────────────┐
│  WebSocket      │ Emit chunk-by-chunk
│  Server         │ → Frontend
└────┬────────────┘
     │
     ▼
┌──────────┐
│  USUARIO │ Ve la respuesta aparecer en tiempo real
└──────────┘
```

**Protocolo:** REST + WebSocket (streaming)
**Tools Disponibles:**
- `get_ml_signal(symbol, horizon)` → ML Engine
- `analyze_chart(symbol, timeframe)` → PostgreSQL
- `execute_paper_trade(symbol, side, amount)` → Trading Service
- `get_portfolio_status()` → Investment Service
- `search_education(query)` → Education Service

**Latencia:** 3-8 segundos (depende de tool execution)

---

## 4. APIs y Endpoints

### 4.1 Backend Express (Puerto 3001)

#### Autenticacion

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| POST | `/auth/register` | `{ email, password, firstName, lastName }` | `{ user, tokens }` | No |
| POST | `/auth/login` | `{ email, password }` | `{ user, tokens }` | No |
| POST | `/auth/oauth/:provider` | `{ code }` | `{ user, tokens }` | No |
| POST | `/auth/2fa/setup` | - | `{ secret, qr_code }` | Yes |
| POST | `/auth/2fa/verify` | `{ token }` | `{ success }` | Yes |
| POST | `/auth/refresh` | `{ refresh_token }` | `{ access_token }` | No |

#### Educacion

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/education/courses` | Query: `{ level?, category? }` | `{ courses[] }` | Yes |
| GET | `/education/courses/:slug` | - | `{ course, modules[] }` | Yes |
| POST | `/education/courses/:id/enroll` | - | `{ enrollment }` | Yes |
| GET | `/education/lessons/:id` | - | `{ lesson, content }` | Yes |
| POST | `/education/lessons/:id/progress` | `{ completed, time_spent }` | `{ updated }` | Yes |
| POST | `/education/quizzes/:id/submit` | `{ answers[] }` | `{ score, correct_answers }` | Yes |

#### Trading

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/trading/symbols` | Query: `{ asset_type? }` | `{ symbols[] }` | Yes |
| GET | `/trading/candles/:symbol` | Query: `{ tf, from, to }` | `{ candles[] }` | Yes |
| WS | `/trading/stream/:symbol` | - | Stream: `{ price, volume }` | Yes |
| GET | `/trading/watchlists` | - | `{ watchlists[] }` | Yes |
| POST | `/trading/paper/orders` | `{ symbol, side, amount }` | `{ order }` | Yes |
| GET | `/trading/paper/positions` | - | `{ positions[] }` | Yes |

#### Investment

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/investment/products` | - | `{ products[] }` | Yes |
| GET | `/investment/accounts` | - | `{ accounts[] }` | Yes |
| POST | `/investment/accounts` | `{ product_id, amount }` | `{ account }` | Yes |
| POST | `/investment/accounts/:id/deposit` | `{ amount }` | `{ transaction }` | Yes |
| POST | `/investment/accounts/:id/withdraw` | `{ amount }` | `{ request }` | Yes |
| GET | `/investment/accounts/:id/performance` | Query: `{ from, to }` | `{ snapshots[] }` | Yes |

#### Payments

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/payments/plans` | - | `{ plans[] }` | No |
| POST | `/payments/checkout` | `{ plan_id, promo_code? }` | `{ checkout_url }` | Yes |
| GET | `/payments/subscription` | - | `{ subscription }` | Yes |
| POST | `/payments/subscription/cancel` | - | `{ canceled }` | Yes |
| GET | `/payments/wallet` | - | `{ balance, transactions[] }` | Yes |
| POST | `/payments/wallet/deposit` | `{ amount, method }` | `{ payment_intent }` | Yes |
| POST | `/payments/webhook` | Stripe event | `{ received: true }` | No (Signature) |

#### ML Proxy

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/ml/signals/:symbol` | Query: `{ horizon? }` | `{ signals[] }` | Yes |
| GET | `/ml/predictions/:symbol` | Query: `{ horizon }` | `{ prediction }` | Yes |
| GET | `/ml/indicators/:symbol` | Query: `{ timeframe }` | `{ indicators }` | Yes |

#### LLM Agent

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| POST | `/agent/chat` | `{ message, conversation_id? }` | Stream: `{ chunks }` | Yes |
| GET | `/agent/conversations` | - | `{ conversations[] }` | Yes |
| GET | `/agent/conversations/:id` | - | `{ messages[] }` | Yes |
| DELETE | `/agent/conversations/:id` | - | `{ deleted: true }` | Yes |

---

### 4.2 ML Engine FastAPI (Puerto 8000)

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| POST | `/predictions` | `{ symbol, horizon }` | `{ predicted_high, predicted_low, confidence }` | API Key |
| POST | `/signals` | `{ symbol, horizon, include_range, include_tpsl }` | `{ signal, entry, sl, tp, prob_tp_first }` | API Key |
| GET | `/indicators` | Query: `{ symbol }` | `{ sma, rsi, macd, atr, amd_phase }` | API Key |
| GET | `/models/status` | - | `{ models[] }` | API Key |
| GET | `/models/:name/metrics` | - | `{ mae, accuracy, auc }` | API Key |
| GET | `/health` | - | `{ status: "ok", gpu: true }` | No |
| WS | `/ws/:symbol` | - | Stream: `{ predictions }` | API Key |

**Authentication:** Header `X-API-Key: {api_key}`

---

### 4.3 Data Service Python (Puerto 8001)

| Method | Endpoint | Request | Response | Auth |
|--------|----------|---------|----------|------|
| GET | `/sync/status` | - | `{ tickers[] }` | API Key |
| POST | `/sync/trigger` | `{ ticker_id }` | `{ job_id }` | API Key |
| GET | `/sync/history/:ticker_id` | - | `{ last_sync, records_count }` | API Key |
| GET | `/spreads/:ticker_id` | Query: `{ session }` | `{ avg_spread, min, max }` | API Key |
| GET | `/health` | - | `{ status: "ok", providers[] }` | No |

---

## 5. Eventos y Webhooks

### 5.1 Webhooks Entrantes

| Proveedor | Endpoint | Evento | Accion |
|-----------|----------|--------|--------|
| Stripe | `/payments/webhook` | `checkout.session.completed` | Activar suscripcion |
| Stripe | `/payments/webhook` | `invoice.payment_succeeded` | Renovar suscripcion |
| Stripe | `/payments/webhook` | `customer.subscription.deleted` | Cancelar suscripcion |
| Stripe | `/payments/webhook` | `invoice.payment_failed` | Marcar pago fallido |
| MetaAPI | `/broker/webhook` | `trade_executed` | Log trade en BD |
| MetaAPI | `/broker/webhook` | `position_closed` | Calcular PnL |

**Seguridad:** Verificacion de firma HMAC

---

### 5.2 WebSocket Events (Frontend ← Backend)

| Event | Channel | Payload | Trigger |
|-------|---------|---------|---------|
| `price_update` | `ticker:{symbol}` | `{ bid, ask, timestamp }` | Cada 1s (market hours) |
| `ml_signal_new` | `signals:{symbol}` | `{ signal, entry, sl, tp }` | ML Engine genera senal |
| `trade_executed` | `user:{id}:trades` | `{ trade_id, status }` | Orden ejecutada en broker |
| `position_closed` | `user:{id}:positions` | `{ position_id, pnl }` | TP/SL alcanzado |
| `subscription_activated` | `user:{id}:notifications` | `{ plan }` | Webhook Stripe procesado |
| `llm_response_chunk` | `chat:{conversation_id}` | `{ chunk }` | Claude streaming |

**Protocolo:** Socket.IO (WebSocket + fallbacks)

---

## 6. Protocolos por Componente

### 6.1 Matriz de Protocolos

| Origen | Destino | Protocolo | Puerto | Uso |
|--------|---------|-----------|--------|-----|
| Frontend | Backend Express | HTTPS (REST) | 3001 | APIs CRUD |
| Frontend | Backend Express | WSS (WebSocket) | 3001 | Real-time updates |
| Backend | PostgreSQL | TCP (libpq) | 5432 | Database queries |
| Backend | Redis | TCP (RESP) | 6379 | Cache + Pub/Sub |
| Backend | ML Engine | HTTP (REST) | 8000 | ML predictions |
| Backend | Stripe | HTTPS (REST) | 443 | Payment processing |
| Backend | Claude API | HTTPS (REST) | 443 | LLM requests |
| ML Engine | PostgreSQL | TCP (libpq) | 5432 | Training data |
| ML Engine | Redis | TCP (RESP) | 6379 | Cache results |
| Data Service | Polygon API | HTTPS (REST) | 443 | Market data |
| Data Service | MetaAPI | HTTPS + WSS | 443 | Broker integration |
| Data Service | PostgreSQL | TCP (libpq) | 5432 | Insert OHLCV |

---

### 6.2 Formatos de Datos

| Componente | Request | Response | Schema |
|------------|---------|----------|--------|
| Backend Express | JSON | JSON | OpenAPI 3.0 |
| ML Engine | JSON | JSON | Pydantic models |
| PostgreSQL | SQL | Row sets | PostgreSQL types |
| Redis | RESP | RESP | Redis data types |
| WebSocket | JSON | JSON | Custom events |
| Stripe | JSON | JSON | Stripe API spec |

---

## 7. Seguridad de Integraciones

### 7.1 Autenticacion por Servicio

| Servicio | Metodo | Implementacion |
|----------|--------|----------------|
| Backend → Frontend | JWT | Access token (15 min) + Refresh (7 dias) |
| Backend → ML Engine | API Key | Header `X-API-Key` |
| Backend → Data Service | API Key | Header `X-API-Key` |
| Stripe → Backend | Signature | Header `Stripe-Signature` (HMAC) |
| Backend → Claude | API Key | Header `x-api-key` |
| Backend → Polygon | API Key | Query param `apiKey` |
| Backend → MetaAPI | Token | Header `auth-token` |

---

### 7.2 Rate Limiting

| Endpoint | Free | Basic | Pro | Premium |
|----------|------|-------|-----|---------|
| `/ml/*` | 3/dia | 10/dia | 100/dia | Unlimited |
| `/agent/chat` | 10/dia | 50/dia | 200/dia | Unlimited |
| `/trading/paper/*` | 10/min | 30/min | 100/min | 300/min |
| `/payments/*` | 5/min | 10/min | 20/min | 50/min |

**Implementacion:** Redis + express-rate-limit

---

## 8. Diagramas de Secuencia

### 8.1 Registro de Usuario

```mermaid
sequenceDiagram
    participant U as Usuario
    participant F as Frontend
    participant B as Backend
    participant DB as PostgreSQL
    participant E as Email Service

    U->>F: Click "Registrarse"
    F->>B: POST /auth/register
    B->>DB: INSERT INTO users
    DB-->>B: user_id
    B->>E: Send verification email
    B-->>F: { user, tokens }
    F->>F: Store tokens localStorage
    F-->>U: Redirect to dashboard
```

---

### 8.2 Ejecucion de Trade

```mermaid
sequenceDiagram
    participant ML as ML Engine
    participant B as Backend
    participant A as Trading Agent
    participant M as MetaAPI
    participant MT as MT4 Broker
    participant DB as PostgreSQL

    ML->>B: Publish signal to Redis
    B->>A: Forward signal
    A->>A: Risk check
    A->>M: POST /trade
    M->>MT: Execute order
    MT-->>M: Order filled
    M-->>A: Confirmation
    A->>DB: Log execution
    A->>B: Notify user
    B->>Frontend: WebSocket event
```

---

## 9. Contingencias

### 9.1 Fallback Strategies

| Servicio | Fallo | Fallback |
|----------|-------|----------|
| ML Engine | Down | Cache ultimas predicciones (Redis TTL 1h) |
| Polygon API | Rate limit | Usar datos MySQL legacy |
| MetaAPI | Timeout | Switch a investor mode (solo tracking) |
| Claude API | Error | Fallback a respuestas template |
| Stripe | Webhook miss | Polling manual cada 5 min |

---

### 9.2 Circuit Breakers

| Servicio | Threshold | Timeout | Reset |
|----------|-----------|---------|-------|
| ML Engine | 5 fallos | 30s | 60s |
| Polygon API | 3 fallos | 60s | 300s |
| MetaAPI | 10 fallos | 10s | 30s |

---

## 10. Monitoreo de Integraciones

### 10.1 Metricas Clave

| Metrica | Threshold | Alerta |
|---------|-----------|--------|
| API p95 latency | <200ms | Slack |
| ML prediction time | <2s | Email |
| WebSocket lag | <500ms | PagerDuty |
| Stripe webhook delay | <5s | Slack |
| Database query time | <100ms | Email |

---

### 10.2 Health Checks

| Servicio | Endpoint | Frecuencia |
|----------|----------|------------|
| Backend | `/health` | 30s |
| ML Engine | `/health` | 60s |
| Data Service | `/health` | 60s |
| PostgreSQL | TCP ping | 10s |
| Redis | PING | 10s |

---

## 11. Referencias

- [PLAN-DESARROLLO-DETALLADO.md](../roadmap/PLAN-DESARROLLO-DETALLADO.md)
- [MATRIZ-DEPENDENCIAS.yml](../inventarios/MATRIZ-DEPENDENCIAS.yml)
- [ARQUITECTURA-UNIFICADA.md](./ARQUITECTURA-UNIFICADA.md)
- [INT-DATA-001-data-service.md](../90-transversal/integraciones/INT-DATA-001-data-service.md)

---

**Version History:**

| Version | Fecha | Cambios |
|---------|-------|---------|
| 1.0.0 | 2025-12-05 | Creacion inicial |
