trading-platform/docs/01-arquitectura/ARQUITECTURA-MULTI-AGENTE-MT4.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

603 lines
25 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: "ARQUITECTURA-MULTI-AGENTE-MT4"
title: "Arquitectura Multi-Agente MT4"
type: "Documentation"
project: "trading-platform"
version: "1.0.0"
updated_date: "2026-01-04"
---
# Arquitectura Multi-Agente MT4
**Fecha:** 2025-12-12
**Estado:** Diseño
**Contexto:** Soporte para múltiples cuentas MT4 independientes, cada una con su agente de trading
---
## Resumen Ejecutivo
Esta arquitectura permite ejecutar **múltiples agentes de trading**, cada uno con:
- Su propia cuenta MT4 en EBC (u otro broker)
- Terminal MT4 independiente
- Estrategia/configuración personalizada
- Risk management aislado
---
## Arquitectura General
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ TRADING MULTI-AGENT PLATFORM │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ ADMIN DASHBOARD (React) │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │ │
│ │ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │ Global │ │ │
│ │ │ Overview │ │ Overview │ │ Overview │ │ Summary │ │ │
│ │ │ $847 │ │ $1,234 │ │ $567 │ │ $2,648 │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────────┐ │
│ │ ORCHESTRATION LAYER (Python) │ │
│ │ ┌───────────────────────────────────────────────────────────────────┐│ │
│ │ │ AgentOrchestrator ││ │
│ │ │ • Distribuye señales a agentes ││ │
│ │ │ • Coordina risk management global ││ │
│ │ │ • Consolida reporting ││ │
│ │ └───────────────────────────────────────────────────────────────────┘│ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────────┐ │
│ │ ML ENGINE (FastAPI) │ │
│ │ Señales compartidas para todos los agentes │ │
│ │ • AMDDetector → RangePredictor → TPSLClassifier │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────────┐ │
│ │ MT4 GATEWAY SERVICE (FastAPI) │ │
│ │ │ │
│ │ ┌─────────────────────────────────────────────────────────────────┐ │ │
│ │ │ AgentRegistry │ │ │
│ │ │ agent_1 → MT4 Terminal @ port 8081 → Account #22437 │ │ │
│ │ │ agent_2 → MT4 Terminal @ port 8082 → Account #XXXXX │ │ │
│ │ │ agent_3 → MT4 Terminal @ port 8083 → Account #YYYYY │ │ │
│ │ └─────────────────────────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ Endpoints: │ │
│ │ POST /api/agents/{agent_id}/trade │ │
│ │ GET /api/agents/{agent_id}/positions │ │
│ │ GET /api/agents/{agent_id}/account │ │
│ │ GET /api/agents/summary │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────────┐ │
│ │ MT4 TERMINALS LAYER (Windows) │ │
│ │ │ │
│ │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ │
│ │ │ MT4 Terminal #1 │ │ MT4 Terminal #2 │ │ MT4 Terminal #3 │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ Account: 22437 │ │ Account: XXXXX │ │ Account: YYYYY │ │ │
│ │ │ Balance: $200 │ │ Balance: $500 │ │ Balance: $1000 │ │ │
│ │ │ Strategy: AMD │ │ Strategy: ICT │ │ Strategy: Mixed │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ ┌────────────┐ │ │ ┌────────────┐ │ │ ┌────────────┐ │ │ │
│ │ │ │ EA Bridge │ │ │ │ EA Bridge │ │ │ │ EA Bridge │ │ │ │
│ │ │ │ :8081 │ │ │ │ :8082 │ │ │ │ :8083 │ │ │ │
│ │ │ └────────────┘ │ │ └────────────┘ │ │ └────────────┘ │ │ │
│ │ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## Componentes Detallados
### 1. MT4 Terminal + EA Bridge
Cada terminal MT4 corre con un Expert Advisor (EA) que expone una API REST local.
#### EA Bridge Recomendado: MT4-REST-API
```mql4
// Configuración del EA
input int SERVER_PORT = 8081; // Puerto único por terminal
input string AUTH_TOKEN = "secret"; // Token de autenticación
input bool ALLOW_TRADE = true; // Permitir trading
```
#### Endpoints expuestos por el EA:
| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/account` | GET | Info de cuenta (balance, equity, margin) |
| `/tick/{symbol}` | GET | Precio actual bid/ask |
| `/positions` | GET | Posiciones abiertas |
| `/orders` | GET | Órdenes pendientes |
| `/trade` | POST | Abrir/cerrar/modificar orden |
| `/history` | GET | Historial de trades |
### 2. MT4 Gateway Service
Servicio Python que unifica acceso a múltiples terminales.
```python
# apps/mt4-gateway/src/gateway.py
from fastapi import FastAPI, HTTPException
from typing import Dict, Optional
import aiohttp
app = FastAPI(title="MT4 Gateway Service")
# Configuración de agentes
AGENTS_CONFIG = {
"agent_1": {
"name": "Atlas",
"mt4_host": "localhost",
"mt4_port": 8081,
"account": "22437",
"strategy": "amd",
"risk_config": {
"max_risk_per_trade": 0.01,
"max_daily_loss": 0.05,
"max_positions": 1
}
},
"agent_2": {
"name": "Orion",
"mt4_host": "localhost",
"mt4_port": 8082,
"account": "XXXXX",
"strategy": "ict",
"risk_config": {
"max_risk_per_trade": 0.02,
"max_daily_loss": 0.05,
"max_positions": 2
}
},
"agent_3": {
"name": "Nova",
"mt4_host": "localhost",
"mt4_port": 8083,
"account": "YYYYY",
"strategy": "mixed",
"risk_config": {
"max_risk_per_trade": 0.02,
"max_daily_loss": 0.05,
"max_positions": 3
}
}
}
class MT4Client:
"""Cliente para comunicarse con un terminal MT4 vía EA Bridge"""
def __init__(self, host: str, port: int, auth_token: str = "secret"):
self.base_url = f"http://{host}:{port}"
self.auth_token = auth_token
async def get_account(self) -> Dict:
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/account",
headers={"Authorization": self.auth_token}
) as resp:
return await resp.json()
async def get_tick(self, symbol: str) -> Dict:
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/tick/{symbol}",
headers={"Authorization": self.auth_token}
) as resp:
return await resp.json()
async def get_positions(self) -> list:
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/positions",
headers={"Authorization": self.auth_token}
) as resp:
return await resp.json()
async def open_trade(
self,
symbol: str,
action: str, # "buy" or "sell"
lots: float,
sl: Optional[float] = None,
tp: Optional[float] = None,
comment: str = "Trading Platform"
) -> Dict:
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/trade",
headers={"Authorization": self.auth_token},
json={
"symbol": symbol,
"action": action,
"lots": lots,
"sl": sl,
"tp": tp,
"comment": comment
}
) as resp:
return await resp.json()
async def close_position(self, ticket: int) -> Dict:
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/trade",
headers={"Authorization": self.auth_token},
json={
"action": "close",
"ticket": ticket
}
) as resp:
return await resp.json()
# Gateway endpoints
@app.get("/api/agents")
async def list_agents():
"""Lista todos los agentes configurados"""
return {
agent_id: {
"name": config["name"],
"account": config["account"],
"strategy": config["strategy"]
}
for agent_id, config in AGENTS_CONFIG.items()
}
@app.get("/api/agents/{agent_id}/account")
async def get_agent_account(agent_id: str):
"""Obtiene info de cuenta de un agente"""
if agent_id not in AGENTS_CONFIG:
raise HTTPException(404, "Agent not found")
config = AGENTS_CONFIG[agent_id]
client = MT4Client(config["mt4_host"], config["mt4_port"])
account = await client.get_account()
return {
"agent_id": agent_id,
"name": config["name"],
**account
}
@app.get("/api/agents/{agent_id}/positions")
async def get_agent_positions(agent_id: str):
"""Obtiene posiciones abiertas de un agente"""
if agent_id not in AGENTS_CONFIG:
raise HTTPException(404, "Agent not found")
config = AGENTS_CONFIG[agent_id]
client = MT4Client(config["mt4_host"], config["mt4_port"])
return await client.get_positions()
@app.post("/api/agents/{agent_id}/trade")
async def execute_agent_trade(
agent_id: str,
trade_request: dict
):
"""Ejecuta un trade para un agente específico"""
if agent_id not in AGENTS_CONFIG:
raise HTTPException(404, "Agent not found")
config = AGENTS_CONFIG[agent_id]
client = MT4Client(config["mt4_host"], config["mt4_port"])
# Validar contra risk config
risk_config = config["risk_config"]
# TODO: Implementar validación de riesgo
return await client.open_trade(
symbol=trade_request["symbol"],
action=trade_request["action"],
lots=trade_request["lots"],
sl=trade_request.get("sl"),
tp=trade_request.get("tp"),
comment=f"Trading Platform-{config['name']}"
)
@app.get("/api/agents/summary")
async def get_agents_summary():
"""Resumen consolidado de todos los agentes"""
summary = {
"total_balance": 0,
"total_equity": 0,
"total_profit": 0,
"total_positions": 0,
"agents": []
}
for agent_id, config in AGENTS_CONFIG.items():
try:
client = MT4Client(config["mt4_host"], config["mt4_port"])
account = await client.get_account()
positions = await client.get_positions()
agent_summary = {
"agent_id": agent_id,
"name": config["name"],
"balance": account.get("balance", 0),
"equity": account.get("equity", 0),
"profit": account.get("profit", 0),
"open_positions": len(positions),
"status": "online"
}
summary["total_balance"] += account.get("balance", 0)
summary["total_equity"] += account.get("equity", 0)
summary["total_profit"] += account.get("profit", 0)
summary["total_positions"] += len(positions)
except Exception as e:
agent_summary = {
"agent_id": agent_id,
"name": config["name"],
"status": "offline",
"error": str(e)
}
summary["agents"].append(agent_summary)
return summary
```
### 3. Configuración por Agente
```yaml
# apps/mt4-gateway/config/agents.yml
agents:
agent_1:
id: "agent_1"
name: "Atlas"
description: "Conservative AMD strategy"
mt4:
host: "localhost"
port: 8081
account: "22437"
server: "EBCFinancialGroupKY-Demo02"
strategy:
type: "amd"
pairs: ["XAUUSD"]
timeframe: "5m"
risk:
initial_balance: 200
max_risk_per_trade: 0.01 # 1%
max_daily_loss: 0.05 # 5%
max_positions: 1
allowed_pairs: ["XAUUSD"]
agent_2:
id: "agent_2"
name: "Orion"
description: "Moderate ICT strategy"
mt4:
host: "localhost"
port: 8082
account: "XXXXX"
server: "EBCFinancialGroupKY-Demo02"
strategy:
type: "ict"
pairs: ["EURUSD", "GBPUSD"]
timeframe: "15m"
risk:
initial_balance: 500
max_risk_per_trade: 0.015
max_daily_loss: 0.05
max_positions: 2
allowed_pairs: ["EURUSD", "GBPUSD"]
agent_3:
id: "agent_3"
name: "Nova"
description: "Aggressive mixed strategy"
mt4:
host: "localhost"
port: 8083
account: "YYYYY"
server: "EBCFinancialGroupKY-Demo02"
strategy:
type: "mixed"
pairs: ["XAUUSD", "EURUSD", "GBPUSD", "USDJPY"]
timeframe: "5m"
risk:
initial_balance: 1000
max_risk_per_trade: 0.02
max_daily_loss: 0.05
max_positions: 3
allowed_pairs: ["XAUUSD", "EURUSD", "GBPUSD", "USDJPY"]
```
---
## Setup de Múltiples Terminales MT4
### Opción A: Windows Local/VPS
1. **Instalar múltiples instancias de MT4:**
```batch
:: Crear copias del directorio MT4
xcopy "C:\Program Files\EBC MT4" "C:\MT4_Agent1" /E /I
xcopy "C:\Program Files\EBC MT4" "C:\MT4_Agent2" /E /I
xcopy "C:\Program Files\EBC MT4" "C:\MT4_Agent3" /E /I
```
2. **Configurar cada terminal con diferente puerto:**
```
MT4_Agent1/terminal.exe → EA Bridge port 8081
MT4_Agent2/terminal.exe → EA Bridge port 8082
MT4_Agent3/terminal.exe → EA Bridge port 8083
```
3. **Script de inicio:**
```batch
:: start_all_agents.bat
start "" "C:\MT4_Agent1\terminal.exe"
start "" "C:\MT4_Agent2\terminal.exe"
start "" "C:\MT4_Agent3\terminal.exe"
```
### Opción B: Docker (Más complejo, requiere Wine)
```dockerfile
# Dockerfile.mt4
FROM scottyhardy/docker-wine
# Install MT4
COPY mt4_installer.exe /tmp/
RUN wine /tmp/mt4_installer.exe /silent
# Copy EA Bridge
COPY ea_bridge.ex4 /home/wineuser/.wine/drive_c/MT4/MQL4/Experts/
EXPOSE 8081
CMD ["wine", "/home/wineuser/.wine/drive_c/MT4/terminal.exe"]
```
```yaml
# docker-compose.yml
version: '3.8'
services:
mt4_agent1:
build: .
ports:
- "8081:8081"
environment:
- MT4_LOGIN=22437
- MT4_PASSWORD=AfcItz2391!
- MT4_SERVER=EBCFinancialGroupKY-Demo02
- EA_PORT=8081
mt4_agent2:
build: .
ports:
- "8082:8082"
environment:
- MT4_LOGIN=XXXXX
- MT4_PASSWORD=password
- MT4_SERVER=EBCFinancialGroupKY-Demo02
- EA_PORT=8082
mt4_gateway:
build: ./mt4-gateway
ports:
- "8090:8090"
depends_on:
- mt4_agent1
- mt4_agent2
```
---
## Flujo de Ejecución Multi-Agente
```
┌──────────────────────────────────────────────────────────────────────────┐
│ SIGNAL FLOW │
│ │
│ [ML Engine] │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────┐ │
│ │ AgentOrchestrator │ │
│ │ Signal: XAUUSD LONG, Confidence: 78% │ │
│ └────────────────────────────────────────────────┘ │
│ │ │
│ ├───────────────────┬───────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │
│ │ (Atlas) │ │ (Orion) │ │ (Nova) │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Risk Check Risk Check Risk Check │
│ ✓ XAUUSD allowed ✗ Not in pairs ✓ XAUUSD allowed │
│ ✓ Position OK → SKIP ✓ Position OK │
│ │ │ │
│ ▼ ▼ │
│ Calculate Size Calculate Size │
│ $200 × 1% = $2 $1000 × 2% = $20 │
│ → 0.01 lots → 0.05 lots │
│ │ │ │
│ ▼ ▼ │
│ Execute via Execute via │
│ MT4 Terminal #1 MT4 Terminal #3 │
│ Port 8081 Port 8083 │
│ │ │ │
│ ▼ ▼ │
│ Position Opened Position Opened │
│ Ticket: 12345 Ticket: 12348 │
│ │
└──────────────────────────────────────────────────────────────────────────┘
```
---
## Comparativa: MetaAPI vs EA Bridge para Multi-Agente
| Aspecto | MetaAPI.cloud | EA Bridge |
|---------|---------------|-----------|
| **Costo** | $10/mes por cuenta adicional | $0 (solo VPS) |
| **Setup** | Simple (web UI) | Complejo (instalar EA) |
| **Mantenimiento** | Bajo (cloud) | Alto (terminales 24/7) |
| **Latencia** | ~200-500ms | ~50-100ms |
| **Escalabilidad** | Fácil | Requiere más recursos |
| **Independencia** | Depende de tercero | Control total |
| **10 agentes/mes** | $100/mes | ~$20 VPS |
**Recomendación:**
- **1-2 agentes:** MetaAPI más simple
- **3+ agentes:** EA Bridge más económico
- **Producción seria:** EA Bridge + VPS dedicado
---
## Próximos Pasos
1. **Fase 1: Setup inicial**
- [ ] Instalar MT4 EBC en Windows/VPS
- [ ] Descargar EA Bridge (MT4-REST-API)
- [ ] Configurar primer terminal con cuenta demo
2. **Fase 2: Gateway Service**
- [ ] Crear proyecto `apps/mt4-gateway`
- [ ] Implementar MT4Client
- [ ] Implementar endpoints REST
3. **Fase 3: Integración**
- [ ] Conectar Gateway con ML Engine
- [ ] Implementar risk management por agente
- [ ] Crear dashboard multi-agente
4. **Fase 4: Escalar**
- [ ] Agregar segunda cuenta demo
- [ ] Configurar segundo terminal
- [ ] Test de operaciones paralelas
---
## Referencias
- [MT4-REST-API EA](https://github.com/nickyshlee/MT4-REST-API)
- [ZeroMQ-MT4](https://github.com/darwinex/dwx-zeromq-connector)
- [EBC MT4 Download](https://www.ebc.com/en/trading-platform/)