Content
# mt5-mcp-server
Automatically operate **MetaTrader 5's Strategy Tester** with AI using **MCP Server** (Python / FastMCP / stdio).
When you ask an MCP client like Claude Code to "backtest and optimize this EA on EURUSD H1 for 2024",
it automatically generates `.ini`, starts `terminal64.exe`, waits for completion, analyzes the report, and returns structured results.
> **Windows only** (MT5 Strategy Tester is Windows only). Python 3.10+.
## Tool List
| Tool | Overview |
|---|---|
| `mt5_info` | Detect default MT5, data folder, build, EA count, and whether it's running (for setup confirmation) |
| `list_mt5_terminals` | List all detected MT5 installations (by broker) |
| `list_eas` | List `.ex5` files in `MQL5/Experts/` (pass `rel_path` to `ea`) |
| `run_backtest` | Run a single backtest → return net profit, PF, DD, win rate, trade count, etc. |
| `optimize` | Genetic optimization → find best N and optimal parameters (`min_trades` for trade count limit) |
| `run_forward_test` | Run an out-of-sample (OOS) test with fixed parameters |
| `full_pipeline` | Perform IS optimization → OOS verification → over-optimization check in one go |
| `send_to_iwaraizer` | Send MT5 backtest trade details to Iwaraizar FX for analysis (with keepdata injection) |
## Requirements
- **Windows 10/11**
- **Python 3.10+**
- **MetaTrader 5 installed** and **logged in to the target account** with **downloaded history**
(if not logged in or no history, report will be generated but with `history_quality=0%` and 0 trades)
## Installation
```powershell
# pipx (recommended and isolated installation)
pipx install git+https://github.com/iwanao513/mt5-mcp-server
# After PyPI release: pipx install mt5-mcp-server
# uvx (zero-install execution)
uvx --from git+https://github.com/iwanao513/mt5-mcp-server mt5-mcp-server
# After PyPI release: uvx mt5-mcp-server
# From source (development)
git clone https://github.com/iwanao513/mt5-mcp-server
cd mt5-mcp-server
python -m venv .venv
.\.venv\Scripts\python -m pip install -e .
```
In all cases, the executable file `mt5-mcp-server` will be added to PATH (or venv).
## Registration to MCP Client
This is a stdio server. All clients use the same format for `command`/`args`, with different configuration files.
**Claude Code**
```powershell
claude mcp add mt5 -- mt5-mcp-server
# If only in venv, pass the full path to the executable:
# claude mcp add mt5 -- "<REPO>\.venv\Scripts\mt5-mcp-server.exe"
```
**Claude Desktop** (`%APPDATA%\Claude\claude_desktop_config.json`)
```json
{ "mcpServers": { "mt5": { "command": "mt5-mcp-server", "args": [] } } }
```
**Cursor** (`.cursor/mcp.json`) / **Windsurf** (`~/.codeium/windsurf/mcp_config.json`) / **VS Code** (`.vscode/mcp.json` with `servers` key) can also be registered with `command: "mt5-mcp-server"`.
Confirmation: `claude mcp list` / `claude mcp get mt5` / `/mcp` in the client.
## Usage
1. Confirm detection with `mt5_info()` (if `is_running` is true, close the target MT5).
2. Get the `rel_path` of an EA with `list_eas("moving")`.
3. Run a backtest with `run_backtest(ea="Examples\\Moving Average\\Moving Average.ex5", symbol="EURUSD", from_date="2024.01.01", to_date="2024.06.30", period="H1")`.
4. Optimize with `optimize(ea=..., symbol="EURUSD", from_date="2024.01.01", to_date="2024.04.30", param_ranges={"MovingPeriod":[8,40,2],"MovingShift":[0,10,2]}, min_trades=40)`.
5. Perform a full pipeline with `full_pipeline(...)` for IS optimization → OOS verification → over-optimization check.
> If `list_eas` returns empty, open MetaEditor and compile an EA (e.g., `MQL5/Experts/Examples`) to generate a `.ex5` file.
## Choosing an MT5 (supporting multiple installations)
Use `list_mt5_terminals()` to check available terminals (by broker and build) and specify the target terminal by path.
- Tool argument `terminal_path` (per call): e.g., `run_backtest(..., terminal_path="C:\\Program Files\\XMTrading MT5\\terminal64.exe")`
- Set as default in user settings (below): `terminal_path`
If not specified, automatically detect from config → `C:\Program Files\MetaTrader 5` (if exists) → registry (including broker versions).
## Configuration
Configurations are read in the following order and merged with later wins:
1. Repository-included `config/mt5_config.json` (dev template with all nulls)
2. **User settings `%APPDATA%\mt5-mcp-server\mt5_config.json`** (for installation) / or `mt5_config.local.json`
3. Environment variable `MT5_MCP_CONFIG` (any JSON full path)
| Key | Default | Description |
|---|---|---|
| `terminal_path` | Auto-detect | Full path to `terminal64.exe` (or parent folder) |
| `data_folder` | Auto-detect | Infer from `origin.txt` |
| `default_deposit`/`default_currency`/`default_leverage` | 10000/USD/1:100 | |
| `default_model` | 1 | 0=every tick, 1=1-minute OHLC, 2=open, 4=real ticks |
| `backtest_timeout_sec`/`optimization_timeout_sec` | 1200/7200 | |
| `login`/`password`/`server` | (not set) | For headless auto-login (below) |
### Headless Auto-Login (also auto-downloads history)
If using an unlogged-in MT5, add account information to user settings to enable auto-login via `.ini` `[Common]` and auto-download missing history:
```json
{ "terminal_path": "C:\\Program Files\\XMTrading MT5\\terminal64.exe",
"login": 12345678, "password": "demo_password", "server": "XMTrading-Demo" }
```
> ⚠️ **Strongly recommend using a demo account** (do not store live password in plain text). `mt5_config.local.json` is gitignored. **Do not store `terminal_path`/`login`/`password` in tracked `mt5_config.json`** (to prevent commit accidents).
## Avoiding Over-Optimization
`full_pipeline` **splits IS (optimization) and OOS (verification) periods** and raises an `overfit_warning` if PF deteriorates, becomes unprofitable, or has too few trades in OOS.
Use `min_trades` to set a **trade count limit** and exclude parameters optimized by a few lucky trades.
It's safer to optimize **fewer parameters**.
## Iwaraizar FX Integration
Use `send_to_iwaraizer` to send **all trade details** of an MT5 backtest to Iwaraizar FX desktop app for analysis.
1. Run `run_backtest(...)` (returns `report_path`).
2. Run `send_to_iwaraizer(report_path=<that .htm>, title="My EA EURUSD", parameter="MovingPeriod=8; MovingShift=4")`.
- Reconstruct trades from the **Deals table** in FIFO order (in/out pairs) and append as **one dataset** to `%APPDATA%\iwaraizar_fx_public\keepdata\Contents.json` (with `.bak` auto-backup).
3. Open Iwaraizar FX → Additional data sets → Calculate to display charts/stats (PF/DD/win rate/monthly, etc.).
- The app side is **unmodified** (using `fs.watch` for auto-detection). Use `keepdata_dir` argument to override the save location.
- Verification: confirmed that reconstructed trades for 146 trades match "final balance - initial balance = report net profit".
## Troubleshooting
| Symptom | Cause / Solution |
|---|---|
| `terminal64.exe not found` | MT5 not detected. Confirm with `list_mt5_terminals()` or specify `terminal_path` in settings |
| `MetaTrader 5 is already running` | Target MT5 is running. Close it or set `close_running=true` |
| `no report produced` / `history_quality=0%` / 0 trades | Not logged in or no history. Log in to MT5 and download history (or specify login/password/server in settings) |
| `authorization ... (Old version)` | Terminal build is old and rejected by server. Update terminal or use the latest build |
| `list_eas` is empty | No `.ex5` files. Compile an EA with MetaEditor |
## Safety and Disclaimer
- Backtesting/trading carries risks. This tool is for verification assistance and does not guarantee results or strategy quality.
- `close_running` **shuts down** the target MT5 (default false; explicit opt-in).
- Stdio local server has **no external exposure**. Handle authentication information locally and never commit it.
## License
MIT License — see [LICENSE](LICENSE).