Listed from the MCP registry; nobody on Odel publishes it.

MCP server: One MCP server.

MT5-MCP-Quant

@severus-sysMCP server · External

Native Windows MCP server for MetaTrader 5 backtesting, Market Watch, calendar data, and analytics.

Computer controlv1.35.1MITRust
Freeno charge per call

Runs on your machine from its package; the steps are below.

What it does

  1. Reads
  2. Writes
  3. High impact

At most: only reads or looks up information.

What it costs

Free

Odel charges nothing per call. The publisher may charge for its own service.

Runs locally over stdio

This server isn't hosted — your MCP client launches it from a package registry. Use one of the commands below, or drop the config into your client (e.g. Claude Desktop).

MCP Bundlehttps://github.com/severus-sys/mt5-mcp-quant/releases/download/v1.35.1/mt5-mcp-quant-windows-x64.mcpbv1.35.1

Distributed as an MCP bundle (`https://github.com/severus-sys/mt5-mcp-quant/releases/download/v1.35.1/mt5-mcp-quant-windows-x64.mcpb`) — download it and import the bundle in your MCP client.

README19 min read

Native Windows MCP server for MetaTrader 5 strategy development. Compile, backtest, analyze, optimize, debug, manage Market Watch, export historical tick CSVs, and build static economic-calendar datasets through MCP tools—without Wine, WSL, or runtime GUI automation.

The repository, Rust crate, executable, MCP registration examples, and Agent Skill identifiers all use the mt5-mcp-quant / mt5_mcp_quant project identity.

You: "Backtest MyEA Jan-Mar, what caused the February drawdown?"

Claude: [compile → clean → backtest → analyze 1,847 deals]
        → Feb 14: BUY grid at L6, locking lot 1.75× base
        → Cutloss fired 17 points later
        → Recommendation: cap locking multiplier to ≤1.2×

Why MT5-MCP-Quant

Focus: Backtest organization, reporting, and analytics — capabilities MT5 itself doesn't provide.

MT5-MCP-QuantOthers
PlatformNative WindowsWindows integrations
Backtest pipeline✅ Full (compile → run → analyze)✅ Via MT5 Python package
Deal-level analytics✅ 19 dimensions, DB-backed❌
Report organization✅ SQLite (reports + deals) + search + history❌
MQL5 compilation✅ MetaEditor CLI⚠️ Via GUI or terminal
Optimization✅ Background + results parsing + .set generation⚠️ Terminal only, no parsing
Crash debugging✅ Native process, log, and resource diagnostics❌

Unlike integrations centered on the MetaTrader5 Python trading API, MT5-MCP-Quant focuses on Strategy Tester automation, report organization, deal-level insight, and optimization workflows.

Quick Start

Do I need to manage an .exe?

No, not during normal use. MT5-MCP-Quant is a native Windows MCP server, so the MCP client must start a Windows process in the background. That process is technically an .exe, but it is a one-time installation detail:

  • Do not double-click the binary. It speaks JSON-RPC over stdio and is meant to be started by an MCP client.
  • An AI coding agent can download or build it, save its path in the client configuration, and verify the connection once.
  • After registration, use natural-language prompts. Codex, Claude Code, OpenCode, or Hermes starts and stops MT5-MCP-Quant automatically.
  • cargo run does not remove the executable; Rust still builds one internally and makes every MCP startup slower. A registered release build is the recommended runtime.

In short: the runtime needs an executable, but the user should not have to manage it.

Requirements

  • Windows 10/11 x64 and native MetaTrader 5, opened once under the same user account
  • A logged-in MT5 demo or live account in the same interactive Windows session
  • For a pre-built release: no Rust or Visual Studio installation is required
  • For source builds only: Rust stable and Visual Studio’s Desktop development with C++ workload

Release formats

Each Windows release publishes two equivalent, checksummed artifacts:

  • mt5-mcp-quant-windows-x64.mcpb is the installable Windows MCP Bundle referenced by the MCP Registry.
  • mcp-mt5-mcp-quant-windows-x64.tar.gz is the portable archive for agents and manual installation.

