# MCP MT4 Connector

**Version:** 0.1.0
**Date:** 2026-01-04
**System:** Trading Platform + NEXUS v3.4 + SIMCO

---

## Description

MCP Server that exposes MetaTrader 4 (MT4) trading capabilities as tools for AI agents. This service enables AI agents to:
- Query account information
- Monitor open positions
- Execute trades (BUY/SELL)
- Manage positions (modify SL/TP, close)
- Get real-time price quotes

---

## Installation

```bash
# Navigate to the project
cd /home/isem/workspace-v1/projects/trading-platform/apps/mcp-mt4-connector

# Install dependencies
npm install

# Configure environment
cp .env.example .env
# Edit .env with your MT4 Gateway credentials
```

---

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | MCP Server port | 3605 |
| `MT4_GATEWAY_HOST` | MT4 Gateway hostname | localhost |
| `MT4_GATEWAY_PORT` | MT4 Gateway port | 8081 |
| `MT4_GATEWAY_AUTH_TOKEN` | Authentication token | secret |
| `REQUEST_TIMEOUT` | Request timeout (ms) | 10000 |
| `LOG_LEVEL` | Logging level | info |

### Example .env
```env
PORT=3605
MT4_GATEWAY_HOST=localhost
MT4_GATEWAY_PORT=8081
MT4_GATEWAY_AUTH_TOKEN=your-secure-token
REQUEST_TIMEOUT=10000
LOG_LEVEL=info
```

---

## Usage

### Start Server

```bash
# Development (with hot reload)
npm run dev

# Production
npm run build
npm start
```

### Health Check

```bash
curl http://localhost:3605/health
```

### List Available Tools

```bash
curl http://localhost:3605/tools
```

### Execute a Tool

```bash
# Get account info
curl -X POST http://localhost:3605/tools/mt4_get_account \
  -H "Content-Type: application/json" \
  -d '{"parameters": {}}'

# Get price quote
curl -X POST http://localhost:3605/tools/mt4_get_quote \
  -H "Content-Type: application/json" \
  -d '{"parameters": {"symbol": "XAUUSD"}}'

# Execute trade
curl -X POST http://localhost:3605/tools/mt4_execute_trade \
  -H "Content-Type: application/json" \
  -d '{"parameters": {"symbol": "XAUUSD", "action": "buy", "lots": 0.1}}'
```

---

## MCP Tools Available

| Tool | Description | Risk |
|------|-------------|------|
| `mt4_get_account` | Get account balance, equity, margin | Low |
| `mt4_get_positions` | List open positions | Low |
| `mt4_get_quote` | Get current bid/ask price | Low |
| `mt4_execute_trade` | Execute BUY/SELL order | HIGH |
| `mt4_close_position` | Close a position | HIGH |
| `mt4_modify_position` | Modify SL/TP | Medium |

---

## Project Structure

```
mcp-mt4-connector/
├── README.md                 # This file
├── package.json              # Dependencies
├── tsconfig.json             # TypeScript configuration
├── .env.example              # Environment template
├── .gitignore                # Git ignore rules
├── docs/
│   ├── ARCHITECTURE.md       # Architecture documentation
│   └── MCP-TOOLS-SPEC.md     # Detailed tool specifications
└── src/
    ├── index.ts              # Server entry point
    ├── tools/
    │   ├── index.ts          # Tool exports
    │   ├── account.ts        # mt4_get_account
    │   ├── positions.ts      # mt4_get_positions, mt4_close_position
    │   ├── trading.ts        # mt4_execute_trade, mt4_modify_position
    │   └── quotes.ts         # mt4_get_quote
    └── services/
        └── mt4-client.ts     # MT4 Gateway HTTP client
```

---

## Development

### Build

```bash
npm run build
```

### Type Check

```bash
npm run typecheck
```

### Lint

```bash
npm run lint
npm run lint:fix
```

### Test

```bash
npm run test
npm run test:coverage
```

---

## Integration with Claude

### MCP Configuration

Add to your Claude/MCP configuration:

```json
{
  "mcpServers": {
    "mt4": {
      "url": "http://localhost:3605",
      "transport": "http"
    }
  }
}
```

### Example Agent Prompts

```
"Check my MT4 account balance"
→ Uses mt4_get_account

"What's the current gold price?"
→ Uses mt4_get_quote({ symbol: "XAUUSD" })

"Buy 0.1 lots of XAUUSD with stop loss at 2640"
→ Uses mt4_execute_trade({ symbol: "XAUUSD", action: "buy", lots: 0.1, stopLoss: 2640 })

"Close my profitable gold positions"
→ Uses mt4_get_positions({ symbol: "XAUUSD" }) + mt4_close_position for each
```

---

## Dependencies

### Runtime
- `express` - HTTP server
- `axios` - HTTP client
- `zod` - Input validation
- `dotenv` - Environment configuration
- `@modelcontextprotocol/sdk` - MCP protocol

### Development
- `typescript` - Type safety
- `ts-node-dev` - Development server
- `jest` - Testing framework
- `eslint` - Code linting

---

## Prerequisites

1. **MT4 Gateway** running on configured host:port
2. **MT4 Terminal** connected with EA Bridge active
3. **Node.js** >= 18.0.0

---

## Troubleshooting

### Cannot connect to MT4 Gateway
```bash
# Check if mt4-gateway is running
curl http://localhost:8081/status

# Verify environment variables
cat .env | grep MT4
```

### Tool execution fails
```bash
# Check health endpoint for dependency status
curl http://localhost:3605/health

# Check server logs
npm run dev  # Logs will show in console
```

### Invalid parameters error
```bash
# Verify tool schema
curl http://localhost:3605/tools/mt4_execute_trade

# Check parameter names match schema
```

---

## References

- [MCP Protocol](https://modelcontextprotocol.io)
- MT4 Gateway: `apps/mt4-gateway/`
- SIMCO-MCP: `orchestration/directivas/simco/SIMCO-MCP.md`
- Architecture: `docs/ARCHITECTURE.md`
- Tool Specs: `docs/MCP-TOOLS-SPEC.md`

---

**Maintained by:** @PERFIL_MCP_DEVELOPER
**Project:** Trading Platform
