# EA Bridge Architecture

## Overview

The EA Bridge is a distributed architecture that enables AI-driven trading decisions to be executed on MetaTrader 4 (MT4) terminals. It provides a standardized interface between the Trading Platform's AI components and broker execution.

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────┐
│                     AI Layer (Decision Making)                   │
│  ┌─────────────┐  ┌──────────────┐  ┌────────────────────────┐  │
│  │  LLM Agent  │  │ Trading      │  │      ML Engine         │  │
│  │   (:8003)   │  │ Agents(:8004)│  │       (:8001)          │  │
│  └──────┬──────┘  └──────┬───────┘  └────────────────────────┘  │
│         │                │                                       │
└─────────┼────────────────┼───────────────────────────────────────┘
          │  MCP Protocol  │
          ▼                ▼
┌─────────────────────────────────────────────────────────────────┐
│                  MCP Layer (Protocol Bridge)                     │
│  ┌─────────────────────────┐  ┌─────────────────────────────┐   │
│  │  MCP MT4 Connector      │  │  MCP Binance Connector      │   │
│  │       (:3605)           │  │        (:3606)              │   │
│  │  - 6 Trading Tools      │  │  - 7 Trading Tools          │   │
│  │  - Zod Validation       │  │  - Rate Limiting            │   │
│  └───────────┬─────────────┘  └─────────────────────────────┘   │
│              │                                                   │
└──────────────┼───────────────────────────────────────────────────┘
               │  HTTP REST
               ▼
┌─────────────────────────────────────────────────────────────────┐
│                Gateway Layer (Risk & Routing)                    │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │              MT4 Gateway Service (:8005)                    ││
│  │  - Multi-agent orchestration                                ││
│  │  - Risk Management validation                               ││
│  │  - Agent Registry (Atlas, Orion, Nova)                      ││
│  └───────────┬─────────────┬────────────────┬──────────────────┘│
└──────────────┼─────────────┼────────────────┼────────────────────┘
               │             │                │  HTTP REST
               ▼             ▼                ▼
┌─────────────────────────────────────────────────────────────────┐
│                Execution Layer (MT4 Terminals)                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐              │
│  │  Terminal 1 │  │  Terminal 2 │  │  Terminal 3 │              │
│  │ Atlas :8081 │  │ Orion :8082 │  │ Nova  :8083 │              │
│  │ Conservative│  │  Moderate   │  │  Aggressive │              │
│  └─────────────┘  └─────────────┘  └─────────────┘              │
│         │                │                │                      │
└─────────┼────────────────┼────────────────┼──────────────────────┘
          │                │                │
          ▼                ▼                ▼
    ┌─────────────────────────────────────────┐
    │           Broker Server (EBC)           │
    │      Real order execution & fills       │
    └─────────────────────────────────────────┘
```

## Components

### 1. MCP MT4 Connector

**Location:** `apps/mcp-mt4-connector/`
**Technology:** TypeScript/Node.js (Express.js)
**Port:** 3605

Exposes 6 MCP-compatible tools:

| Tool | Risk Level | Description |
|------|------------|-------------|
| `mt4_get_account` | LOW | Get balance, equity, margin, leverage |
| `mt4_get_positions` | LOW | List open positions with P/L |
| `mt4_get_quote` | LOW | Get bid/ask/spread for symbol |
| `mt4_execute_trade` | HIGH | Execute BUY/SELL with SL/TP |
| `mt4_close_position` | HIGH | Close position (full or partial) |
| `mt4_modify_position` | MEDIUM | Modify SL/TP levels |

**Key Files:**
- `src/index.ts` - Express server with MCP protocol endpoints
- `src/services/mt4-client.ts` - HTTP client wrapper for MT4 Gateway
- `src/tools/` - Individual tool implementations

### 2. MT4 Gateway

**Location:** `apps/mt4-gateway/`
**Technology:** Python/FastAPI
**Port:** 8005

Provides:
- Multi-agent orchestration
- Risk validation before execution
- Agent configuration management
- Connection pooling to terminals

**Key Files:**
- `src/main.py` - FastAPI application
- `src/api/routes.py` - REST API endpoints
- `src/providers/mt4_bridge_client.py` - Async HTTP client
- `config/agents.yml` - Agent definitions

### 3. EA Bridge (Expert Advisor)

**Location:** External (MT4 Terminal)
**Technology:** MQL4
**Ports:** 8081, 8082, 8083

The Expert Advisor runs within MetaTrader 4 and exposes a REST API:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/status` | GET | Connection health check |
| `/account` | GET | Account info (balance, equity) |
| `/tick/{symbol}` | GET | Current bid/ask/spread |
| `/positions` | GET | Open positions list |
| `/trade` | POST | Execute trade order |
| `/history` | GET | Trade history |
| `/symbols` | GET | Available symbols |

## Trading Agents

Three pre-configured agents with different risk profiles:

| Agent | Strategy | Risk Profile | Port |
|-------|----------|--------------|------|
| Atlas | AMD Phase Detection | 1% per trade, max 1 position | 8081 |
| Orion | ICT Concepts | 1.5% per trade, max 2 positions | 8082 |
| Nova | Mixed (AMD + ICT) | 2% per trade, max 3 positions | 8083 |

## Data Flow

### Trade Execution Flow

