ML Engine Updates: - Updated BTCUSD with Polygon API data (2024-2025): 215,699 new records - Re-trained all ML models: Attention (R²: 0.223), Base, Metamodel (87.3% confidence) - Backtest results: +176.71R profit with aggressive_filter strategy Documentation Consolidation: - Created docs/99-analisis/_MAP.md index with 13 new analysis documents - Consolidated inventories: removed duplicates from orchestration/inventarios/ - Updated ML_INVENTORY.yml with BTCUSD metrics and training results - Added execution reports: FASE11-BTCUSD, correction issues, alignment validation Architecture & Integration: - Updated all module documentation with NEXUS v3.4 frontmatter - Fixed _MAP.md indexes across all folders - Updated orchestration plans and traces Files: 229 changed, 5064 insertions(+), 1872 deletions(-) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
467 lines
19 KiB
Markdown
467 lines
19 KiB
Markdown
---
|
|
id: "INT-DATA-001-data-service"
|
|
title: "Data Service - Integración de Fuentes de Datos"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# INT-DATA-001: Data Service - Integración de Fuentes de Datos
|
|
|
|
## Metadata
|
|
|
|
| Campo | Valor |
|
|
|-------|-------|
|
|
| **ID** | INT-DATA-001 |
|
|
| **Módulo** | Data Service |
|
|
| **Tipo** | Especificación de Integración |
|
|
| **Versión** | 1.0.0 |
|
|
| **Estado** | Implementado |
|
|
| **Fecha creación** | 2025-12-05 |
|
|
| **Última actualización** | 2025-12-05 |
|
|
| **Autor** | Database Agent |
|
|
|
|
---
|
|
|
|
## 1. Resumen Ejecutivo
|
|
|
|
Este documento describe la implementación del **Data Service**, un componente crítico que gestiona:
|
|
- Integración con API Polygon.io/Massive.com para datos históricos y tiempo real
|
|
- Conexión con MetaTrader 4 para precios de broker y ejecución de trades
|
|
- Modelo de adaptación de precios entre fuentes de datos y broker
|
|
- Tracking y análisis de spreads por activo y sesión de trading
|
|
|
|
---
|
|
|
|
## 2. Arquitectura de Integración
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
│ DATA SERVICE │
|
|
│ │
|
|
│ ┌────────────────────────────────────────────────────────────────────────┐ │
|
|
│ │ PROVIDERS LAYER │ │
|
|
│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────────┐│ │
|
|
│ │ │ PolygonClient │ │ MT4Client │ │ MetaAPIClient ││ │
|
|
│ │ │ │ │ │ │ ││ │
|
|
│ │ │ • Forex (C:) │ │ • Direct TCP │ │ • Cloud API ││ │
|
|
│ │ │ • Crypto (X:) │ │ • Propietario │ │ • REST + WebSocket ││ │
|
|
│ │ │ • Indices (I:)│ │ │ │ • Sin terminal MT4 ││ │
|
|
│ │ │ • Futures │ │ │ │ ││ │
|
|
│ │ └───────┬────────┘ └───────┬────────┘ └─────────────┬──────────────┘│ │
|
|
│ └──────────┼───────────────────┼─────────────────────────┼───────────────┘ │
|
|
│ │ │ │ │
|
|
│ ┌──────────▼───────────────────▼─────────────────────────▼───────────────┐ │
|
|
│ │ SERVICES LAYER │ │
|
|
│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────────┐│ │
|
|
│ │ │ DataSyncService│ │ SpreadTracker │ │ PriceAdjustmentService ││ │
|
|
│ │ │ │ │ │ │ ││ │
|
|
│ │ │ • Sync 5m │ │ • Record bids │ │ • Offset calculation ││ │
|
|
│ │ │ • Incremental │ │ • Statistics │ │ • Session multipliers ││ │
|
|
│ │ │ • Backfill │ │ • By session │ │ • Volatility adjust ││ │
|
|
│ │ └───────┬────────┘ └───────┬────────┘ └─────────────┬──────────────┘│ │
|
|
│ └──────────┼───────────────────┼─────────────────────────┼───────────────┘ │
|
|
│ │ │ │ │
|
|
│ ┌──────────▼───────────────────▼─────────────────────────▼───────────────┐ │
|
|
│ │ DATABASE LAYER │ │
|
|
│ │ │ │
|
|
│ │ SCHEMAS: │ │
|
|
│ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────────┐│ │
|
|
│ │ │ data_sources │ │broker_integr. │ │ market_data ││ │
|
|
│ │ │ │ │ │ │ ││ │
|
|
│ │ │ • providers │ │ • accounts │ │ • ohlcv_5m (partitioned) ││ │
|
|
│ │ │ • mappings │ │ • prices │ │ • tickers ││ │
|
|
│ │ │ • sync_status │ │ • spreads │ │ • indicators ││ │
|
|
│ │ │ │ │ • adjustments │ │ ││ │
|
|
│ │ └────────────────┘ └────────────────┘ └────────────────────────────┘│ │
|
|
│ └─────────────────────────────────────────────────────────────────────────┘ │
|
|
└─────────────────────────────────────────────────────────────────────────────┘
|
|
│
|
|
▼
|
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
│ EXTERNAL SYSTEMS │
|
|
│ │
|
|
│ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────────────┐ │
|
|
│ │ Polygon.io │ │ MT4 Server │ │ MetaAPI.cloud │ │
|
|
│ │ api.polygon.io│ │ Broker │ │ metaapi.cloud │ │
|
|
│ └────────────────┘ └────────────────┘ └────────────────────────────────┘ │
|
|
└─────────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## 3. Componentes Implementados
|
|
|
|
### 3.1 Base de Datos (Migration 002)
|
|
|
|
**Archivo:** `apps/database/migrations/002_add_indexes_and_integrations.sql`
|
|
|
|
#### Nuevos Schemas
|
|
|
|
| Schema | Propósito |
|
|
|--------|-----------|
|
|
| `data_sources` | Configuración de proveedores de datos externos |
|
|
| `broker_integration` | Conexión con broker MT4 y tracking de precios |
|
|
|
|
#### Tablas Creadas
|
|
|
|
| Tabla | Schema | Descripción |
|
|
|-------|--------|-------------|
|
|
| `api_providers` | data_sources | Configuración de APIs (Polygon, Massive, MT4) |
|
|
| `ticker_mapping` | data_sources | Mapeo de símbolos entre sistemas |
|
|
| `data_sync_status` | data_sources | Estado de sincronización por ticker |
|
|
| `broker_accounts` | broker_integration | Cuentas MT4/MT5 configuradas |
|
|
| `broker_prices` | broker_integration | Precios bid/ask del broker |
|
|
| `spread_statistics` | broker_integration | Estadísticas de spread por sesión |
|
|
| `price_adjustment_model` | broker_integration | Modelo de ajuste de precios |
|
|
| `trade_execution` | broker_integration | Log de trades ejecutados |
|
|
|
|
#### Índices de Optimización
|
|
|
|
```sql
|
|
-- Índices para consultas ML
|
|
idx_ohlcv_5m_ticker_ts_close -- Consultas de cierre por ticker
|
|
idx_ohlcv_5m_ticker_high_low -- Búsqueda de máx/mín
|
|
idx_ohlcv_5m_timestamp_brin -- BRIN para series temporales
|
|
idx_ohlcv_5m_ml_features -- Covering index para features
|
|
|
|
-- Índices para trading
|
|
idx_entry_signals_rr -- Búsqueda por R:R ratio
|
|
idx_entry_signals_analysis -- Análisis de outcomes
|
|
idx_broker_prices_spread -- Análisis de spreads
|
|
```
|
|
|
|
#### Funciones SQL
|
|
|
|
| Función | Descripción |
|
|
|---------|-------------|
|
|
| `calculate_spread_adjusted_entry()` | Calcula R:R neto después del spread |
|
|
| `get_expected_spread()` | Estima spread por ticker y sesión |
|
|
| `adjust_price_to_broker()` | Ajusta precio de data source a broker |
|
|
|
|
### 3.2 Polygon/Massive API Client
|
|
|
|
**Archivo:** `apps/data-service/src/providers/polygon_client.py`
|
|
|
|
#### Características
|
|
|
|
- Soporte para múltiples tipos de activos:
|
|
- **Forex:** Prefijo `C:` (ej: `C:EURUSD`)
|
|
- **Crypto:** Prefijo `X:` (ej: `X:BTCUSD`)
|
|
- **Indices:** Prefijo `I:` (ej: `I:SPX`)
|
|
- **Futures:** Sin prefijo (ej: `GCZ2025`)
|
|
|
|
- Rate limiting automático (5 req/min plan básico)
|
|
- Paginación para datos históricos masivos
|
|
- Snapshots en tiempo real
|
|
- Caché de respuestas
|
|
|
|
#### Endpoints Soportados
|
|
|
|
| Endpoint | Método | Descripción |
|
|
|----------|--------|-------------|
|
|
| `/v2/aggs/ticker/{ticker}/range/{mult}/{timespan}/{from}/{to}` | GET | Datos OHLCV históricos |
|
|
| `/v2/snapshot/locale/global/markets/forex/tickers/{ticker}` | GET | Snapshot forex |
|
|
| `/v2/snapshot/locale/global/markets/crypto/tickers/{ticker}` | GET | Snapshot crypto |
|
|
| `/v3/snapshot` | GET | Universal snapshot (múltiples tickers) |
|
|
|
|
### 3.3 MetaTrader 4 Client
|
|
|
|
**Archivo:** `apps/data-service/src/providers/mt4_client.py`
|
|
|
|
#### Opciones de Conexión
|
|
|
|
1. **MetaAPIClient** (Recomendado)
|
|
- Usa servicio cloud MetaAPI.cloud
|
|
- No requiere terminal MT4
|
|
- REST API + WebSocket
|
|
- Soporta trading real
|
|
|
|
2. **MT4Client** (Directo)
|
|
- Conexión TCP directa al servidor
|
|
- Requiere protocolo propietario
|
|
- Más complejo de implementar
|
|
|
|
#### Funcionalidades
|
|
|
|
```python
|
|
# Obtener tick actual
|
|
tick = await client.get_tick("EURUSD")
|
|
# MT4Tick(symbol='EURUSD', bid=1.05432, ask=1.05435, spread=0.00003)
|
|
|
|
# Abrir orden
|
|
ticket = await client.open_order(
|
|
symbol="EURUSD",
|
|
order_type=OrderType.OP_BUY,
|
|
lots=0.1,
|
|
sl=1.0500,
|
|
tp=1.0600
|
|
)
|
|
|
|
# Tracking de spread
|
|
await spread_tracker.record_spread(
|
|
account_id=1,
|
|
ticker_id=2,
|
|
bid=1.05432,
|
|
ask=1.05435,
|
|
timestamp=datetime.now()
|
|
)
|
|
```
|
|
|
|
### 3.4 Price Adjustment Service
|
|
|
|
**Archivo:** `apps/data-service/src/services/price_adjustment.py`
|
|
|
|
#### Funcionalidades
|
|
|
|
1. **Estimación de Spread por Sesión**
|
|
|
|
```python
|
|
SESSION_MULTIPLIERS = {
|
|
"asian": 1.3, # Spreads más amplios
|
|
"london": 0.9, # Spreads más ajustados
|
|
"newyork": 0.95,
|
|
"overlap": 0.85, # Los más ajustados
|
|
"pacific": 1.2
|
|
}
|
|
```
|
|
|
|
2. **Ajuste de Precio por Volatilidad**
|
|
|
|
```python
|
|
# Alto volatilidad: spread x 1.5
|
|
# Baja volatilidad: spread x 1.0
|
|
```
|
|
|
|
3. **Cálculo de R:R Neto**
|
|
|
|
```python
|
|
result = await price_adjustment.calculate_adjusted_entry(
|
|
ticker_id=2,
|
|
entry_price=1.0550,
|
|
stop_loss=1.0500,
|
|
take_profit=1.0650,
|
|
signal_type="long"
|
|
)
|
|
# {
|
|
# "gross_rr": 2.0,
|
|
# "net_rr": 1.85,
|
|
# "rr_reduction_pct": 7.5,
|
|
# "spread_cost_pct": 0.014,
|
|
# "min_win_rate_for_profit": 35.1
|
|
# }
|
|
```
|
|
|
|
---
|
|
|
|
## 4. Análisis de Impacto
|
|
|
|
### 4.1 Módulos Afectados
|
|
|
|
| Módulo | Impacto | Tipo | Detalle |
|
|
|--------|---------|------|---------|
|
|
| **OQI-006 ML Signals** | Alto | Dependencia | Usa datos de `market_data.ohlcv_5m` |
|
|
| **OQI-003 Trading Charts** | Alto | Dependencia | Consume datos OHLCV para visualización |
|
|
| **OQI-008 Portfolio Manager** | Medio | Dependencia | Usa precios para cálculo de posiciones |
|
|
| **OQI-007 LLM Agent** | Bajo | Indirecto | Consulta datos via ML Engine |
|
|
| **OQI-004 Investment Accounts** | Bajo | Futuro | Usará trade_execution para órdenes |
|
|
|
|
### 4.2 Compatibilidad con Arquitectura Existente
|
|
|
|
#### ✅ Compatible
|
|
|
|
| Componente | Razón |
|
|
|------------|-------|
|
|
| Schema `market_data` | Tablas existentes no modificadas, solo se agregan índices |
|
|
| Schema `ml_predictions` | Se agregó columna `expected_spread` (ALTER TABLE) |
|
|
| API ML Engine | El Data Service es complementario, no reemplaza |
|
|
|
|
#### ⚠️ Requiere Integración
|
|
|
|
| Componente | Acción Requerida |
|
|
|------------|------------------|
|
|
| ML Engine (FastAPI) | Agregar endpoint para consultar spreads esperados |
|
|
| Backend (Express) | Agregar rutas `/api/data/*` para sync manual |
|
|
| Frontend (React) | Componente para mostrar spread actual |
|
|
|
|
### 4.3 Dependencias Externas
|
|
|
|
| Servicio | Requerido | Plan Mínimo | Costo |
|
|
|----------|-----------|-------------|-------|
|
|
| Polygon.io | Sí (datos) | Currencies Basic | $0/mes |
|
|
| MetaAPI.cloud | Opcional (trading) | Free tier | $0/mes |
|
|
| PostgreSQL | Sí | Local | $0 |
|
|
| Redis | Recomendado (caché) | Local | $0 |
|
|
|
|
### 4.4 Riesgos Identificados
|
|
|
|
| Riesgo | Probabilidad | Impacto | Mitigación |
|
|
|--------|--------------|---------|------------|
|
|
| Rate limiting API | Alta | Medio | Caché agresivo, backoff exponencial |
|
|
| Diferencia precios broker vs data | Media | Alto | Modelo de ajuste entrenado |
|
|
| Latencia en sincronización | Baja | Medio | Sync incremental cada 5 min |
|
|
| Fallo conexión MT4 | Media | Alto | Fallback a investor mode |
|
|
|
|
---
|
|
|
|
## 5. Matriz de Trazabilidad
|
|
|
|
### 5.1 Archivos Creados
|
|
|
|
| Archivo | Propósito | Dependencias |
|
|
|---------|-----------|--------------|
|
|
| `migrations/002_add_indexes_and_integrations.sql` | Schema DB | 001_create_market_data_schema.sql |
|
|
| `data-service/src/providers/polygon_client.py` | API Polygon | aiohttp, asyncpg |
|
|
| `data-service/src/providers/mt4_client.py` | API MT4 | aiohttp |
|
|
| `data-service/src/services/price_adjustment.py` | Ajuste precios | asyncpg, numpy |
|
|
| `data-service/src/config.py` | Configuración | python-dotenv |
|
|
| `data-service/src/main.py` | Entry point | apscheduler |
|
|
| `data-service/.env.example` | Variables entorno | - |
|
|
| `data-service/requirements.txt` | Dependencias Python | - |
|
|
|
|
### 5.2 Tablas y Relaciones
|
|
|
|
```
|
|
data_sources.api_providers
|
|
└── data_sources.ticker_mapping (provider_id FK)
|
|
└── data_sources.data_sync_status (provider_id FK)
|
|
|
|
market_data.tickers
|
|
└── data_sources.ticker_mapping (ticker_id FK)
|
|
└── broker_integration.broker_prices (ticker_id FK)
|
|
└── broker_integration.spread_statistics (ticker_id FK)
|
|
└── broker_integration.price_adjustment_model (ticker_id FK)
|
|
|
|
broker_integration.broker_accounts
|
|
└── broker_integration.broker_prices (account_id FK)
|
|
└── broker_integration.trade_execution (account_id FK)
|
|
|
|
ml_predictions.entry_signals
|
|
└── broker_integration.trade_execution (signal_id FK)
|
|
```
|
|
|
|
### 5.3 Flujo de Datos
|
|
|
|
```
|
|
[Polygon API] ──────────────┐
|
|
▼
|
|
[MySQL Legacy] ──► [PostgreSQL ohlcv_5m] ──► [ML Engine]
|
|
│ │
|
|
▼ ▼
|
|
[Technical Indicators] [Predictions]
|
|
│
|
|
▼
|
|
[MT4 Broker] ──► [broker_prices] ──► [entry_signals + spread]
|
|
│ │
|
|
▼ ▼
|
|
[spread_statistics] ──► [price_adjustment_model]
|
|
│
|
|
▼
|
|
[trade_execution]
|
|
```
|
|
|
|
---
|
|
|
|
## 6. Configuración
|
|
|
|
### 6.1 Variables de Entorno
|
|
|
|
```bash
|
|
# Database
|
|
DB_HOST=localhost
|
|
DB_PORT=5432
|
|
DB_NAME=trading_data
|
|
DB_USER=trading_user
|
|
DB_PASSWORD=trading_dev_2025
|
|
|
|
# Polygon API
|
|
POLYGON_API_KEY=your_api_key
|
|
POLYGON_BASE_URL=https://api.polygon.io
|
|
POLYGON_RATE_LIMIT=5
|
|
POLYGON_TIER=basic
|
|
|
|
# MetaAPI (opcional)
|
|
METAAPI_TOKEN=your_token
|
|
METAAPI_ACCOUNT_ID=your_account_id
|
|
|
|
# Sync
|
|
SYNC_INTERVAL_MINUTES=5
|
|
BACKFILL_DAYS=30
|
|
```
|
|
|
|
### 6.2 Ejecución del Servicio
|
|
|
|
```bash
|
|
cd apps/data-service
|
|
pip install -r requirements.txt
|
|
python src/main.py
|
|
```
|
|
|
|
---
|
|
|
|
## 7. Testing
|
|
|
|
### 7.1 Tests Unitarios Requeridos
|
|
|
|
- [ ] `test_polygon_client.py` - Conexión y parseo de respuestas
|
|
- [ ] `test_mt4_client.py` - Conexión y órdenes
|
|
- [ ] `test_price_adjustment.py` - Cálculos de spread y R:R
|
|
- [ ] `test_data_sync.py` - Sincronización incremental
|
|
|
|
### 7.2 Tests de Integración
|
|
|
|
- [ ] Sync completo de un ticker
|
|
- [ ] Cálculo de spread en diferentes sesiones
|
|
- [ ] Ajuste de precios broker vs data source
|
|
|
|
---
|
|
|
|
## 8. Próximos Pasos
|
|
|
|
1. **Inmediato:**
|
|
- Obtener API key de Polygon.io
|
|
- Configurar cuenta demo en MetaAPI.cloud
|
|
- Ejecutar tests de integración
|
|
|
|
2. **Corto plazo:**
|
|
- Integrar con ML Engine para consulta de spreads
|
|
- Crear dashboard de monitoreo de sync
|
|
- Implementar alertas de spread anormal
|
|
|
|
3. **Mediano plazo:**
|
|
- Entrenar modelo de ajuste con datos reales
|
|
- Implementar ejecución de trades via MT4
|
|
- Agregar más tickers (indices, commodities)
|
|
|
|
---
|
|
|
|
## 9. Referencias
|
|
|
|
- [Polygon.io Documentation](https://polygon.io/docs)
|
|
- [MetaAPI Documentation](https://metaapi.cloud/docs)
|
|
- [ET-ML-005: Integración Backend](../../02-definicion-modulos/OQI-006-ml-signals/especificaciones/ET-ML-005-integracion.md)
|
|
- [ARQUITECTURA-UNIFICADA](../../01-arquitectura/ARQUITECTURA-UNIFICADA.md)
|
|
|
|
---
|
|
|
|
## 10. Historial de Cambios
|
|
|
|
| Versión | Fecha | Autor | Cambios |
|
|
|---------|-------|-------|---------|
|
|
| 1.0.0 | 2025-12-05 | Database Agent | Creación inicial |
|
|
|
|
---
|
|
|
|
**Estado de Validación:**
|
|
|
|
| Aspecto | Estado | Notas |
|
|
|---------|--------|-------|
|
|
| Schema DB ejecutado | ✅ | Migration 002 aplicada |
|
|
| Índices creados | ✅ | 8 índices adicionales |
|
|
| Tickers insertados | ✅ | 7 nuevos (índices + commodities) |
|
|
| Mappings creados | ✅ | 25 mappings Polygon |
|
|
| Código Python | ✅ | Estructura completa |
|
|
| Tests | ⏳ | Pendiente |
|
|
| Documentación | ✅ | Este documento |
|