Content
# MT5 MCP Server
> Give Claude AI autonomous, end-to-end control over MetaTrader 5.
An MCP (Model Context Protocol) server that bridges Claude and MetaTrader 5 — letting the AI write MQL5 Expert Advisors, compile them, run unattended backtests, fetch live prices, calculate indicators, and analyze trade history, all in a single loop without human intervention.
---
## What It Does
Traditional algo-trading research is a slow manual cycle: write code → open MetaEditor → compile → open Strategy Tester → configure → run → read report → repeat. This server collapses that entire cycle into tool calls that Claude can invoke autonomously.
```
Claude writes EA code → compile_mql5 → run_backtest → get_backtest_results → analyze → iterate
```
Claude can also scan the entire broker symbol list for setups, calculate indicators on any timeframe, and monitor open positions and closed trade history — all without you touching the MetaTrader terminal.
---
## Tools (16 total)
### EA Manager
| Tool | Description |
|------|-------------|
| `write_ea` | Write MQL5 EA / indicator / script code to the MT5 Experts folder |
| `compile_mql5` | Compile a `.mq5` file via MetaEditor; returns errors and warnings |
| `write_file` | Write any text file (Python script, config, CSV) to disk |
| `read_file` | Read any text file — logs, reports, existing EA code |
| `list_files` | List files in a directory (defaults to `Experts/AI_Generated`) |
### Backtester
| Tool | Description |
|------|-------------|
| `run_backtest` | Run MT5 Strategy Tester unattended for a compiled EA; detects completion via tester log |
| `get_backtest_results` | Parse backtest results — net profit, win rate, profit factor, best/worst trade, full trade list |
### Market Data
| Tool | Description |
|------|-------------|
| `get_price` | Live bid/ask price and spread for any symbol |
| `get_price_data` | Historical OHLCV candles (up to 5000 bars, any timeframe) |
| `get_symbols` | List all available symbols on the connected broker |
| `get_account_info` | Account balance, equity, margin, leverage, and floating P&L |
| `run_python` | Execute arbitrary Python code with MT5 library available; returns stdout |
### Indicators
| Tool | Description |
|------|-------------|
| `calculate_indicators` | EMA, SMA, RSI, MACD, ATR, Bollinger Bands on any symbol/timeframe |
| `scan_symbols` | Scan the entire broker symbol list for a condition (EMA crossover, RSI extremes, trend direction) |
### Trade Manager
| Tool | Description |
|------|-------------|
| `get_open_positions` | All open positions — ticket, direction, volume, entry, current price, floating P&L |
| `get_trade_history` | Closed trade history with full stats: win rate, profit factor, per-symbol breakdown |
---
## Architecture
```
Claude (via MCP client)
│
▼
server.py (MCP server — stdio transport)
│
┌────┴────────────────────────────┐
│ │
tools/ea_manager.py tools/market_data.py
tools/backtester.py tools/indicators.py
tools/trade_manager.py
│
▼
MetaTrader 5 (terminal + MetaEditor)
```
- **Transport**: stdio (MCP standard)
- **MT5 connection**: `MetaTrader5` Python library (COM bridge to the running terminal)
- **Backtest detection**: polls the tester log file; no XML parsing needed
- **Indicator calculation**: pure pandas/numpy on OHLCV data fetched from MT5
---
## Requirements
- Windows (MetaTrader 5 is Windows-only)
- MetaTrader 5 terminal installed and logged in
- Python 3.10+
- Claude Desktop or any MCP-compatible client
---
## Installation
**1. Clone the repo**
```bash
git clone https://github.com/tusharrayamajhi/mt5-mcp-server.git
cd mt5-mcp-server
```
**2. Install dependencies**
```bash
pip install mcp MetaTrader5 pandas lxml
```
**3. Edit `config.py`** — set paths to your MT5 installation:
```python
META_EDITOR_PATH = r"C:\Program Files\MetaTrader 5\MetaEditor64.exe"
TERMINAL_PATH = r"C:\Program Files\MetaTrader 5\terminal64.exe"
EXPERTS_DIR = r"C:\Users\<you>\AppData\Roaming\MetaQuotes\Terminal\<ID>\MQL5\Experts"
```
**4. Register with Claude Desktop** — add to `~/.claude/settings.json`:
```json
{
"mcpServers": {
"mt5": {
"command": "python",
"args": ["C:\\path\\to\\mt5-mcp-server\\server.py"]
}
}
}
```
**5. Start MetaTrader 5**, then restart Claude Desktop. The `mt5` server appears in the MCP tool list.
---
## Usage Examples
### Write and backtest an EA from scratch
```
Claude prompt: "Write an EMA(10/50) crossover EA for EURUSD H1 with 1% risk per trade,
1.5x ATR stop loss, and 3x ATR take profit. Compile it and run a backtest
from 2024.01.01 to 2025.01.01 with $10,000 deposit."
```
Claude will call `write_ea` → `compile_mql5` → `run_backtest` → `get_backtest_results` and return a full performance report.
### Scan for setups across the market
```
Claude prompt: "Scan all EUR pairs on H4 for bullish EMA(25/100) crossovers."
```
Claude calls `scan_symbols` with `condition: "ema_crossover"` and `search_filter: "EUR"`.
### Analyze your live account
```
Claude prompt: "Show me my open positions and last 30 days trade history with a breakdown by symbol."
```
Claude calls `get_open_positions` and `get_trade_history`.
### Run custom analysis in Python
```
Claude prompt: "Calculate the Sharpe ratio of my EURUSD trades from 2025."
```
Claude calls `run_python` with custom code that queries MT5 history and computes the metric.
---
## Backtest: EMA(25/100) + Regime Filter — EURUSD H1
This strategy was researched end-to-end using the MCP server. Claude iterated through multiple versions autonomously.
**Parameters**
| Setting | Value |
|---------|-------|
| Fast EMA | 25 |
| Slow EMA | 100 |
| Trend filter EMA | 200 (H4 alignment) |
| Stop loss | 1.5× ATR |
| Take profit | 3.0× ATR |
| Position sizing | 1% risk per trade (compounding) |
| Regime filter | Choppiness Index < 61.8 + ADX > 15 |
| ATR entry filter | < 0.6× average ATR (avoid high-volatility entries) |
**Results (2024–2026, after spread + $7 commission RT + swap)**
| Period | Net P&L | Return | Profit Factor | Max Drawdown |
|--------|---------|--------|---------------|--------------|
| 2024 | +$1,891 | +18.9% | 2.80 | 2.3% |
| 2025 | +$1 | 0.0% | 1.00 | 6.3% |
| 2026 Jan–Jun | +$120 | +1.2% | 1.18 | 4.6% |
| **3yr combined** | **+$2,042** | **+20.4%** | **1.59** | **6.3%** |
- Annualized: **~7.9%/year** after all fees
- Trade frequency: ~22 trades/year (very selective — only enters in trending, low-choppiness conditions)
- Best broker fit: market maker with tight spread (avoid ECN commission structures)
**Key finding from the research**: adding a break-even stop or trailing stop *hurts* performance for this strategy — the wide ATR-based TP needs room to breathe.
---
## Backtest Scripts
All scripts in the repo root were used during the research process:
| Script | Purpose |
|--------|---------|
| `backtest_ma_crossover.py` | v1 baseline — raw EMA crossover |
| `backtest_ma_v2.py` | v2 — added 200 EMA trend filter |
| `backtest_all.py` | Full strategy suite comparison |
| `regime_final.py` | **Final strategy** — regime detector (best results) |
| `multi_year_test.py` | Year-by-year breakdown (2024/2025/2026) |
| `broker_fees_test.py` | Impact of spread, commission, and swap |
| `scale_test.py` | Compounding and portfolio scaling tests |
| `be_optimize.py` | Break-even / trailing stop optimization (conclusion: don't use them) |
| `long_short_breakdown.py` | Long vs short trade performance split |
| `flip_test.py` | What happens if you reverse every signal |
---
## Project Structure
```
mt5-mcp-server/
├── server.py # MCP server entry point — registers all 16 tools
├── config.py # Paths to MetaEditor, terminal, Experts dir
├── requirements.txt
├── tools/
│ ├── ea_manager.py # write_ea, compile_mql5, read/write/list files
│ ├── backtester.py # run_backtest, get_backtest_results
│ ├── market_data.py # get_price, get_price_data, get_symbols, get_account_info, run_python
│ ├── indicators.py # calculate_indicators, scan_symbols
│ └── trade_manager.py # get_open_positions, get_trade_history
└── [backtest research scripts] # All scripts used during strategy research
```
---
## Limitations
- **Windows only** — MetaTrader 5 and its Python library only run on Windows
- **Terminal must be running** — the MT5 Python library connects to an already-open terminal instance
- **Backtest speed** — Strategy Tester runs at MetaTrader's own speed; complex EAs on tick data can take minutes
- **No live order execution** — this version is read/research focused; live trade execution tools are not included
---
## License
MIT