```
1. User Request
   "Buy 0.1 lots XAUUSD with SL at 2640"
          │
          ▼
2. LLM Agent (Intent Recognition)
   Identifies: symbol=XAUUSD, action=buy, lots=0.1, stopLoss=2640
          │
          ▼
3. MCPOrchestrator (Venue Routing)
   Determines: XAUUSD → MT4 (forex/metals)
          │
          ▼
4. MCP MT4 Connector (Protocol)
   Validates input with Zod schemas
   Calls mt4_execute_trade tool
          │
          ▼
5. MT4 Gateway (Risk Check)
   Validates: lot size, margin, max positions
   Routes to correct agent terminal
          │
          ▼
6. EA Bridge (Execution)
   POST /trade → MT4 Terminal
          │
          ▼
7. Broker Server
   Order executed, ticket assigned
          │
          ▼
8. Response Flow (Reverse Path)
   Ticket #12345, entry 2650.50, SL 2640.00
```

### Portfolio Query Flow

```
1. MCPOrchestrator.get_combined_portfolio()
          │
          ├─────────────────────────────────┐
          ▼                                 ▼
2a. MCP MT4 Connector           2b. MCP Binance Connector
    GET /account                    GET /account
          │                                 │
          ▼                                 ▼
3a. MT4 Gateway                 3b. Binance API
    GET /account                    GET /account
          │                                 │
          ▼                                 ▼
4a. EA Bridge                   4b. Binance Exchange
    Returns account info            Returns account info
          │                                 │
          └───────────┬─────────────────────┘
                      ▼
5. MCPOrchestrator (Aggregation)
   Combined portfolio:
   - Total Balance: $X (MT4) + $Y (Binance)
   - Total Equity: $X' + $Y'
   - All Positions: [MT4 positions] + [Binance positions]
```

## Configuration

### Environment Variables

**MCP MT4 Connector:**
```env
PORT=3605
MT4_GATEWAY_HOST=localhost
MT4_GATEWAY_PORT=8005
MT4_GATEWAY_AUTH_TOKEN=your-secure-token
REQUEST_TIMEOUT=10000
LOG_LEVEL=info
```

**MT4 Gateway:**
```env
MT4_BRIDGE_HOST=localhost
MT4_BRIDGE_PORT=8081
MT4_BRIDGE_AUTH_TOKEN=secret_agent_1
API_PORT=8005
```

### Agent Configuration (agents.yml)

```yaml
agents:
  - id: agent_1
    name: Atlas
    description: Conservative AMD strategy
    port: 8081
    enabled: true
    max_positions: 1
    risk_per_trade: 0.01

  - id: agent_2
    name: Orion
    description: Moderate ICT strategy
    port: 8082
    enabled: false
    max_positions: 2
    risk_per_trade: 0.015

  - id: agent_3
    name: Nova
    description: Aggressive mixed strategy
    port: 8083
    enabled: false
    max_positions: 3
    risk_per_trade: 0.02
```

## Risk Management

### Per-Trade Limits
- Max risk: 1-2% of equity
- Max position size: 10% of equity
- Lot size range: 0.01 - 10.0

### Per-Account Limits
- Max daily drawdown: 5%
- Max total drawdown: 20%
- Max open positions: Agent-dependent (1-3)

### Validation Flow
```
Request → Lot Size Check → Margin Check → Position Limit Check → Execute
```

## Security

1. **Authentication:** Bearer token in HTTP headers
2. **Validation:** Zod schemas (TypeScript), Pydantic models (Python)
3. **Error Handling:** Graceful degradation on failures
4. **Health Checks:** Connection verification before operations

## Integration Points

| Service | Port | Purpose |
|---------|------|---------|
| LLM Agent | 8003 | AI decision making |
| Trading Agents | 8004 | Strategy execution |
| ML Engine | 8001 | Signal generation |
| Backend API | 3000 | User interface |
| PostgreSQL | 5432 | Data persistence |

## Deployment

```
┌────────────────────────────────────────────────────────────┐
│ Linux/Docker Environment                                    │
│  - MT4 Gateway (:8005)                                     │
│  - MCP Connectors (:3605, :3606)                           │
│  - AI Services (:8001, :8003, :8004)                       │
└────────────────────────────────────────────────────────────┘
                           │
                    HTTP/REST (Network)
                           │
                           ▼
┌────────────────────────────────────────────────────────────┐
│ Windows Environment                                         │
│  - MT4 Terminal + EA Bridge (:8081)                        │
│  - MT4 Terminal + EA Bridge (:8082)                        │
│  - MT4 Terminal + EA Bridge (:8083)                        │
└────────────────────────────────────────────────────────────┘
```

## Troubleshooting

### Common Issues

1. **Connection Refused (port 8081-8083)**
   - Verify MT4 terminal is running
   - Check EA is attached to chart
   - Verify firewall rules

2. **Authentication Failed**
   - Check AUTH_TOKEN matches in .env files
   - Verify token format (Bearer prefix)

3. **Trade Rejected**
   - Check margin availability
   - Verify symbol is available
   - Check market is open

4. **Timeout Errors**
   - Increase REQUEST_TIMEOUT
   - Check network latency
   - Verify EA is responding

### Health Check Commands

```bash
# Check MCP Connector
curl http://localhost:3605/health

# Check MT4 Gateway
curl http://localhost:8005/health

# Check EA Bridge directly
curl http://localhost:8081/status
```

## Related Documentation

- [MCPOrchestrator Integration](./MCP-ORCHESTRATOR.md)
- [Trading Agents Configuration](./TRADING-AGENTS.md)
- [Risk Management Policies](./RISK-MANAGEMENT.md)
