Data aggregation and distribution service: - Market data collection - OHLCV aggregation - Real-time data feeds - Data API endpoints Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
376 lines
9.5 KiB
Markdown
376 lines
9.5 KiB
Markdown
# Data Service - Massive.com Integration
|
|
|
|
## Resumen
|
|
|
|
Integración completa de Massive.com (rebrand de Polygon.io) para el Data Service de Trading Platform.
|
|
|
|
## Características Implementadas
|
|
|
|
### 1. Cliente Polygon/Massive Mejorado
|
|
- **Archivo**: `src/providers/polygon_client.py`
|
|
- Soporte para ambas URLs (api.polygon.io y api.massive.com)
|
|
- Rate limiting inteligente (5 req/min para tier gratuito)
|
|
- Soporte completo de timeframes: 1m, 5m, 15m, 1h, 4h, 1d
|
|
- Manejo robusto de errores y reintentos
|
|
- Async/await nativo para mejor performance
|
|
|
|
### 2. Servicio de Sincronización
|
|
- **Archivo**: `src/services/sync_service.py`
|
|
- Sincronización automática de datos históricos
|
|
- Backfill inteligente desde última sincronización
|
|
- Inserción por lotes para mejor performance
|
|
- Tracking de estado de sincronización
|
|
- Soporte multi-timeframe
|
|
|
|
### 3. Endpoints de Sincronización
|
|
- **Archivo**: `src/api/sync_routes.py`
|
|
|
|
#### Endpoints Disponibles:
|
|
|
|
```
|
|
GET /api/sync/symbols - Lista de símbolos soportados
|
|
GET /api/sync/symbols/{symbol} - Info de símbolo específico
|
|
POST /api/sync/sync/{symbol} - Sincronizar símbolo
|
|
POST /api/sync/sync-all - Sincronizar todos los símbolos
|
|
GET /api/sync/status - Estado de sincronización
|
|
GET /api/sync/status/{symbol} - Estado de símbolo específico
|
|
GET /api/sync/health - Health check del servicio
|
|
```
|
|
|
|
### 4. Scheduler Automático
|
|
- **Archivo**: `src/services/scheduler.py`
|
|
- Sincronización periódica automática:
|
|
- **1min data**: Cada minuto
|
|
- **5min data**: Cada 5 minutos
|
|
- **15min data**: Cada 15 minutos
|
|
- **1h data**: Cada hora
|
|
- **4h data**: Cada 4 horas
|
|
- **Daily data**: Diariamente a medianoche UTC
|
|
- Limpieza automática de datos antiguos (semanal)
|
|
|
|
### 5. Tests Básicos
|
|
- **Archivos**: `tests/test_*.py`
|
|
- Tests unitarios para sync_service
|
|
- Tests unitarios para polygon_client
|
|
- Coverage de funcionalidad crítica
|
|
|
|
## Instalación
|
|
|
|
### Dependencias Adicionales
|
|
|
|
Agregar al `requirements.txt`:
|
|
|
|
```txt
|
|
apscheduler>=3.10.4
|
|
pytest>=7.4.0
|
|
pytest-asyncio>=0.21.0
|
|
```
|
|
|
|
### Variables de Entorno
|
|
|
|
```bash
|
|
# API Keys (usar una de las dos)
|
|
POLYGON_API_KEY=your_polygon_api_key
|
|
MASSIVE_API_KEY=your_massive_api_key # Funciona igual que Polygon
|
|
|
|
# Base URL (opcional - por defecto usa api.polygon.io)
|
|
POLYGON_BASE_URL=https://api.polygon.io
|
|
# O para usar Massive directamente:
|
|
# POLYGON_BASE_URL=https://api.massive.com
|
|
|
|
# Rate Limiting
|
|
POLYGON_RATE_LIMIT=5 # requests por minuto (tier gratuito)
|
|
POLYGON_TIER=basic # basic, starter, advanced
|
|
|
|
# Sync Configuration
|
|
ENABLE_SYNC_SCHEDULER=true
|
|
SYNC_INTERVAL_MINUTES=5
|
|
BACKFILL_DAYS=30
|
|
|
|
# Database
|
|
DB_HOST=localhost
|
|
DB_PORT=5432
|
|
DB_NAME=trading_data
|
|
DB_USER=trading_user
|
|
DB_PASSWORD=trading_dev_2025
|
|
```
|
|
|
|
## Uso
|
|
|
|
### 1. Iniciar el Servicio
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform/apps/data-service
|
|
|
|
# Instalar dependencias
|
|
pip install -r requirements.txt
|
|
|
|
# Copiar app actualizado
|
|
cp src/app_updated.py src/app.py
|
|
|
|
# Iniciar servicio
|
|
python src/app.py
|
|
```
|
|
|
|
### 2. Ver Símbolos Disponibles
|
|
|
|
```bash
|
|
curl http://localhost:8001/api/sync/symbols
|
|
```
|
|
|
|
Respuesta:
|
|
```json
|
|
{
|
|
"symbols": [
|
|
{
|
|
"symbol": "EURUSD",
|
|
"polygon_symbol": "C:EURUSD",
|
|
"mt4_symbol": "EURUSD",
|
|
"asset_type": "forex",
|
|
"pip_value": 0.0001,
|
|
"supported": true
|
|
}
|
|
],
|
|
"total": 45,
|
|
"asset_types": ["forex", "crypto", "index"]
|
|
}
|
|
```
|
|
|
|
### 3. Sincronizar un Símbolo
|
|
|
|
```bash
|
|
curl -X POST "http://localhost:8001/api/sync/sync/EURUSD" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"asset_type": "forex",
|
|
"timeframe": "5min",
|
|
"backfill_days": 30
|
|
}'
|
|
```
|
|
|
|
Respuesta:
|
|
```json
|
|
{
|
|
"status": "success",
|
|
"symbol": "EURUSD",
|
|
"timeframe": "5min",
|
|
"rows_inserted": 8640,
|
|
"start_date": "2024-11-08T00:00:00",
|
|
"end_date": "2024-12-08T00:00:00"
|
|
}
|
|
```
|
|
|
|
### 4. Ver Estado de Sincronización
|
|
|
|
```bash
|
|
curl http://localhost:8001/api/sync/status
|
|
```
|
|
|
|
Respuesta:
|
|
```json
|
|
[
|
|
{
|
|
"symbol": "EURUSD",
|
|
"asset_type": "forex",
|
|
"timeframe": "5min",
|
|
"last_sync": "2024-12-08T20:00:00",
|
|
"rows_synced": 8640,
|
|
"status": "success",
|
|
"error": null,
|
|
"updated_at": "2024-12-08T20:05:00"
|
|
}
|
|
]
|
|
```
|
|
|
|
### 5. Ver Estado del Scheduler
|
|
|
|
```bash
|
|
curl http://localhost:8001/scheduler/status
|
|
```
|
|
|
|
Respuesta:
|
|
```json
|
|
{
|
|
"enabled": true,
|
|
"running": true,
|
|
"jobs": [
|
|
{
|
|
"id": "sync_5min",
|
|
"name": "Sync 5-minute data",
|
|
"next_run": "2024-12-08T20:10:00",
|
|
"trigger": "interval[0:05:00]"
|
|
}
|
|
],
|
|
"total_jobs": 7
|
|
}
|
|
```
|
|
|
|
## Arquitectura
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────┐
|
|
│ FastAPI Application │
|
|
│ (app.py) │
|
|
└────────────┬────────────────────────────────────────────┘
|
|
│
|
|
┌───────┴───────┐
|
|
│ │
|
|
┌────▼─────┐ ┌────▼──────┐
|
|
│ Market │ │ Sync │
|
|
│ Data │ │ Routes │
|
|
│ Routes │ │ │
|
|
└────┬─────┘ └────┬──────┘
|
|
│ │
|
|
│ ┌────▼──────────┐
|
|
│ │ Sync Service │
|
|
│ │ │
|
|
│ └────┬──────────┘
|
|
│ │
|
|
│ ┌────▼──────────┐
|
|
│ │ Scheduler │
|
|
│ │ Manager │
|
|
│ └────┬──────────┘
|
|
│ │
|
|
┌────▼──────────────▼─────┐
|
|
│ Polygon/Massive │
|
|
│ Client │
|
|
│ (polygon_client.py) │
|
|
└────┬────────────────────┘
|
|
│
|
|
┌────▼──────────────┐
|
|
│ Massive.com API │
|
|
│ (api.polygon.io) │
|
|
└───────────────────┘
|
|
```
|
|
|
|
## Timeframes Soportados
|
|
|
|
| Timeframe | Valor Enum | Tabla DB | Sync Interval |
|
|
|-----------|-----------|----------|---------------|
|
|
| 1 minuto | `MINUTE_1` | `ohlcv_1min` | Cada 1 min |
|
|
| 5 minutos | `MINUTE_5` | `ohlcv_5min` | Cada 5 min |
|
|
| 15 minutos | `MINUTE_15` | `ohlcv_15min` | Cada 15 min |
|
|
| 1 hora | `HOUR_1` | `ohlcv_1hour` | Cada 1 hora |
|
|
| 4 horas | `HOUR_4` | `ohlcv_4hour` | Cada 4 horas |
|
|
| Diario | `DAY_1` | `ohlcv_daily` | Diario |
|
|
|
|
## Asset Types Soportados
|
|
|
|
| Asset Type | Prefix | Ejemplo | Cantidad |
|
|
|-----------|--------|---------|----------|
|
|
| Forex | `C:` | C:EURUSD | 25+ pares |
|
|
| Crypto | `X:` | X:BTCUSD | 1+ |
|
|
| Índices | `I:` | I:SPX | 4+ |
|
|
| Stocks | (none) | AAPL | Configurable |
|
|
|
|
## Rate Limits
|
|
|
|
### Tier Gratuito (Basic)
|
|
- 5 requests/minuto
|
|
- Implementado con rate limiting automático
|
|
- Retry automático en caso de 429
|
|
|
|
### Tier Starter
|
|
- 100 requests/minuto
|
|
- Configurar: `POLYGON_RATE_LIMIT=100`
|
|
|
|
### Tier Advanced
|
|
- Sin límites
|
|
- Configurar: `POLYGON_RATE_LIMIT=999`
|
|
|
|
## Manejo de Errores
|
|
|
|
El servicio incluye manejo robusto de errores:
|
|
|
|
1. **Rate Limiting**: Espera automática cuando se alcanza el límite
|
|
2. **Reintentos**: Retry en caso de errores temporales
|
|
3. **Logging**: Todas las operaciones se registran
|
|
4. **Estado de Sync**: Tracking de errores en base de datos
|
|
5. **Partial Success**: Guarda datos parciales si hay errores
|
|
|
|
## Estructura de Base de Datos
|
|
|
|
### Tabla sync_status
|
|
|
|
```sql
|
|
CREATE TABLE IF NOT EXISTS market_data.sync_status (
|
|
id SERIAL PRIMARY KEY,
|
|
ticker_id INTEGER REFERENCES market_data.tickers(id),
|
|
timeframe VARCHAR(20) NOT NULL,
|
|
last_sync_timestamp TIMESTAMP,
|
|
last_sync_rows INTEGER,
|
|
sync_status VARCHAR(20),
|
|
error_message TEXT,
|
|
updated_at TIMESTAMP DEFAULT NOW(),
|
|
UNIQUE(ticker_id, timeframe)
|
|
);
|
|
```
|
|
|
|
## Testing
|
|
|
|
### Ejecutar Tests
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform/apps/data-service
|
|
|
|
# Instalar pytest
|
|
pip install pytest pytest-asyncio
|
|
|
|
# Ejecutar todos los tests
|
|
pytest tests/ -v
|
|
|
|
# Ejecutar tests específicos
|
|
pytest tests/test_sync_service.py -v
|
|
pytest tests/test_polygon_client.py -v
|
|
|
|
# Con coverage
|
|
pytest tests/ --cov=src --cov-report=html
|
|
```
|
|
|
|
## Próximos Pasos
|
|
|
|
1. **Configurar API Key**: Obtener API key de Massive.com o Polygon.io
|
|
2. **Crear Tablas**: Ejecutar migrations de base de datos
|
|
3. **Iniciar Servicio**: Levantar el Data Service
|
|
4. **Sync Inicial**: Ejecutar backfill de datos históricos
|
|
5. **Monitoreo**: Verificar logs y estado de sincronización
|
|
|
|
## Troubleshooting
|
|
|
|
### Problema: API Key inválida
|
|
```
|
|
Solución: Verificar POLYGON_API_KEY en .env
|
|
```
|
|
|
|
### Problema: Rate limit excedido
|
|
```
|
|
Solución: Reducir POLYGON_RATE_LIMIT o esperar 1 minuto
|
|
```
|
|
|
|
### Problema: Scheduler no inicia
|
|
```
|
|
Solución: Verificar ENABLE_SYNC_SCHEDULER=true
|
|
```
|
|
|
|
### Problema: No hay datos
|
|
```
|
|
Solución: Ejecutar POST /api/sync/sync/{symbol} manualmente
|
|
```
|
|
|
|
## Soporte
|
|
|
|
Para más información sobre Massive.com/Polygon.io:
|
|
- Documentación: https://polygon.io/docs
|
|
- Massive.com: https://massive.com
|
|
- Dashboard: https://polygon.io/dashboard
|
|
|
|
## Changelog
|
|
|
|
### v2.0.0 (2024-12-08)
|
|
- Integración completa de Massive.com/Polygon.io
|
|
- Servicio de sincronización automática
|
|
- Scheduler con múltiples timeframes
|
|
- Endpoints de administración de sync
|
|
- Tests unitarios básicos
|
|
- Documentación completa
|