Both contain the binary, configuration example, documentation, PowerShell installers, all ten MT5 skills, auditable MQL sources, README, changelog, and license. crates.io publishing is intentionally out of scope.

Agent-managed installation

Give this prompt to Codex, Claude Code, OpenCode, or Hermes from the repository directory:

Install and configure MT5-MCP-Quant on this Windows computer. Prefer the official pre-built Windows x64 release; build from source only when needed. Detect MT5 with scripts/setup.ps1, register the server as mt5_mcp_quant over stdio, install the Agent Skills for this client, and verify that healthcheck works and the documented tools are available. Do not ask me to launch the binary manually.

The agent should complete the whole one-time setup:

  1. Download the Windows x64 release, or build the Rust source when a release is unavailable.
  2. Run powershell -ExecutionPolicy Bypass -File scripts\setup.ps1 to detect the MT5 program and data directories.
  3. Register the runtime command and --stdio in the client's MCP configuration.
  4. Install the router and workflow skills with scripts\install-agent-skills.ps1.
  5. Ask for one client restart, then confirm MT5 readiness and the documented tool inventory.
  6. For Market Watch, historical ticks, or calendar work, compile the embedded MT5McpQuantBridge Service and ask the user to start it once from MT5 Navigator → Services → MT5-MCP-Quant.

The stored binary path is an internal runtime setting after step 3. Normal users should not need to remember, open, or pass that path in prompts.

Install Agent Skills

Install the router and nine workflow skills for Codex, Claude Code, OpenCode, and Hermes:

powershell
powershell -ExecutionPolicy Bypass -File scripts\install-agent-skills.ps1 -Client all

Users can then write a vague prompt such as “MT5 MCP'yi kullan ve EA'me bak.” The router performs safe discovery and selects the appropriate workflow without requiring a tool name. See Agent Skills.

The router starts with read-only orientation checks: MCP health, active account, available EAs, and the latest report. It then chooses setup, MQL development, set-file management, backtesting, optimization, tick export, calendar data, reporting, analytics, or recovery. When two materially different goals remain possible, it asks one outcome-level question instead of asking the user to choose an MCP tool.

First Backtest

Run a backtest on MyEA from 2025.01.01 to 2025.03.31

The AI runs the full pipeline: compile → clean cache → backtest → extract → analyze.

MCP Tools

Core workflow

ToolDescription
run_backtestFull pipeline: compile → clean → backtest → extract → analyze
run_backtest_quickAsync quick backtest using pre-compiled EA; poll status
run_backtest_onlyAsync raw backtest without compile/analysis; poll status
launch_backtestFire-and-forget: launch MT5 backtest, poll for completion
get_backtest_statusPoll running backtest status (MT5 running, report found, elapsed time)
run_optimizationGenetic optimization (background, returns immediately)
get_optimization_resultsParse optimization results after MT5 finishes
list_jobsList all optimization jobs with status
analyze_reportRead analysis.json from any report directory
compare_baselineCompare report vs baseline, return winner/loser verdict
compile_eaCompile MQL5 EA via MetaEditor
list_expertsList all EAs in MQL5/Experts directory
list_indicatorsList all indicators in MQL5/Indicators directory
list_scriptsList all scripts in MQL5/Scripts directory
healthcheckQuick server health check
list_symbolsList symbols with local Strategy Tester history

Backtest (including rolling) and optimization tools accept an optional integer model: 0 = simulated Every tick (the default), 1 = 1 minute OHLC, 2 = Open prices, or 4 = Every tick based on real ticks. Other values and non-integer inputs are rejected. Model 4 records the requested tester mode; it does not by itself establish actual real-tick coverage or data quality. Optimization retains its existing M1 period and uses local agents only.

