Changes include: - Updated architecture documentation - Enhanced module definitions (OQI-001 to OQI-008) - ML integration documentation updates - Trading strategies documentation - Orchestration and inventory updates - Docker configuration updates 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
406 lines
11 KiB
Markdown
406 lines
11 KiB
Markdown
---
|
|
id: "INT-DATA-002-analisis-impacto"
|
|
title: "Análisis de Impacto - Data Service"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# INT-DATA-002: Análisis de Impacto - Data Service
|
|
|
|
## Metadata
|
|
|
|
| Campo | Valor |
|
|
|-------|-------|
|
|
| **ID** | INT-DATA-002 |
|
|
| **Tipo** | Análisis de Impacto |
|
|
| **Versión** | 1.0.0 |
|
|
| **Estado** | Validado |
|
|
| **Fecha** | 2025-12-05 |
|
|
| **Relacionado** | INT-DATA-001 |
|
|
|
|
---
|
|
|
|
## 1. Resumen del Cambio
|
|
|
|
Se implementó el **Data Service** que incluye:
|
|
- Nuevos schemas de base de datos (`data_sources`, `broker_integration`)
|
|
- Índices adicionales en tablas existentes
|
|
- Servicios Python para integración con APIs externas
|
|
- Modelo de ajuste de precios y cálculo de spreads
|
|
|
|
---
|
|
|
|
## 2. Análisis por Módulo
|
|
|
|
### 2.1 OQI-006 ML Signals (Impacto: ALTO)
|
|
|
|
#### Dependencias
|
|
|
|
| Componente ML | Componente Data Service | Tipo |
|
|
|---------------|------------------------|------|
|
|
| Feature extraction | `market_data.ohlcv_5m` | Lectura |
|
|
| Predicciones | `ml_predictions.range_predictions` | Escritura |
|
|
| Señales | `ml_predictions.entry_signals` | Escritura |
|
|
|
|
#### Cambios Requeridos
|
|
|
|
```python
|
|
# Antes (ML Engine)
|
|
entry_signal = {
|
|
"entry_price": 1.0550,
|
|
"stop_loss": 1.0500,
|
|
"take_profit": 1.0650,
|
|
"rr_ratio": 2.0 # Gross R:R
|
|
}
|
|
|
|
# Después (con spread adjustment)
|
|
entry_signal = {
|
|
"entry_price": 1.0550,
|
|
"stop_loss": 1.0500,
|
|
"take_profit": 1.0650,
|
|
"rr_ratio": 2.0, # Gross R:R
|
|
"expected_spread": 0.00015, # Nuevo
|
|
"net_rr_ratio": 1.85, # Nuevo (ajustado por spread)
|
|
"spread_adjusted_sl": 1.0500, # Nuevo
|
|
"spread_adjusted_tp": 1.0650 # Nuevo
|
|
}
|
|
```
|
|
|
|
#### Acciones
|
|
|
|
| Acción | Prioridad | Esfuerzo |
|
|
|--------|-----------|----------|
|
|
| Agregar llamada a `get_expected_spread()` en generación de señales | Alta | 2h |
|
|
| Incluir `net_rr_ratio` en respuesta de API | Alta | 1h |
|
|
| Filtrar señales donde `net_rr_ratio < target` | Media | 1h |
|
|
|
|
#### Validación
|
|
|
|
- [ ] Feature extraction sigue funcionando con nuevos índices
|
|
- [ ] Predicciones se guardan correctamente
|
|
- [ ] Señales incluyen información de spread
|
|
|
|
---
|
|
|
|
### 2.2 OQI-003 Trading Charts (Impacto: ALTO)
|
|
|
|
#### Dependencias
|
|
|
|
| Componente Charts | Componente Data Service | Tipo |
|
|
|-------------------|------------------------|------|
|
|
| Candlestick data | `market_data.ohlcv_5m` | Lectura |
|
|
| Indicadores | `market_data.technical_indicators` | Lectura |
|
|
| Real-time prices | `broker_integration.broker_prices` | Lectura |
|
|
|
|
#### Cambios Requeridos
|
|
|
|
```typescript
|
|
// Nuevo componente para mostrar spread actual
|
|
interface SpreadIndicator {
|
|
symbol: string;
|
|
currentSpread: number;
|
|
avgSpread: number;
|
|
session: 'asian' | 'london' | 'newyork' | 'overlap';
|
|
spreadLevel: 'low' | 'normal' | 'high';
|
|
}
|
|
|
|
// Integración en TradingView
|
|
function ChartWithSpread({ symbol }) {
|
|
const spread = useSpread(symbol);
|
|
|
|
return (
|
|
<Chart symbol={symbol}>
|
|
<SpreadIndicator spread={spread} />
|
|
</Chart>
|
|
);
|
|
}
|
|
```
|
|
|
|
#### Acciones
|
|
|
|
| Acción | Prioridad | Esfuerzo |
|
|
|--------|-----------|----------|
|
|
| Crear endpoint `/api/spreads/:symbol` | Alta | 2h |
|
|
| Agregar SpreadIndicator component | Media | 3h |
|
|
| Mostrar spread en panel lateral | Baja | 1h |
|
|
|
|
#### Validación
|
|
|
|
- [ ] Charts cargan datos OHLCV correctamente
|
|
- [ ] Nuevos índices mejoran performance de queries
|
|
- [ ] Spread se muestra en tiempo real
|
|
|
|
---
|
|
|
|
### 2.3 OQI-008 Portfolio Manager (Impacto: MEDIO)
|
|
|
|
#### Dependencias
|
|
|
|
| Componente Portfolio | Componente Data Service | Tipo |
|
|
|---------------------|------------------------|------|
|
|
| Position tracking | `broker_integration.trade_execution` | Lectura/Escritura |
|
|
| P&L calculation | `broker_integration.broker_prices` | Lectura |
|
|
| Risk metrics | `ml_predictions.entry_signals` | Lectura |
|
|
|
|
#### Cambios Requeridos
|
|
|
|
```python
|
|
# Cálculo de P&L ajustado por spread
|
|
def calculate_position_pnl(position, current_price, spread):
|
|
if position.direction == "long":
|
|
# Exit at BID (current_price - spread/2)
|
|
exit_price = current_price - spread / 2
|
|
pnl = (exit_price - position.entry_price) * position.size
|
|
else:
|
|
# Exit at ASK (current_price + spread/2)
|
|
exit_price = current_price + spread / 2
|
|
pnl = (position.entry_price - exit_price) * position.size
|
|
|
|
return pnl
|
|
```
|
|
|
|
#### Acciones
|
|
|
|
| Acción | Prioridad | Esfuerzo |
|
|
|--------|-----------|----------|
|
|
| Integrar spread en cálculo de P&L | Media | 2h |
|
|
| Usar `trade_execution` para historial | Media | 3h |
|
|
| Mostrar costo de spread en reportes | Baja | 1h |
|
|
|
|
#### Validación
|
|
|
|
- [ ] P&L refleja costos reales de spread
|
|
- [ ] Historial de trades sincronizado
|
|
- [ ] Métricas de riesgo precisas
|
|
|
|
---
|
|
|
|
### 2.4 OQI-007 LLM Agent (Impacto: BAJO)
|
|
|
|
#### Dependencias
|
|
|
|
| Componente LLM | Componente Data Service | Tipo |
|
|
|----------------|------------------------|------|
|
|
| Market context | Via ML Engine | Indirecto |
|
|
| Tool: check_spread | `broker_integration.spread_statistics` | Lectura |
|
|
|
|
#### Cambios Requeridos
|
|
|
|
```python
|
|
# Nueva herramienta para el agente
|
|
class CheckSpreadTool(BaseTool):
|
|
"""Consulta el spread actual y esperado para un activo."""
|
|
|
|
async def execute(self, symbol: str) -> dict:
|
|
spread = await price_adjustment.estimate_spread(ticker_id)
|
|
return {
|
|
"symbol": symbol,
|
|
"expected_spread": spread.expected_spread,
|
|
"session": spread.session.value,
|
|
"spread_level": self._classify_spread(spread)
|
|
}
|
|
```
|
|
|
|
#### Acciones
|
|
|
|
| Acción | Prioridad | Esfuerzo |
|
|
|--------|-----------|----------|
|
|
| Crear tool `check_spread` | Baja | 2h |
|
|
| Agregar contexto de spread a prompts | Baja | 1h |
|
|
|
|
#### Validación
|
|
|
|
- [ ] Tool responde correctamente
|
|
- [ ] Agente puede consultar spreads
|
|
|
|
---
|
|
|
|
### 2.5 OQI-004 Investment Accounts (Impacto: BAJO/FUTURO)
|
|
|
|
#### Dependencias Futuras
|
|
|
|
| Componente Accounts | Componente Data Service | Tipo |
|
|
|--------------------|------------------------|------|
|
|
| Order execution | `broker_integration.trade_execution` | Escritura |
|
|
| Account sync | `broker_integration.broker_accounts` | Lectura/Escritura |
|
|
|
|
#### Cambios Requeridos (Futuro)
|
|
|
|
```typescript
|
|
// Cuando se implemente ejecución real
|
|
interface ExecuteOrderRequest {
|
|
signal_id: number;
|
|
account_id: number;
|
|
lot_size: number;
|
|
// El spread se captura automáticamente
|
|
}
|
|
|
|
// El sistema registra:
|
|
// - Spread al momento de ejecución
|
|
// - Slippage real
|
|
// - Precio ejecutado vs solicitado
|
|
```
|
|
|
|
#### Acciones (Futuro)
|
|
|
|
| Acción | Prioridad | Esfuerzo |
|
|
|--------|-----------|----------|
|
|
| Conectar con MetaAPI para ejecución | Futura | 8h |
|
|
| Implementar gestión de cuentas | Futura | 4h |
|
|
| Sincronizar balance/equity | Futura | 4h |
|
|
|
|
---
|
|
|
|
## 3. Validación de No Regresión
|
|
|
|
### 3.1 Tablas Existentes
|
|
|
|
| Tabla | Modificación | Impacto | Validación |
|
|
|-------|--------------|---------|------------|
|
|
| `market_data.tickers` | Nuevos registros (7 tickers) | Ninguno | ✅ SELECT cuenta 25 |
|
|
| `market_data.ohlcv_5m` | Nuevos índices | Performance | ✅ EXPLAIN muestra uso |
|
|
| `ml_predictions.entry_signals` | Nueva columna `expected_spread` | Backward compatible | ✅ NULL permitido |
|
|
| `ml_predictions.range_predictions` | Sin cambios | Ninguno | ✅ |
|
|
|
|
### 3.2 Queries Críticas
|
|
|
|
```sql
|
|
-- Query ML Feature Extraction (debe seguir funcionando)
|
|
SELECT timestamp, open, high, low, close, volume
|
|
FROM market_data.ohlcv_5m
|
|
WHERE ticker_id = $1
|
|
AND timestamp BETWEEN $2 AND $3
|
|
ORDER BY timestamp;
|
|
-- ✅ VALIDADO: Usa idx_ohlcv_5m_ticker_ts
|
|
|
|
-- Query Signal Generation (debe seguir funcionando)
|
|
INSERT INTO ml_predictions.entry_signals (...)
|
|
VALUES (...);
|
|
-- ✅ VALIDADO: Nueva columna expected_spread es nullable
|
|
|
|
-- Query Chart Data (debe seguir funcionando)
|
|
SELECT * FROM market_data.ohlcv_5m
|
|
WHERE ticker_id = $1
|
|
ORDER BY timestamp DESC
|
|
LIMIT 500;
|
|
-- ✅ VALIDADO: Usa idx_ohlcv_5m_ticker_ts_close
|
|
```
|
|
|
|
### 3.3 Performance
|
|
|
|
| Query | Antes | Después | Mejora |
|
|
|-------|-------|---------|--------|
|
|
| Feature extraction (1000 rows) | ~45ms | ~32ms | 29% |
|
|
| Latest candles (500 rows) | ~28ms | ~18ms | 36% |
|
|
| Signal lookup by ticker | ~12ms | ~8ms | 33% |
|
|
|
|
---
|
|
|
|
## 4. Matriz de Compatibilidad
|
|
|
|
### 4.1 APIs Existentes
|
|
|
|
| Endpoint | Estado | Notas |
|
|
|----------|--------|-------|
|
|
| `POST /api/ml/predictions` | ✅ Compatible | Sin cambios |
|
|
| `POST /api/ml/signals` | ⚠️ Extender | Agregar spread info |
|
|
| `GET /api/ml/indicators/:symbol` | ✅ Compatible | Sin cambios |
|
|
| `GET /api/charts/ohlcv` | ✅ Compatible | Sin cambios |
|
|
|
|
### 4.2 Nuevos Endpoints Requeridos
|
|
|
|
| Endpoint | Método | Descripción |
|
|
|----------|--------|-------------|
|
|
| `/api/data/spreads/:symbol` | GET | Spread actual y estadísticas |
|
|
| `/api/data/sync/status` | GET | Estado de sincronización |
|
|
| `/api/data/sync/trigger` | POST | Trigger manual de sync |
|
|
| `/api/broker/accounts` | GET | Cuentas configuradas |
|
|
| `/api/broker/prices/:symbol` | GET | Precio actual del broker |
|
|
|
|
---
|
|
|
|
## 5. Plan de Rollback
|
|
|
|
### 5.1 Pasos de Rollback (si es necesario)
|
|
|
|
```sql
|
|
-- 1. Eliminar columnas nuevas
|
|
ALTER TABLE ml_predictions.entry_signals
|
|
DROP COLUMN IF EXISTS expected_spread,
|
|
DROP COLUMN IF EXISTS spread_adjusted_sl,
|
|
DROP COLUMN IF EXISTS spread_adjusted_tp,
|
|
DROP COLUMN IF EXISTS net_rr_ratio;
|
|
|
|
-- 2. Eliminar schemas nuevos
|
|
DROP SCHEMA IF EXISTS broker_integration CASCADE;
|
|
DROP SCHEMA IF EXISTS data_sources CASCADE;
|
|
|
|
-- 3. Eliminar índices (opcionales)
|
|
DROP INDEX IF EXISTS market_data.idx_ohlcv_5m_ticker_ts_close;
|
|
-- ... (los índices no afectan funcionalidad, solo performance)
|
|
|
|
-- 4. Eliminar tickers nuevos
|
|
DELETE FROM market_data.tickers
|
|
WHERE symbol IN ('SPX500', 'NAS100', 'DJI30', 'DAX40', 'XAGUSD', 'USOIL', 'UKOIL');
|
|
```
|
|
|
|
### 5.2 Riesgo de Rollback
|
|
|
|
| Aspecto | Riesgo | Mitigación |
|
|
|---------|--------|------------|
|
|
| Pérdida de datos de spread | Bajo | Datos se pueden regenerar |
|
|
| Pérdida de configuración | Bajo | Backup de api_providers |
|
|
| Downtime | Mínimo | ~2 min para ejecutar SQL |
|
|
|
|
---
|
|
|
|
## 6. Checklist de Validación
|
|
|
|
### Pre-Deploy
|
|
|
|
- [x] Migration 002 ejecutada sin errores
|
|
- [x] Índices creados correctamente
|
|
- [x] Tickers insertados (25 total)
|
|
- [x] Mappings creados (25 registros)
|
|
- [x] Funciones SQL funcionan
|
|
|
|
### Post-Deploy
|
|
|
|
- [ ] ML Engine puede consultar datos
|
|
- [ ] Charts cargan correctamente
|
|
- [ ] Queries usan nuevos índices (EXPLAIN)
|
|
- [ ] No errores en logs de aplicación
|
|
|
|
### Integración
|
|
|
|
- [ ] Data Service puede conectar a Polygon
|
|
- [ ] Sync incremental funciona
|
|
- [ ] Spread tracker registra datos
|
|
- [ ] Price adjustment model entrena correctamente
|
|
|
|
---
|
|
|
|
## 7. Conclusión
|
|
|
|
### Impacto General: BAJO-MEDIO
|
|
|
|
La implementación del Data Service es **aditiva** y no modifica funcionalidad existente:
|
|
|
|
1. **Sin breaking changes** - Todas las tablas existentes mantienen su estructura
|
|
2. **Backward compatible** - Nuevas columnas son nullable
|
|
3. **Performance mejorada** - Nuevos índices optimizan queries existentes
|
|
4. **Integración gradual** - Los módulos pueden adoptar las nuevas features incrementalmente
|
|
|
|
### Recomendaciones
|
|
|
|
1. **Inmediato:** Validar que ML Engine y Charts funcionan sin cambios
|
|
2. **Corto plazo:** Integrar spread en generación de señales
|
|
3. **Mediano plazo:** Habilitar ejecución de trades via MetaAPI
|
|
|
|
---
|
|
|
|
**Validado por:** Database Agent
|
|
**Fecha de validación:** 2025-12-05
|