mcp-mt5
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-mt5 compile and backtest my moving average EA"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mcp-mt5
Model Context Protocol server for the MetaTrader 4/5 build pipeline. Compile MQL sources, deploy compiled EAs, run Strategy Tester, parse reports, tail logs — all driven by an LLM agent without touching the MetaTrader UI.
What this is — and what it isn't
✅ This server | ❌ Not this server |
MetaTrader dev harness — compile, deploy, backtest, parse | Live trading (orders, positions, quotes) |
Wraps | Wraps the |
Runs entirely offline against installed terminal | Connects to a broker server |
Iterates strategies before they go live | Executes strategies in production |
Use case: an LLM agent edits
.mq5source → compiles → deploys → runs Strategy Tester → reads report → adjusts → repeats. No broker login, no human in the loop, no risk of real-money execution.
For runtime trading, pair this with a live-trading MCP — they target different layers and compose well.
Related MCP server: mcp-mt5
Tools
The server exposes 32 tools and 3 MCP resources across nine categories.
🔍 Discovery & terminal selection
Tool | Description |
| Dump resolved paths, terminal hash, edition, and missing-component issues |
| Enumerate every MT4/5 terminal data folder under |
| Switch the active terminal data folder mid-session by origin path, hash, or install dir — handy for testing across multiple brokers |
🔨 Build & deploy
Tool | Description |
| Invoke MetaEditor CLI on a |
| Compile, then copy the resulting |
| Same as |
| Compile + deploy + run a 1-day headless backtest + scan the journal for runtime errors. Catches problems that pass |
| Copy a compiled binary into |
| Copy a |
| Enumerate |
🔎 Source analysis
Tool | Description |
| Parse |
| Auto-build a |
| Recursive |
| Grep a symbol across MQL files, skipping comments and string literals |
| LOC, function count, max nesting per file — or aggregated across an entire tree |
| Pull MetaEditor |
| Detect duplicate magic-number assignments across the project |
⚠️ Lint & validation
Tool | Description |
| Structural rules: missing |
| Flag MT4-style API calls ( |
| Sanity-check a |
🎨 Format
Tool | Description |
| Format a source file via |
| Same as above but reports whether changes are needed without writing the file |
✏️ Refactor
Tool | Description |
| Whole-word rename across all MQL files in a tree, with |
| Brace-aware extraction of a contiguous block into a new helper function — inline or into an external |
📊 Strategy Tester
Tool | Description |
| Programmatically update keys in a |
| Launch |
| [LEGACY] Best-effort parser for the latest |
| [LEGACY] Sort optimization passes by a chosen criterion and return the top N |
| High-fidelity CSV reader for optimization results generated via |
| Start non-blocking Strategy Tester runs (backtest or optimize) using SQLite tracking |
| Poll execution status, elapsed time, and exit codes of background runs |
| Retrieve full parsed backtest report or optimization CSV after job completion |
| Query the history and status of all background Strategy Tester executions |
| Automatically write OptExport include and OnTester log code into any EA source |
| Locate and parse the latest tester HTML report into a structured |
| Diff two tester reports key-by-key with absolute and percent deltas |
| Verify a candidate report stays within guard thresholds vs a baseline (e.g. "net_profit may not drop more than 5%") |
|
|
📝 Logs & snapshots
Tool | Description |
| Tail the last N lines of either |
| Freeze a copy of source files into a timestamped folder with a |
| Enumerate previously captured snapshots |
📡 MCP resources
Live, re-readable URIs that an MCP client can poll instead of calling a tool repeatedly.
URI | Description |
| Latest tail of |
| Today's daily MT5 journal log |
| Most recent Strategy Tester journal |
Quick start
Install
pip install mcp-mt5Requires Windows + an installed MetaTrader 4 or 5 terminal.
Register with an MCP client
Most MCP clients accept a JSON entry under mcpServers. The server inherits its configuration from environment variables:
{
"mcpServers": {
"mt5": {
"command": "mcp-mt5",
"env": {
"MT5_INSTALL": "C:\\Program Files\\MetaTrader 5"
}
}
}
}Refer to your client's documentation for the exact config file location.
Verify the install
Once registered, ask your agent to call env_info:
{
"edition": "mt5",
"install": "C:\\Program Files\\MetaTrader 5",
"terminal_hash": "<32-char-hex-hash>",
"metaeditor": "C:\\Program Files\\MetaTrader 5\\MetaEditor64.exe",
"experts_dir": "C:\\Users\\<you>\\AppData\\Roaming\\MetaQuotes\\Terminal\\<hash>\\MQL5\\Experts",
"issues": []
}An empty issues array means everything is wired up correctly.
Configuration
Resolution priority for the MetaTrader install + data folder:
Explicit env vars (below)
Auto-scan of
%APPDATA%\MetaQuotes\Terminal\*\origin.txtfor a folder whose origin matchesMT5_INSTALLPortable mode fallback (data colocated with install dir)
Env var | Default | Notes |
|
| Install dir containing |
| (auto-detected) |
|
| (auto-detected) | 32-char folder name |
|
| Set to |
MT4 support
Set MT5_EDITION=mt4 and point MT5_INSTALL at your MT4 install. The server switches to metaeditor.exe (32-bit), terminal.exe, and the MQL4/ data tree automatically.
Example workflow
A typical LLM-driven iteration loop:
1. env_info → verify paths
2. compile_and_deploy source="MyEA.mq5" → 0 errors, .ex5 deployed ✅
3. patch_tester_ini config="tester.ini" updates={
"Tester.Symbol": "EURUSD",
"Tester.FromDate": "2025.01.01",
"TesterInputs.RiskPct": "1.5"
}
4. run_backtest config="tester.ini" wait=true
5. read_tester_report → summary.net_profit = 1234.56
summary.profit_factor = 1.45
6. tail_log mode="tester" lines=200 structured=true → diagnose journal warnings
7. <edit Signal.mqh based on findings>
8. → loop back to step 2A sample tester.ini
; Launch: terminal64.exe /config:tester.ini
; Period codes: M1=1, M5=5, M15=15, H1=16385, H4=16388, D1=16408
; Model: 0=Every tick, 1=1 min OHLC, 4=Real ticks
[Tester]
Expert=MyEA
Symbol=EURUSD
Period=M15
Model=1
FromDate=2024.01.01
ToDate=2024.12.31
Deposit=10000
Currency=USD
Leverage=500
Visual=0
ShutdownTerminal=1 ; required so run_backtest can wait for the run to finish
Report=tester_report
[TesterInputs]
; ParamName=value||start||step||stop||(N=fixed|Y=optimize)
; RiskPct=1.0||0.1||0.1||3.0||NA more complete sample lives at examples/tester.ini.
Remote access from Linux client
Since MetaTrader 5 and MetaEditor must run on Windows, but your development environment may be on Linux/macOS, mcp-mt5 provides two remote connection patterns:
Option A: Token-Authenticated HTTP Transport (streamable-http)
Run mcp-mt5 as a network web service. Set MCP_MT5_TRANSPORT=http and configure a secure Bearer token via MCP_MT5_TOKEN:
# On the Windows Server VPS:
set MCP_MT5_TRANSPORT=http
set MCP_MT5_PORT=8931
set MCP_MT5_TOKEN=your-random-secure-token
python -m mcp_mt5.serverThen connect from your Linux client using standard streamable-http MCP setup:
{
"mcpServers": {
"mt5": {
"command": "mcp-client-streamable-http",
"args": ["http://<your-vps-ip>:8931/mcp"],
"env": {
"Authorization": "Bearer your-random-secure-token"
}
}
}
}Note: For production deployments, it is highly recommended to bind to 127.0.0.1 and place a reverse proxy (like Caddy or Nginx) in front of the server to handle TLS and restrict public interfaces.
Option B: SSH stdio bridge
Run the MCP server locally over an SSH connection. This option requires no port exposure or network transport configuration on the server:
{
"mcpServers": {
"mt5": {
"command": "ssh",
"args": [
"username@winserver-vps",
"python -m mcp_mt5.server"
]
}
}
}Development
git clone https://github.com/PHUICMT/mcp-mt5
cd mcp-mt5
pip install -e ".[dev]"
pytest # runs the 18-test suite
ruff check src tests # lintsCI runs on Windows for Python 3.10, 3.11, and 3.12 against every push to main. Tagging a release (e.g. v0.2.0) triggers an OIDC publish to PyPI.
Project layout
mcp-mt5/
├── src/mcp_mt5/
│ ├── server.py # FastMCP tool definitions
│ ├── paths.py # Layout detection + origin.txt scan
│ └── parsers.py # Compile log + tester HTML report parsers
├── tests/ # 18 pytest tests, no live MT5 required
├── examples/ # Sample tester.ini + client config
└── .github/workflows/ # CI + PyPI releaseLimitations
Windows-only. MetaTrader CLI binaries don't ship for Linux/macOS. Wine ports may work but are untested.
No live broker access. This server intentionally never authenticates to a broker. Use a separate MCP server for runtime trading.
Tester report parsing is best-effort. MetaTrader's HTML output isn't a stable schema; the raw HTML is also returned alongside the parsed structure so you can fall back to text inspection when needed.
Optimization runs (.opt) are best-effort (legacy). Binary
.optfiles are unreliable to parse directly due to changing format layouts across MT5 builds. For high-fidelity optimization runs, it is recommended to instrument your Expert Advisor withOptExport.mqhand retrieve optimization passes via theread_optimization_csvtool.
Roadmap
All v0.3.x roadmap items shipped in v0.4.0. Future ideas:
Real tree-sitter MQL grammar for
extract_function(current implementation is brace-counting + regex)WebSocket transport for long-lived sessions (currently stdio only)
Linux/Wine port for non-Windows agents
License
MIT © 2026 PHUICMT
Available Tools
41 toolscheck_deprecatedC
Flag MT4-style deprecated API calls in MT5 source.
Inputs: source (required).
check_job_statusA
Check the status and elapsed duration of a background execution job.
Args: job_id: The job ID returned by start_job.
Inputs: job_id (required).
code_metricsA
Compute LOC/function/nesting metrics for a file or every MQL file under a root.
Inputs: root, source.
compare_reportsB
Diff two MT5 tester HTML reports key-by-key with absolute and percent deltas.
Inputs: baseline (required), candidate (required).
compileA
Compile a .mq4/.mq5/.mqh source via MetaEditor CLI.
Args:
source: Absolute path to the source file.
include: Optional MQL root override (parent of Include/). Defaults to terminal MQL root.
log_file: Optional explicit log path. Defaults to .log.
timeout_sec: Subprocess timeout.
Returns: returncode, structured errors/warnings lists, result_errors/result_warnings,
log_path, log_excerpt (last 80 lines), cmd.
Inputs: source (required), include, log_file, timeout_sec.
compile_and_deployC
Compile then deploy resulting .ex5/.ex4 to Experts/ in one shot.
Inputs: source (required), ea_name.
deploy_eaA
Copy compiled .ex4/.ex5 binary into Experts/.
Args: source_ex: Path to compiled .ex4/.ex5. name: Optional rename target.
Inputs: source_ex (required), name.
env_infoB
Resolve and report MT4/5 paths, terminal hash, and missing-component issues.
Inputs: no named parameters.
extract_docB
Extract MetaEditor //+--+ //| ... +--+ doc blocks from a source file.
Inputs: source (required).
extract_functionA
Extract a contiguous block of lines into a new helper function.
Brace-counting + regex param detection — not a full AST parser. Returns the
proposed helper, call site, and parameter list. Set dry_run=False to write.
Inputs: source (required), line_end (required), new_name (required), line_start (required), +3 more.
extract_inputsC
Parse input <type> <name> = <default>; declarations from a source file.
Inputs: source (required).
find_magic_collisionC
Find duplicate magic-number assignments across the project.
Inputs: root (required), var_pattern.
find_symbolB
Grep a symbol across MQL files, skipping comments and string literals.
Inputs: root (required), symbol (required), exts, limit.
format_checkB
Report whether a file needs formatting without writing it.
Inputs: source (required), style.
format_mqlB
Format an MQL file via clang-format (treats source as C++).
Inputs: source (required), style, write.
gen_tester_inputsC
Generate a [TesterInputs] block from EA inputs.
If write_to points at a tester.ini, the block is appended/replaced in-place.
Inputs: source (required), write_to.
get_job_resultB
Retrieve full structured results of a completed background job.
Args: job_id: The job ID returned by start_job.
Inputs: job_id (required).
install_includeB
Copy a .mqh into the terminal Include folder (e.g. for LiveLog.mqh).
Args: source: Absolute path to source .mqh. target_name: Optional rename.
Inputs: source (required), target_name.
instrument_ea_for_optB
Automatically instrument an MQL5 Expert Advisor (.mq5) file with OptExport.mqh logging.
Args: ea_path: Absolute path to the .mq5 file.
Inputs: ea_path (required).
kill_terminalA
Force-kill all running terminal processes for the configured edition.
Inputs: no named parameters.
lint_basicC
Run structural lint rules (missing handlers, unused inputs, hardcoded magic/symbol).
Inputs: source (required).
list_expertsC
List compiled EAs in Experts/.
Inputs: pattern, recurse.
list_jobsA
List recent Strategy Tester execution jobs tracked in the database.
Args: limit: Maximum number of jobs to return (default 20). status: Optional filter by job status (e.g. 'running', 'done', 'failed').
Inputs: limit, status.
list_snapshotsB
List all snapshot folders under dest.
Inputs: dest (required).
list_terminalsA
Enumerate all MetaTrader terminal data folders under %APPDATA%\MetaQuotes\Terminal.
Inputs: no named parameters.
parse_optimizationA
[LEGACY] Best-effort binary .opt parser — unreliable, prefer read_optimization_csv with OptExport.mqh instrumented EA.
Parse the latest .opt file in the Tester folder, or one given by path.
Inputs: path.
patch_tester_iniA
Update fields in a tester.ini file in-place.
Args:
config: Path to tester.ini.
updates: Mapping of Section.Key → value (e.g. {"Tester.Symbol": "EURUSD", "Tester.FromDate": "2025.01.01"}).
Returns dict listing applied + skipped keys.
Inputs: config (required), updates (required).
read_optimization_csvA
Read optimization results from the CSV file generated by OptExport.mqh in Common Files folder.
Args: run_id: The run ID specified during optimization run. top_n: Number of top passes to return. criterion: The column name to sort by (e.g. 'profit', 'sharpe_ratio', 'custom_metric'). descending: Set to True to sort from highest to lowest.
Inputs: run_id (required), top_n, criterion, descending.
read_tester_reportB
Locate and parse latest MT5 tester HTML report.
Args: path: Explicit report path. If omitted, find latest *.htm under Tester/. raw_truncate: Max chars of raw HTML returned.
Inputs: path, raw_truncate.
regression_checkC
Verify candidate report stays within guard thresholds vs baseline.
Inputs: baseline (required), candidate (required), guards.
rename_symbolB
Rename a symbol across MQL files (whole-word match). dry_run=True previews only.
Inputs: new (required), old (required), root (required), dry_run.
resolve_includesB
Recursively resolve #include directives. Reports unresolved files.
Inputs: source (required), mql_root.
run_backtestB
Launch terminal with /config:<tester.ini>.
Args:
config: Absolute path to tester.ini.
wait: Block until terminal exits (requires ShutdownTerminal=1 in ini).
timeout_sec: Wait timeout.
portable: Pass /portable flag.
Returns: returncode, elapsed_sec, latest_tester_log path.
Inputs: config (required), wait, portable, timeout_sec.
select_terminalA
Switch the active terminal data folder for this session.
Provide one of: origin (install path stored in origin.txt), hash (32-char
folder name), or install (auto-scan for the matching origin).
Subsequent tool calls will use the new layout until the server restarts.
Inputs: hash, origin, edition, install.
smoke_testB
Compile, deploy, run a 1-day headless backtest, and scan the journal for runtime errors.
Returns ok: true only if compilation, deployment, run, and the journal scan all pass.
Inputs: source (required), days, period, symbol, +2 more.
snapshot_sourcesC
Freeze a copy of source files into a timestamped folder under dest.
Inputs: dest (required), sources (required), label.
start_jobA
Start a non-blocking backtest or optimization Strategy Tester run.
Args: config: Absolute path to the tester .ini configuration file. kind: Execution type, either "backtest" or "optimize".
Inputs: kind (required), config (required).
syntax_checkA
Compile a source via MetaEditor's syntax-only mode (/s) and return diagnostics.
Inputs: source (required), timeout_sec.
tail_logA
Read last N lines from terminal logs.
Args: mode: "live" (Files/LiveLog.txt), "journal" (Logs/YYYYMMDD.log), "tester" (latest tester log). lines: Tail line count. date: Override YYYYMMDD for journal mode. structured: Parse journal lines into ts/source/message records.
Inputs: date, mode, lines, structured.
top_passesA
[LEGACY] Best-effort binary .opt parser — unreliable, prefer read_optimization_csv with OptExport.mqh instrumented EA.
Sort optimization passes by criterion and return the top N.
Inputs: n, opt_path, criterion, descending.
validate_tester_iniB
Sanity-check a tester.ini. If source given, cross-check inputs vs EA declarations.
Inputs: config (required), source.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 41 tools
Most tools have distinct purposes, but the legacy tools `parse_optimization` and `top_passes` overlap with `read_optimization_csv` and are explicitly noted as unreliable, creating potential confusion for agents.
The majority of tools follow a verb_noun pattern (e.g., list_terminals, run_backtest), but a few exceptions like `code_metrics`, `syntax_check`, and `top_passes` break the pattern slightly, resulting in minor inconsistency.
With 41 tools, the server covers a broad scope but feels slightly bloated. Some redundancy (e.g., legacy optimization parsers) and the possibility of merging tools like `compile` and `compile_and_deploy` suggest the count could be reduced without losing functionality.
The toolset covers the full development lifecycle for MQL5: environment setup, compilation, backtesting, optimization, code analysis, refactoring, and job management. Minor gaps like missing file creation or EA removal are acceptable for the focused domain.
Related MCP Connectors
Let AI agents read and trade MetaTrader 5 accounts. Sign in with OAuth; read-only unless you allow.
Build, backtest, and deploy quantitative trading strategies from your AI agent.
Read-only access to your MetaTrader 4 and 5 accounts for AI agents: balances, open positions, trade history with win rate, live quotes, symbol specs and candles. It cannot place, modify or close orders.
Build, validate, and deploy multi-agent AI solutions from any AI environment.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceConnects MCP clients to MetaTrader 5 MetaEditor on Linux via Wine, enabling automated MQL5 development workflows including code editing, compilation of EAs/indicators, and strategy backtesting.6MIT
- AlicenseBqualityBmaintenanceModel Context Protocol server for the MetaTrader 4/5 build pipeline, enabling LLM-driven compilation, deployment, backtesting, and log tailing without UI interaction.4353 PyPI20MIT
- AlicenseNot gradedqualityAmaintenanceExposes a unified AI interface to MetaTrader 5 over the Model Context Protocol, enabling live quotes, historical data, technical indicators, order execution, position management, and headless backtests.108 PyPIMIT
- AlicenseNot gradedqualityCmaintenanceEnables AI assistants to trade on MetaTrader 5 using natural language, supporting account management, order placement, and real-time market data.1MIT