Backtest and optimization launches share a durable execution manager and a process-lifetime installation lock. An accepted launch is not completed: completion requires verified owned-process exit, stable exact report bytes, successful native parsing and committed finalization. Status reads do not launch tests and do not infer completion from metrics.json or a DONE marker. UUID execution/report identities and raw artifacts support restart recovery; unresolved spawn ownership blocks new launches instead of killing by PID/name. shutdown=false stops only the identity-verified owned child after a stable, complete native report is available, then reparses and finalizes after exit.

Captured native OnInit aborts are technical failures even if the terminal writes a recognized zero-trade HTML report. Raw/journal evidence remains hash-bound; new monetary finalization is refused. Current validation also marks historical finalized rows unavailable when their immutable journal proves such an abort, without rewriting stored observations. Broker evidence follows the explicit login/server pair or the saved native account actually selected by the INI.

Close an interactive terminal yourself before starting tester work. kill_existing defaults to false, including rolling tests, and does not grant authority to terminate unowned processes or steal managed work. Compilation, cache deletion and installed tester-profile writes refuse instance_busy during managed ownership. Stdio/TCP status calls remain responsive while work runs.

Market Watch, historical ticks, and economic calendar

ToolDescription
ensure_market_watch_symbolResolve broker suffix/prefix aliases without guessing, select the exact symbol, and verify Market Watch visibility
prepare_tick_exportStart historical tick export using explicit UTC/offset bounds and an agent-selected CSV filename
inspect_tick_exportPoll persistent progress and publish the complete CSV into the selected project/data or absolute destination
research_dataset_registerRegister a complete tick export as an immutable, SHA-addressed dataset with streaming quality
research_dataset_inspectVerify current CSV/manifest bytes and read redacted catalogue metadata
research_listPaginate stored datasets or experiments by symbol; limit 1–100, default 20
prepare_calendar_exportCreate an idempotent asynchronous export job against the active broker's live MT5 calendar
inspect_calendar_exportPoll job state, progress, row count, coverage, validation, and machine-readable errors
prepare_calendar_backtest_datasetPublish a validated CSV v1 dataset and checksum manifest for Strategy Tester EAs

The embedded MT5McpQuantBridge MQL5 Service is optional for existing backtest/report operations and required for broker-catalog/Market Watch, historical tick export and live-calendar operations. Start it once from MT5 Navigator, and restart it after an embedded Service version upgrade.

Tick export example:

json
{"symbol":"EURUSD.pro","from":"2026-10-02T12:00:00Z","to":"2026-10-02T12:01:00Z","output_path":"data/EURUSD.pro_ticks.csv"}

Call prepare_tick_export, then poll inspect_tick_export with the returned job_id until complete or failed. Inspection publishes an Excel-compatible UTF-8 CSV; it does not return every tick inline. Relative paths use configured project_dir or the MCP server's cwd; absolute destinations outside the project are supported. The agent chooses the filename; existing files are never overwritten. Times use UTC [from,to) semantics, not calendar server-time strings. Import through Excel Data > From Text/CSV; CSV retains all rows, while a worksheet holds at most 1,048,575 data rows plus its header. Import large integers as Text to avoid Excel's 15-digit precision limit.

After an export is complete, call research_dataset_register with its job_id. Registration and inspection do not require a running bridge. Manifests under Config::installation_dir()/research/datasets reference the original absolute CSV path, hash and byte count without copying or rewriting it. Every consuming read verifies current bytes; mutation or deletion invalidates the dataset. Coverage is observed_ticks_only, not proof of complete broker retention. Quality separates same-ms extras from adjacent exact duplicates, excludes unusable quotes from raw-price spread statistics and reports observed gaps without calling them missing data. Empty exports have null spread statistics and are insufficient for price analysis. Public summaries omit account login.

Non-native real-binary contract verification:

text
python tests/research_lab.py --binary target/release/mt5-mcp-quant.exe --contract-only

This uses isolated fixture exports and database state; it is not live-broker or Strategy Tester acceptance and does not launch native MT5 work.

Frozen research recipes

