| id |
title |
type |
project |
version |
updated_date |
| INT-MT4-001-gateway-service |
MT4 Gateway Service - Integración Multi-Agente |
Documentation |
trading-platform |
1.0.0 |
2026-01-04 |
INT-MT4-001: MT4 Gateway Service - Integración Multi-Agente
Metadata
| Campo |
Valor |
| ID |
INT-MT4-001 |
| Módulo |
MT4 Gateway Service |
| Tipo |
Especificación de Integración |
| Versión |
1.0.0 |
| Estado |
En Desarrollo |
| Fecha creación |
2025-12-12 |
| Última actualización |
2025-12-12 |
| Autor |
Architecture-Analyst |
| Épica relacionada |
OQI-009 |
1. Resumen Ejecutivo
El MT4 Gateway Service es un componente crítico que permite:
- Gestión de múltiples cuentas MT4 de forma independiente
- Cada cuenta con su propio agente de trading (Atlas, Orion, Nova)
- API unificada para interactuar con todas las cuentas
- Risk management por agente
- Integración con el ML Engine para ejecución de señales
2. Arquitectura de la Integración
┌─────────────────────────────────────────────────────────────────────────────┐
│ ORBIQUANT TRADING PLATFORM │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Admin │ │ Backend │ │ ML Engine │ │ LLM Agent │ │
│ │ Dashboard │ │ Express │ │ FastAPI │ │ (Future) │ │
│ │ :5173 │ │ :3001 │ │ :8000 │ │ :8002 │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │ │
│ └─────────────────┴─────────────────┴─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ MT4 GATEWAY SERVICE (:8090) │ │
│ │ │ │
│ │ /api/agents - Lista agentes │ │
│ │ /api/agents/summary - Resumen consolidado │ │
│ │ /api/agents/{id}/trade - Ejecutar trade │ │
│ │ /api/agents/{id}/account - Info de cuenta │ │
│ │ /api/emergency/stop-all - Parada de emergencia │ │
│ │ │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ Agent Registry │ │ │
│ │ │ │ │ │
│ │ │ agent_1 (Atlas) → MT4 Bridge @ :8081 → Account 22437 │ │ │
│ │ │ agent_2 (Orion) → MT4 Bridge @ :8082 → Account XXXXX │ │ │
│ │ │ agent_3 (Nova) → MT4 Bridge @ :8083 → Account YYYYY │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────┼─────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ MT4 │ │ MT4 │ │ MT4 │ │
│ │ Terminal │ │ Terminal │ │ Terminal │ │
│ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │
│ │ │ │ │ │ │ │
│ │ EA Bridge │ │ EA Bridge │ │ EA Bridge │ │
│ │ :8081 │ │ :8082 │ │ :8083 │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └─────────────────────────┴─────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ EBC Financial Group (Broker) │ │
│ │ Server: EBCFinancialGroupKY-Demo02 │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
3. Componentes del Sistema
3.1 MT4 Gateway Service
| Atributo |
Valor |
| Ubicación |
apps/mt4-gateway/ |
| Framework |
Python/FastAPI |
| Puerto |
8090 |
| Inventario |
docs/90-transversal/inventarios/MT4_GATEWAY_INVENTORY.yml |
Archivos Principales
| Archivo |
Propósito |
Líneas |
src/main.py |
Aplicación FastAPI principal |
~400 |
src/providers/mt4_bridge_client.py |
Cliente para EA Bridge |
~350 |
config/agents.yml |
Configuración de agentes |
~150 |
requirements.txt |
Dependencias Python |
~25 |
3.2 Agentes de Trading
| ID |
Nombre |
Puerto |
Strategy |
Pares |
Risk |
Estado |
| agent_1 |
Atlas |
8081 |
AMD |
XAUUSD |
1% |
Enabled |
| agent_2 |
Orion |
8082 |
ICT |
EUR/GBP |
1.5% |
Disabled |
| agent_3 |
Nova |
8083 |
Mixed |
ALL |
2% |
Disabled |
3.3 EA Bridge (por terminal MT4)
Cada terminal MT4 requiere un Expert Advisor (EA) que expone una API REST.
| Endpoint |
Método |
Descripción |
/account |
GET |
Información de cuenta |
/tick/{symbol} |
GET |
Precio actual |
/positions |
GET |
Posiciones abiertas |
/trade |
POST |
Ejecutar operación |
/history |
GET |
Historial de trades |
4. Flujo de Datos
4.1 Flujo de Señal → Ejecución
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ ML Engine │────▶│ Gateway │────▶│Risk Manager │────▶│ MT4 Client │
│ │ │ Service │ │ │ │ │
│ Signal: │ │ │ │ Validates: │ │ Executes: │
│ • XAUUSD │ │ Routes to: │ │ • Max risk │ │ • OpenOrder │
│ • LONG │ │ • agent_1 │ │ • Position │ │ • SL/TP │
│ • Conf: 78% │ │ • agent_3 │ │ • Daily DD │ │ • Logging │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ MT4 │
│ Terminal │
│ + EA │
└─────────────┘
4.2 Flujo de Datos de Cuenta
Frontend (Dashboard)
│
▼
GET /api/agents/summary
│
▼
MT4 Gateway Service
│
├───▶ Agent 1: GET /account → MT4 Terminal 1
├───▶ Agent 2: GET /account → MT4 Terminal 2
└───▶ Agent 3: GET /account → MT4 Terminal 3
│
▼
Consolidate Response
│
▼
{
total_balance: 1700,
total_equity: 1720,
total_profit: 45.30,
agents: [...]
}
5. Matriz de Trazabilidad
5.1 Dependencias de Componentes
| Componente Origen |
Componente Destino |
Tipo |
Protocolo |
Estado |
| Admin Dashboard |
MT4 Gateway |
Consumer |
HTTP REST |
Pendiente |
| Backend Express |
MT4 Gateway |
Consumer |
HTTP REST |
Pendiente |
| ML Engine |
MT4 Gateway |
Provider |
HTTP REST |
Pendiente |
| MT4 Gateway |
MT4 Terminal 1 |
Consumer |
HTTP REST |
Ready |
| MT4 Gateway |
MT4 Terminal 2 |
Consumer |
HTTP REST |
Ready |
| MT4 Gateway |
MT4 Terminal 3 |
Consumer |
HTTP REST |
Ready |
| MT4 Gateway |
PostgreSQL |
Consumer |
TCP |
Pendiente |
5.2 Relación con Épicas
| Épica |
Relación |
Descripción |
| OQI-003 |
Consumer |
Trading Charts consume datos de posiciones |
| OQI-004 |
Integration |
Investment Accounts integra con agentes |
| OQI-006 |
Provider |
ML Signals provee señales a ejecutar |
| OQI-007 |
Integration |
LLM Agent puede ejecutar via Gateway |
| OQI-008 |
Integration |
Portfolio Manager consolida agentes |
| OQI-009 |
Owner |
Épica principal del MT4 Gateway |
5.3 Archivos Relacionados
| Archivo |
Tipo |
Relación |
apps/mt4-gateway/src/main.py |
Source |
Implementación principal |
apps/mt4-gateway/config/agents.yml |
Config |
Configuración de agentes |
apps/data-service/.env |
Config |
Credenciales MT4 |
docs/01-arquitectura/ARQUITECTURA-MULTI-AGENTE-MT4.md |
Doc |
Arquitectura detallada |
docs/90-transversal/setup/SETUP-MT4-TRADING.md |
Doc |
Guía de setup |
docs/90-transversal/inventarios/MT4_GATEWAY_INVENTORY.yml |
Inventory |
Inventario del servicio |
6. Configuración de Risk Management
6.1 Por Agente
agent_1 (Atlas):
initial_balance: $200
max_risk_per_trade: 1% # $2
max_daily_loss: 5% # $10
max_positions: 1
allowed_pairs: [XAUUSD]
agent_2 (Orion):
initial_balance: $500
max_risk_per_trade: 1.5% # $7.50
max_daily_loss: 5% # $25
max_positions: 2
allowed_pairs: [EURUSD, GBPUSD]
agent_3 (Nova):
initial_balance: $1000
max_risk_per_trade: 2% # $20
max_daily_loss: 5% # $50
max_positions: 3
allowed_pairs: [XAUUSD, EURUSD, GBPUSD, USDJPY]
6.2 Global
emergency_stop_all: false
max_total_exposure: 10%
correlation_limit: 0.5
7. API Reference
7.1 Endpoints
| Endpoint |
Método |
Descripción |
Auth |
/health |
GET |
Health check |
No |
/api/status |
GET |
Estado detallado |
No |
/api/agents |
GET |
Lista agentes |
Yes |
/api/agents/summary |
GET |
Resumen consolidado |
Yes |
/api/agents/{id} |
GET |
Info de agente |
Yes |
/api/agents/{id}/account |
GET |
Info de cuenta MT4 |
Yes |
/api/agents/{id}/positions |
GET |
Posiciones abiertas |
Yes |
/api/agents/{id}/tick/{symbol} |
GET |
Precio actual |
Yes |
/api/agents/{id}/trade |
POST |
Ejecutar trade |
Yes |
/api/agents/{id}/close |
POST |
Cerrar posición |
Yes |
/api/agents/{id}/modify |
POST |
Modificar SL/TP |
Yes |
/api/agents/{id}/close-all |
POST |
Cerrar todas |
Yes |
/api/emergency/stop-all |
POST |
EMERGENCY stop |
Admin |
7.2 Modelos de Request/Response
TradeRequest
{
"symbol": "XAUUSD",
"action": "buy",
"lots": 0.01,
"sl": 2640.00,
"tp": 2660.00,
"comment": "Trading Platform-Atlas"
}
GlobalSummary Response
{
"total_balance": 1700.00,
"total_equity": 1720.50,
"total_profit": 45.30,
"total_positions": 2,
"agents_online": 2,
"agents_offline": 1,
"agents": [
{
"agent_id": "agent_1",
"name": "Atlas",
"status": "online",
"balance": 200.00,
"equity": 205.50,
"profit": 5.50,
"open_positions": 1,
"strategy": "amd"
}
]
}
8. Impacto en el Sistema
8.1 Componentes Afectados
| Componente |
Tipo Impacto |
Acción Requerida |
| Backend Express |
Nuevo módulo |
Crear /api/trading/* routes |
| Admin Dashboard |
Nueva página |
Crear página de agentes |
| ML Engine |
Nuevo consumer |
WebSocket para señales |
| PostgreSQL |
Nuevas tablas |
Tablas de trades y logs |
| Data Service |
Referencia |
Sin cambios |
8.2 Cambios en Base de Datos
-- Nuevas tablas requeridas (futuro)
CREATE TABLE trading.agent_trades (
id SERIAL PRIMARY KEY,
agent_id VARCHAR(50),
ticket INTEGER,
symbol VARCHAR(20),
action VARCHAR(10),
lots DECIMAL(10,2),
open_price DECIMAL(20,5),
close_price DECIMAL(20,5),
stop_loss DECIMAL(20,5),
take_profit DECIMAL(20,5),
profit DECIMAL(20,5),
open_time TIMESTAMP,
close_time TIMESTAMP,
signal_id INTEGER,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE trading.agent_logs (
id SERIAL PRIMARY KEY,
agent_id VARCHAR(50),
event_type VARCHAR(50),
message TEXT,
metadata JSONB,
created_at TIMESTAMP DEFAULT NOW()
);
9. Requisitos de Infraestructura
9.1 Para Ejecución Local
| Componente |
Requisito |
| Python |
3.10+ |
| MT4 Terminal |
Windows (o Wine en Linux) |
| EA Bridge |
Instalado en MT4 |
| PostgreSQL |
15+ |
| Redis |
7+ (opcional, para cache) |
9.2 Para Producción
| Componente |
Requisito |
| VPS Windows |
Para terminales MT4 24/7 |
| VPS Linux |
Para servicios Python |
| Supervisord |
Process manager |
| Nginx |
Reverse proxy |
10. Testing
10.1 Tests Requeridos
10.2 Test de Integración
# Verificar gateway
curl http://localhost:8090/health
# Verificar agentes
curl http://localhost:8090/api/agents/summary
# Test trade (demo only)
curl -X POST http://localhost:8090/api/agents/agent_1/trade \
-H "Content-Type: application/json" \
-d '{"symbol":"XAUUSD","action":"buy","lots":0.01}'
11. Próximos Pasos
| # |
Tarea |
Prioridad |
Dependencia |
| 1 |
Instalar MT4 y EA Bridge |
Alta |
VPS Windows |
| 2 |
Test conexión Gateway → MT4 |
Alta |
#1 |
| 3 |
Integrar con ML Engine |
Alta |
ML Engine WebSocket |
| 4 |
Implementar Risk Manager |
Alta |
- |
| 5 |
Crear Admin Dashboard |
Media |
Backend routes |
| 6 |
Agregar autenticación JWT |
Media |
Backend auth |
| 7 |
Logging a PostgreSQL |
Baja |
DB migrations |
12. Referencias
13. Historial de Cambios
| Versión |
Fecha |
Autor |
Cambios |
| 1.0.0 |
2025-12-12 |
Architecture-Analyst |
Creación inicial |
Estado de Validación:
| Aspecto |
Estado |
Notas |
| Código Gateway implementado |
✅ |
Estructura base completa |
| Configuración de agentes |
✅ |
3 agentes definidos |
| Documentación |
✅ |
Este documento |
| Tests |
⏳ |
Pendiente |
| Integración ML Engine |
⏳ |
Pendiente |
| Integración Admin |
⏳ |
Pendiente |