trading-platform/docs/90-transversal/setup/SETUP-MT4-TRADING.md
rckrdmrd c1b5081208 feat(ml): Complete FASE 11 - BTCUSD update and comprehensive documentation alignment
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>
2026-01-07 09:31:29 -06:00

346 lines
7.9 KiB
Markdown

---
id: "SETUP-MT4-TRADING"
title: "Setup MT4 Trading - EBC Financial Group"
type: "Documentation"
project: "trading-platform"
version: "1.0.0"
updated_date: "2026-01-04"
---
# Setup MT4 Trading - EBC Financial Group
**Fecha:** 2025-12-12
**Estado:** Configuración Inicial
**Broker:** EBC Financial Group (Demo)
---
## Resumen de Credenciales
### Polygon/Massive API (Datos de Mercado)
```
API_KEY: pxwp1peelaTqnKAGVCSEo2hHXVolpoT8
RATE_LIMIT: 5 requests/minuto (tier gratuito)
BASE_URL: https://api.polygon.io
```
### MT4 Demo Account (EBC)
```
SERVER: EBCFinancialGroupKY-Demo02
LOGIN: 22437
PASSWORD: AfcItz2391!
BROKER: EBC Financial Group
TIPO: Demo
```
---
## Opciones de Conexión a MT4
Hay **3 opciones** para conectar con MT4 y ejecutar operaciones:
### Opción 1: MetaAPI.cloud (RECOMENDADA)
MetaAPI es un servicio cloud que actúa como bridge hacia cualquier broker MT4/MT5.
**Ventajas:**
- No requiere terminal MT4 corriendo
- API REST + WebSocket
- Funciona en servidores cloud/VPS
- Soporte para todos los brokers
**Pasos de Configuración:**
1. **Crear cuenta en MetaAPI:**
```
https://app.metaapi.cloud/sign-up
```
2. **Obtener API Token:**
- Dashboard → Settings → API Access Tokens
- Crear token con permisos: `full-access`
- Guardar el token (solo se muestra una vez)
3. **Agregar cuenta MT4:**
- Dashboard → Accounts → Add Account
- Seleccionar: MetaTrader 4
- Llenar datos:
```
Name: Trading Platform Demo
Login: 22437
Password: AfcItz2391!
Server: EBCFinancialGroupKY-Demo02
Platform: mt4
Type: cloud-g2 (recomendado)
```
- Click "Add Account"
- Esperar deployment (1-2 minutos)
- Copiar el Account ID generado
4. **Configurar .env:**
```bash
METAAPI_TOKEN=eyJ...tu_token_aqui
METAAPI_ACCOUNT_ID=abc123...tu_account_id
```
5. **Verificar conexión:**
```bash
cd apps/data-service
python -c "
import asyncio
from src.providers.metaapi_client import MetaAPIClient
async def test():
client = MetaAPIClient()
await client.connect()
info = await client.get_account_info()
print(f'Connected! Balance: {info.balance} {info.currency}')
await client.disconnect()
asyncio.run(test())
"
```
**Costo:** Gratis hasta 1 cuenta, luego desde $10/mes
---
### Opción 2: Expert Advisor Bridge (Sin costo adicional)
Usar un EA (Expert Advisor) que expone una API local.
**Requiere:**
- Terminal MT4 corriendo 24/7
- VPS Windows (si quieres 24/7)
**EAs Recomendados:**
- MT4-to-REST (open source)
- ZeroMQ-MT4
**Pasos:**
1. **Descargar terminal MT4:**
```
https://www.ebc.com/ebc-download-center
```
2. **Login con credenciales demo**
3. **Instalar EA bridge:**
- Copiar EA a: `MT4/MQL4/Experts/`
- Reiniciar MT4
- Arrastrar EA al chart
- Habilitar "Allow DLL imports"
- Habilitar "Allow live trading"
4. **El EA expone API en:**
```
http://localhost:8080/api/...
```
---
### Opción 3: Conexión TCP Directa (Avanzado)
Conexión directa al servidor MT4 usando protocolo propietario.
**NO RECOMENDADO** - Requiere:
- Ingeniería reversa del protocolo
- Mantenimiento complejo
- Posibles bloqueos del broker
---
## Configuración de Pares de Trading
### Pares Iniciales (Prioridad)
| Par | Polygon Symbol | MT4 Symbol | Spread Típico | Sesión Óptima |
|-----|----------------|------------|---------------|---------------|
| XAU/USD | C:XAUUSD | XAUUSD | 25-35 pips | London/NY |
| EUR/USD | C:EURUSD | EURUSD | 0.8-1.5 pips | London/NY Overlap |
| GBP/USD | C:GBPUSD | GBPUSD | 1.2-2.0 pips | London |
| USD/JPY | C:USDJPY | USDJPY | 0.8-1.5 pips | Asian/London |
### Configuración Risk Management
```yaml
# Para cuenta de $200
starter_config:
max_risk_per_trade: 1% # = $2 máximo
max_daily_loss: 5% # = $10 máximo
max_open_positions: 1
allowed_pairs: [XAUUSD] # Solo oro inicialmente
lot_size: 0.01 # Micro lot
# Para cuenta de $1000
optimal_config:
max_risk_per_trade: 2% # = $20 máximo
max_daily_loss: 5% # = $50 máximo
max_open_positions: 3
allowed_pairs: [XAUUSD, EURUSD, GBPUSD, USDJPY]
lot_size_range: [0.01, 0.10]
```
---
## Sincronización de Datos (Polygon)
### Rate Limiting Adaptado
Con el tier gratuito de Polygon (5 req/min), la estrategia es:
```python
# Configuración actual
POLYGON_RATE_LIMIT=5 # 5 requests por minuto
RATE_LIMIT_DELAY_SECONDS=12 # 60/5 = 12 segundos entre requests
# Para 4 pares en sync:
# - 1 request por par cada 5 minutos = factible
# - Backfill histórico: ~48 segundos por día de datos
```
### Script de Sync Inicial
```bash
# Sync últimos 30 días para pares iniciales
cd apps/data-service
python -m src.main --backfill --days=30 --symbols=XAUUSD,EURUSD,GBPUSD,USDJPY
```
### Sync Automático (Cronjob)
```bash
# Agregar a crontab
*/5 * * * * cd /path/to/data-service && python -m src.main --sync
```
---
## Verificación de Setup
### 1. Test Polygon API
```bash
curl "https://api.polygon.io/v2/aggs/ticker/C:EURUSD/range/5/minute/2025-12-11/2025-12-12?apiKey=pxwp1peelaTqnKAGVCSEo2hHXVolpoT8"
```
Respuesta esperada:
```json
{
"ticker": "C:EURUSD",
"status": "OK",
"resultsCount": 288,
"results": [...]
}
```
### 2. Test MT4 Connection (con MetaAPI)
```python
import asyncio
from src.providers.metaapi_client import MetaAPIClient
async def test_mt4():
client = MetaAPIClient()
await client.connect()
# Info de cuenta
info = await client.get_account_info()
print(f"Balance: {info.balance}")
print(f"Equity: {info.equity}")
print(f"Leverage: {info.leverage}")
# Tick actual
tick = await client.get_tick("XAUUSD")
print(f"XAUUSD Bid: {tick.bid}, Ask: {tick.ask}, Spread: {tick.spread}")
await client.disconnect()
asyncio.run(test_mt4())
```
### 3. Test Trade Execution (DEMO ONLY)
```python
async def test_trade():
client = MetaAPIClient()
await client.connect()
# Abrir trade de prueba
result = await client.open_trade(
symbol="XAUUSD",
order_type=OrderType.BUY,
volume=0.01, # Micro lot
sl=None, # Sin SL por ahora
tp=None, # Sin TP por ahora
comment="Test Trading Platform"
)
if result.success:
print(f"Trade abierto! Position ID: {result.position_id}")
# Ver posiciones
positions = await client.get_positions()
for p in positions:
print(f"Position: {p.symbol} {p.type} @ {p.open_price}")
# Cerrar inmediatamente
close_result = await client.close_position(result.position_id)
print(f"Trade cerrado: {close_result.success}")
else:
print(f"Error: {result.error_message}")
await client.disconnect()
asyncio.run(test_trade())
```
---
## Próximos Pasos
1. **[ ] Crear cuenta MetaAPI.cloud**
- Registrarse en https://app.metaapi.cloud
- Agregar cuenta MT4 de EBC
- Obtener token y account_id
2. **[ ] Verificar conexión Polygon**
- Test del endpoint con curl
- Verificar rate limiting
3. **[ ] Backfill datos históricos**
- Ejecutar sync inicial para 4 pares
- Verificar datos en PostgreSQL
4. **[ ] Test de trading en demo**
- Abrir/cerrar trade de prueba
- Verificar logging
---
## Troubleshooting
### Error: "Rate limit exceeded" (Polygon)
- Reducir frecuencia de requests
- El código ya tiene rate limiting de 5 req/min
### Error: "Account deployment failed" (MetaAPI)
- Verificar credenciales MT4
- El servidor debe estar correcto
- Intentar con tipo `cloud-g1` en lugar de `cloud-g2`
### Error: "Connection timeout" (MT4)
- Verificar que el servidor está disponible
- EBC servers pueden tener mantenimiento fines de semana
### Error: "Invalid volume"
- El volumen mínimo es 0.01 lots
- Verificar configuración del símbolo
---
**Archivo de configuración:** `apps/data-service/.env`
**Documentación MetaAPI:** https://metaapi.cloud/docs
**Documentación Polygon:** https://polygon.io/docs