research_experiment_prepare({spec_path}) reads a server-host UTF-8 JSON version-1 recipe. All fields are mandatory; unknown fields are rejected. It validates dimensions, historical native-naive [from,to) dates, scalar set overrides, costs/bootstrap and the checked worst-case budget before writes: symbols × timeframes × (folds × (candidate_count + 1) + 1). Empty or duplicate dimensions, duplicate normalized candidates and over-budget recipes fail rather than being sampled or truncated.

Preparation requires an explicit existing .set, an existing installed EX5, registered unmodified datasets and a ready, connected read-only broker catalogue. It neither compiles nor selects Market Watch symbols. Grid keys are sorted; each value list keeps its given order. Candidate sets are fixed UTF-16LE scalars without optimization sweep flags. Original files are not rewritten. Source/binary/base-set/dataset identities and resolved settings participate in the immutable manifest SHA; creation time and state do not. Resume consumers verify originals and frozen snapshots before use.

Lab runs request model 4, account-currency P&L, local agents, no cloud/remote, shutdown and no automatic takeover. Deposit accepts finite positive fractional amounts without integer narrowing; recipe currency must match native config. Dataset times remain UTC observations; native windows remain tester-naive calendar days. CSV bytes are not claimed as Strategy Tester input.

New provenance preserves the exact post-launch-offset journal and reports window_evidence. Nominal native Period/launch headers and generic completion are not proof of the actual tested end. Without corroborated effective boundaries, effective_window_unverified blocks fitness, OOS aggregation and daily zero-fill. The repository currently has no captured native effective-boundary fixture; live acceptance must establish that evidence before a run is presented as window-verified.

research_experiment_start({experiment_id,retry_failed?:boolean}) (default false) starts/resumes only the frozen ID. Duplicate starts share the same durable trial; completed reports are adopted, not rerun. Failed/interrupted attempts require explicit retry and retain their original IDs; retries consume the same attempt budget. research_experiment_status({experiment_id}) reads bounded counts and exact active identities without launching work. research_experiment_pause({experiment_id}) serializes with SQL reservation: an already reserved native trial finishes normally; otherwise no next trial starts. It never kills a terminal.

Each symbol/timeframe trains every candidate per fold, freezes the winner before OOS and uses the last fold's train winner for final. Verified net/deposit ranks descending, native DD ascending, then candidate ID lexical. Technical failure or unknown evidence fails the experiment rather than silently discarding an inconvenient candidate. Valid minimum-trades/DD filter rejections remain recorded. Financial reconciliation includes entry commission and signed swap; a defensible monetary observation may retain signed costs while unknown native window boundaries still prohibit fitness.

research_experiment_report({experiment_id}) reads a consistent snapshot, returns a bounded summary and links a checksummed, immutable JSON artifact. It preserves every attempt/error and train-only decision, reports independent OOS periods separately from the held-out-within-experiment final, and reuses identical artifact bytes for identical inputs. Original/snapshot mutation or artifact tampering is an error, not a reason to regenerate historical evidence.

Cost sensitivity scales only signed commission/swap debits, preserves credits and applies extra account-currency cost per executed-side lot. It is arithmetic, not a native fill simulation. Execution-resolution realized cashflow drawdown is separate from native equity drawdown. Deterministic circular moving-block resampling uses verified tester-naive daily windows; fewer than two days or a block at least as long as the series is unavailable. Resampling is conditional, not a future probability of profit. DSR/PBO, annualization, portfolio equity, live execution and lookahead/multiple-testing assurances are not supplied.

The same verified signed totals power analyze_costs; legacy/pips/partial or unreconciled financial evidence returns null with a reason, not fake zeros.

Native acceptance is opt-in via tests/research_lab.py --live; it requires registered XAUUSD/EURUSD datasets, a ready demo bridge and a user-closed terminal before tester work. The bounded recipe allows at most eight native attempts, pauses/resumes exact identities and never kills a user terminal. Run python tests/research_lab.py --help for its required arguments. Contract-only success is not native acceptance. Do not replace an installed MCP silently; point the client at the verified release executable and reconnect explicitly.

Granular Analytics (individual analysis)

