trading-platform/docs/02-definicion-modulos/OQI-010-mt4-gateway/README.md
Adrian Flores Cortes df43dd90cb [F0-F2] feat: Coherence analysis baseline + entity types + frontend stores
FASE 0 - Preparación y Purga:
- Archived 21 completed tasks to _archive/2026-01/
- Marked 4 docs as DEPRECATED
- Created 3 baseline coherence reports

FASE 1 - DDL-Backend Coherence:
- audit.types.ts: +4 types (SystemEvent, TradingAudit, ApiRequestLog, DataAccessLog)
- investment.types.ts: +4 types (RiskQuestionnaire, WithdrawalRequest, DailyPerformance, DistributionHistory)
- entity.types.ts: +5 types (Symbol, TradingBot, TradingSignal, TradingMetrics, PaperBalance)

FASE 2 - Backend-Frontend Coherence:
- investmentStore.ts: New Zustand store with 20+ actions
- mlStore.ts: New Zustand store with signal caching
- alerts.service.ts: New service with 15 functions

FASE 3 - Documentation:
- OQI-009: Updated to 100% coverage, added ET-MKT-004-productos.md
- OQI-010: Created full structure (STATUS.md, ROADMAP-MT4.md, ET-MT4-001-gateway.md)

Coherence Baseline Established:
- DDL-Backend: 31% (target 95%)
- Backend-Frontend: 72% (target 85%)
- Global: 39.6% (target 90%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 22:08:04 -06:00

248 lines
13 KiB
Markdown

---
id: "README"
title: "MT4 Gateway Integration"
type: "Documentation"
project: "trading-platform"
version: "0.1.0"
created_date: "2026-01-28"
updated_date: "2026-01-28"
status: "NOT_FUNCTIONAL"
progress: 15
---
# OQI-010: MT4 Gateway Integration
> **ESTADO: NO FUNCIONAL**
>
> Este modulo esta en fase inicial de desarrollo (15% completado).
> NO esta listo para uso en produccion ni desarrollo activo.
> Requiere trabajo significativo antes de ser operativo.
---
## Resumen Ejecutivo
La epica OQI-010 implementa la integracion con MetaTrader 4 (MT4) para permitir trading automatizado en mercados forex y CFDs. El objetivo es exponer las capacidades de MT4 como herramientas MCP (Model Context Protocol) para que agentes de IA puedan ejecutar operaciones de trading.
---
## Metadata
| Campo | Valor |
|-------|-------|
| **ID** | OQI-010 |
| **Nombre** | MT4 Gateway Integration |
| **Modulo** | mt4-gateway |
| **Fase** | Pre-MVP (Incubacion) |
| **Prioridad** | P2 |
| **Estado** | NO FUNCIONAL |
| **Progreso** | 15% |
| **Story Points** | 55 SP (estimado) |
---
## Estado Actual
### Componentes Existentes
| Componente | Ruta | Estado |
|------------|------|--------|
| MCP Server Skeleton | `mcp-mt4-connector/` | Parcial |
| Express Server | `mcp-mt4-connector/src/index.ts` | Funcional (sin MT4) |
| Tool Definitions | `mcp-mt4-connector/src/tools/` | Definidos |
| MT4 Client | `mcp-mt4-connector/src/services/mt4-client.ts` | Mock |
### Funcionalidad Actual
- **Servidor Express:** El servidor MCP esta implementado y puede iniciar
- **Endpoints de Health:** `/health` y `/tools` funcionan
- **Tool Schemas:** Definidos pero NO conectados a MT4 real
- **MT4 Gateway:** NO IMPLEMENTADO - requiere EA Bridge
---
## Razones del Bloqueo
### 1. Falta de MT4 Gateway (Critico)
El `mcp-mt4-connector` requiere un servicio intermedio (`mt4-gateway`) que actue como puente entre el servidor MCP y el terminal MT4. Este componente NO existe.
```
[MCP Server] --> [MT4 Gateway] --> [MT4 Terminal + EA]
^
|
NO IMPLEMENTADO
```
**Requisitos del MT4 Gateway:**
- Servidor HTTP/WebSocket que reciba comandos del MCP
- Expert Advisor (EA) en MQL4 para MT4
- Comunicacion bidireccional con el terminal MT4
- Manejo de sesiones y autenticacion
### 2. Expert Advisor (EA) No Desarrollado
Se necesita un Expert Advisor personalizado en MQL4 que:
- Reciba comandos via DLL o socket
- Ejecute operaciones en MT4
- Retorne resultados y estado de cuenta
- Maneje errores y reconexion
### 3. Dependencias Externas
| Dependencia | Estado | Bloqueante |
|-------------|--------|------------|
| MT4 Terminal | Requiere instalacion local | Si |
| Cuenta Demo MT4 | Requiere broker | Si |
| EA Bridge | No desarrollado | Si |
| Windows/Wine | MT4 solo corre en Windows | Si |
### 4. Infraestructura de Red
- MT4 requiere conexion persistente al broker
- El EA necesita comunicacion local con el gateway
- Configuracion de firewalls y puertos
- SSL/TLS para seguridad
---
## Arquitectura Propuesta
```
┌────────────────────────────────────────────────────────────────────────────┐
│ OQI-010 MT4 GATEWAY ARCHITECTURE │
├────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ LLM TRADING AGENT │ │
│ │ (Via MCP Protocol - OQI-010-llm-trading-integration) │ │
│ └────────────────────────────────┬────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ MCP MT4 CONNECTOR (:3605) │ │
│ │ [PARCIALMENTE IMPLEMENTADO] │ │
│ │ │ │
│ │ Tools: │ │
│ │ - mt4_get_account (definido, no funcional) │ │
│ │ - mt4_get_positions (definido, no funcional) │ │
│ │ - mt4_get_quote (definido, no funcional) │ │
│ │ - mt4_execute_trade (definido, no funcional) │ │
│ │ - mt4_close_position (definido, no funcional) │ │
│ │ - mt4_modify_position (definido, no funcional) │ │
│ └────────────────────────────────┬────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ MT4 GATEWAY (:8081) │ │
│ │ [NO IMPLEMENTADO] │ │
│ │ │ │
│ │ - HTTP/REST API │ │
│ │ - WebSocket para streaming │ │
│ │ - Autenticacion por token │ │
│ │ - Queue de comandos │ │
│ │ - Persistencia de estado │ │
│ └────────────────────────────────┬────────────────────────────────────┘ │
│ │ │
│ [Comunicacion Local] │
│ (DLL/Socket/Named Pipe) │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ MT4 TERMINAL (Windows) │ │
│ │ [REQUIERE INSTALACION] │ │
│ │ │ │
│ │ ┌───────────────────────────────────────────────────────────────┐ │ │
│ │ │ EXPERT ADVISOR (EA) │ │ │
│ │ │ [NO DESARROLLADO] │ │ │
│ │ │ │ │ │
│ │ │ - MQL4 Script │ │ │
│ │ │ - Socket Client para Gateway │ │ │
│ │ │ - Manejo de OrderSend/OrderModify/OrderClose │ │ │
│ │ │ - Reporting de AccountInfo │ │ │
│ │ └───────────────────────────────────────────────────────────────┘ │ │
│ └────────────────────────────────┬────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ BROKER MT4 SERVER │ │
│ │ (Externo - e.g., IC Markets, Pepperstone) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└────────────────────────────────────────────────────────────────────────────┘
```
---
## Herramientas MCP Definidas
| Tool | Descripcion | Nivel de Riesgo | Estado |
|------|-------------|-----------------|--------|
| `mt4_get_account` | Obtener balance, equity, margin | Bajo | Definido |
| `mt4_get_positions` | Listar posiciones abiertas | Bajo | Definido |
| `mt4_get_quote` | Obtener precio bid/ask actual | Bajo | Definido |
| `mt4_execute_trade` | Ejecutar orden BUY/SELL | ALTO | Definido |
| `mt4_close_position` | Cerrar una posicion | ALTO | Definido |
| `mt4_modify_position` | Modificar SL/TP | Medio | Definido |
---
## Dependencias
### Esta epica depende de:
| Epica/Modulo | Estado | Bloqueante | Razon |
|--------------|--------|------------|-------|
| OQI-001 Auth | Completado | No | Autenticacion opcional |
| MT4 Gateway Service | No existe | SI | Core dependency |
| Expert Advisor | No existe | SI | Ejecucion en MT4 |
### Esta epica habilita:
| Epica/Modulo | Razon |
|--------------|-------|
| OQI-010-llm-trading-integration | Permite al LLM operar en MT4 |
| Trading automatizado | Forex/CFD via agentes |
---
## Riesgos
| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Complejidad del EA | Alta | Alto | Usar librerias existentes |
| Latencia de ejecucion | Media | Alto | Optimizar comunicacion |
| Errores de trading | Alta | Critico | Paper trading primero, limits |
| Desconexiones MT4 | Media | Alto | Reconnect logic, heartbeat |
| Cambios en API broker | Baja | Medio | Abstraccion de broker |
---
## Entregables Pendientes
| Entregable | Prioridad | Esfuerzo | Estado |
|------------|-----------|----------|--------|
| MT4 Gateway Service | P0 | 13 SP | No iniciado |
| Expert Advisor MQL4 | P0 | 13 SP | No iniciado |
| Integracion MCP-Gateway | P0 | 8 SP | Parcial |
| Tests de integracion | P1 | 5 SP | No iniciado |
| Documentacion de deploy | P1 | 3 SP | No iniciado |
| Paper trading mode | P0 | 8 SP | No iniciado |
| Monitoring/Alertas | P2 | 5 SP | No iniciado |
---
## Referencias
- [STATUS.md](./STATUS.md) - Estado detallado del modulo
- [ROADMAP-MT4.md](./ROADMAP-MT4.md) - Plan de implementacion
- [Especificaciones](./especificaciones/) - Requisitos tecnicos
- [MCP MT4 Connector README](../../../mcp-mt4-connector/README.md)
- [MCP Protocol](https://modelcontextprotocol.io)
---
*Documento creado: 2026-01-28*
*Ultima actualizacion: 2026-01-28*
*Estado: NO FUNCIONAL*