ToolDescription
analyze_monthly_pnlMonthly P/L breakdown only
analyze_drawdown_eventsDrawdown events and causes only
analyze_top_lossesWorst losing deals only
analyze_loss_sequencesConsecutive loss patterns only
analyze_position_pairsPosition hold time and P/L pairs
analyze_direction_biasBuy vs Sell performance
analyze_streaksWin/loss streak analysis
analyze_concurrent_peakPeak simultaneous positions

Use these for targeted analysis, or analyze_report to run all at once.

Deal-Level Analytics (New)

ToolDescription
list_dealsList individual deals with filters (type, profit range, volume, dates)
search_deals_by_commentFull-text search in deal comments (e.g., "Layer #3")
search_deals_by_magicFilter deals by EA magic number
analyze_profit_distributionProfit histogram: small/medium/large wins and losses
analyze_time_performancePerformance by hour of day and day of week
analyze_hold_time_distributionHold time buckets + correlation with profit
analyze_layer_performanceGrid/martingale layer analysis from comments
analyze_volume_vs_profitVolume correlation + performance by lot size
analyze_costsCommission and swap impact on profitability
analyze_efficiencyProfit per hour/day, annualized return, trade frequency

Monitoring

ToolDescription
verify_setupCheck native MT5 program/data paths and EA/set file inventory
get_optimization_statusCheck live state of a background optimization job
list_jobsAll optimization jobs with compact status in one call

Reports & logs

ToolDescription
list_reportsCompact table of all runs with key metrics — no full analysis needed
get_latest_reportGet most recent report with optional equity chart
search_reportsFind reports by EA, symbol, date range, or profit criteria
get_report_by_idGet specific report by ID with equity chart
get_reports_summaryAggregate stats: counts, averages, pass rates
get_best_reportsTop N reports sorted by any metric (profit factor, drawdown, etc.)
search_reports_by_tagsFind reports by tags
search_reports_by_date_rangeQuery by backtest date range
search_reports_by_notesFull-text search in report notes
get_reports_by_set_fileFind all reports using a specific .set file
get_comparable_reportsFind comparable reports (same EA/symbol/timeframe)
tail_logRead last N lines of any log; filter=errors to see only failures
prune_reportsDelete old report directories, keep last N (skips _opt dirs)
promote_to_baselineWrite a history entry or report to baseline.json for compare_baseline

History & baseline

ToolDescription
archive_reportConvert one report dir → compact JSON entry in backtest_history.json, optionally delete source
archive_all_reportsBulk-archive all report dirs then optionally delete them; keeps N newest safe
get_historyQuery history with filters (EA, symbol, verdict, profit, DD) and sort options
annotate_historyAttach verdict / notes / tags to any history entry

Cache management

ToolDescription
cache_statusMT5 tester cache size breakdown by symbol — check before cleaning
clean_cacheDelete tester cache files; supports per-symbol and dry_run

Pre-flight & Validation

ToolDescription
get_active_accountGet current MT5 account session (login, server, available symbols)
check_symbol_data_statusValidate symbol has sufficient history data for date range
check_mt5_statusCheck if MT5 terminal is installed and ready
validate_ea_syntaxPre-compile syntax check without running full compilation

Debugging & Diagnostics (New)

ToolDescription
diagnose_wineLegacy compatibility tool; reports native-Windows runtime status on Windows
get_mt5_logsGet MT5 terminal, tester, or MetaEditor logs with filtering
search_mt5_errorsSearch logs for error patterns (crash, exception, access violation)
check_mt5_processCheck if MT5 processes are running, get PID, CPU, memory usage
kill_mt5_processRefuses managed-instance mutation or unmanaged PID-only termination; close interactive terminals manually
check_system_resourcesCheck disk space, memory, CPU availability
validate_mt5_configValidate terminal.ini and tester configuration files
get_wine_prefix_infoLegacy compatibility tool; returns MT5 data-folder information on Windows
get_backtest_crash_infoInvestigate backtest failures: incomplete markers, missing deals.csv, errors
check_updateCheck if a newer version of MT5-MCP-Quant is available
updateUpdate MT5-MCP-Quant to latest release

Project Management

ToolDescription
init_projectScaffold new MQL5 project with templates (scalper/swing/grid/basic)
create_set_templateGenerate .set parameter file from EA input variables
export_reportExport backtest report to CSV, JSON, or Markdown

History & Comparison

ToolDescription
get_backtest_historyList all backtests for EA/symbol with summary metrics
compare_backtestsCompare 2+ backtest results side-by-side with analysis

.set file — read / write

ToolDescription
list_set_filesAll .set files in tester profiles dir with sweep stats and combination counts
read_set_fileParse UTF-16LE .set file → structured JSON params
write_set_fileWrite params → UTF-16LE .set with the Windows read-only attribute
patch_set_fileUpdate specific params in-place, return diff — replaces read→edit→write
clone_set_fileCopy .set to new path with optional overrides in one call

.set file — analysis & generation

ToolDescription
describe_sweepSwept params, value counts, and total optimization combinations
diff_set_filesSide-by-side diff of two .set files — only changed params returned
set_from_optimizationGenerate a clean backtest .set from get_optimization_results params; optionally narrow sweep

Search & Discovery

ToolDescription
search_expertsSearch EAs by name pattern across all directories
search_indicatorsSearch indicators by name pattern
search_scriptsSearch scripts by name pattern
copy_indicator_to_projectCopy indicator to project directory
copy_script_to_projectCopy script to project directory

Full schema: docs/MCP_TOOLS.md

Troubleshooting

Run verify_setup from your LLM first — it checks all paths and returns actionable hints.

For crashes or unexplained failures during backtest/compile/optimization:

  • check_mt5_status — Check native terminal, MetaEditor, tester, and data paths
  • search_mt5_errors — Find crash causes in logs
  • check_mt5_process — Inspect processes; close unmanaged interactive terminals manually
  • get_backtest_crash_info — Investigate failed backtest reports

Full Troubleshooting Guide →


Acknowledgements

MT5-MCP-Quant stands on the shoulders of exceptional open-source projects:

  • Rust — The language that makes zero-cost abstractions, memory safety, and fearless concurrency practical
  • Tokio — The async runtime powering all concurrent operations
  • Windows — Native process execution and filesystem integration for MetaTrader 5
  • MetaTrader 5 — MetaQuotes' trading platform (trademark of MetaQuotes Software Corp.)
  • rusqlite — Ergonomic SQLite bindings for Rust
  • serde — The serialization framework making config and report handling painless
  • scraper — HTML parsing for MT5 report extraction
  • tempfile — Secure temporary file handling

Special thanks to the Model Context Protocol (MCP) team at Anthropic for defining the standard that makes AI-powered development workflows possible.

Disclaimer

Not Financial Advice. MT5-MCP-Quant is a development and analysis tool for algorithmic trading strategies. It does not provide investment advice, trading recommendations, or guarantee profitability. All backtest results are historical simulations and do not guarantee future performance.

Use at Your Own Risk. Trading financial instruments carries substantial risk of loss. The authors and contributors of MT5-MCP-Quant accept no liability for:

  • Trading losses incurred using strategies developed or tested with this tool
  • Data loss or corruption from backtest operations
  • Bugs, errors, or incorrect analysis results
  • System crashes, native MT5 process failures, or broker/runtime incompatibilities

Software Warranty. This software is provided "as-is" without warranty of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement. See LICENSE for full terms.

Third-Party Software. MT5-MCP-Quant interacts with MetaTrader 5 and other third-party software. Users are responsible for complying with all applicable licenses and terms of service. MetaTrader is a trademark of MetaQuotes Software Corp. MT5-MCP-Quant is not affiliated with, endorsed by, or sponsored by MetaQuotes.

Regulatory Compliance. Users are responsible for ensuring their trading activities comply with applicable financial regulations in their jurisdiction. Automated trading may be restricted or require licensing in some regions.

License

MIT License


Similar modules

Browse Computer control