mcp-mt5

v0.5.0
mcp-mt5 Checked 1 hour ago Published 2 months ago

MCP server for MetaTrader 4/5 build pipeline — compile, deploy, backtest, parse reports

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

env_info

Resolve and report MT4/5 paths, terminal hash, and missing-component issues.

list_terminals

Enumerate all MetaTrader terminal data folders under %APPDATA%\MetaQuotes\Terminal.

compile

Compile one MQL source with MetaEditor and return structured diagnostics. `ok` is true only when the log has a `Result:` line with 0 errors AND (unless `syntax_only`) a fresh .ex5/.ex4 was produced (`binary_fresh`). Fix every entry in `errors` (file, line, col, code, message) and call again; warnings do not block deployment. Takes 1-30 s. To also copy the binary into Experts/ use `compile_and_deploy`.

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
includeMQL root folder (parent of Include/) if different from the active terminal's.
log_fileExplicit path for the compile log; defaults to .mt5tmp/<stem>.compile.log next to the source.
syntax_onlybooleantrue = MetaEditor /s syntax check only: faster, produces no binary.
timeout_secintegerGive up after this many seconds.

run_backtest

Run a Strategy Tester backtest headlessly from a tester.ini and wait for it to finish. Requires the EA to be deployed first (`compile_and_deploy` / `deploy_ea`) and `ShutdownTerminal=1` in the ini, otherwise the call runs until `timeout_sec`. Typically 1-30 minutes; progress notifications are sent every few seconds while waiting. If the tester reports "cannot synchronize history" (first headless start after login), the run is retried once automatically. For long runs prefer `start_backtest` + `get_backtest`. Returns `run_id`, `report_path` (resolved from `Report=` in t…

ParameterTypeDescription
config *stringAbsolute path to the tester.ini file.
portablebooleanPass /portable so the terminal uses its install folder as data folder.
timeout_secintegerGive up (and kill the terminal) after this many seconds.
waitbooleantrue = block until the terminal exits (needs ShutdownTerminal=1); false = launch and return a run_id for get_backtest.

start_backtest

Launch a backtest in the background and return immediately with a `run_id`. Poll `get_backtest(run_id)` until `status` is no longer "running"; the final record carries `report_path` and `journal_notes`. Runs are also written to `.mt5tmp/runs/<run_id>.json` next to the ini. Only one terminal per install can test at a time.

ParameterTypeDescription
config *stringAbsolute path to the tester.ini file.
portablebooleanPass /portable so the terminal uses its install folder as data folder.
timeout_secintegerKill the terminal if it has not exited after this many seconds.

get_backtest

Status of a background backtest (running / completed / timeout / cancelled) with report path and journal notes when done; without run_id, lists all runs newest first.

ParameterTypeDescription
run_idIdentifier returned by start_backtest / run_backtest; omit to list every run of this server process.
tail_linesintegerWhile running, include this many trailing lines of the tester journal.

cancel_backtest

Kill the terminal of a running background backtest. No report is produced for a cancelled run.

ParameterTypeDescription
run_id *stringIdentifier returned by start_backtest / run_backtest.

kill_terminal

Force-kill terminal processes launched by this server (run_backtest / smoke_test). By default only PIDs this server started are killed, so a live-trading terminal on the same machine is never touched. Pass `all_instances=True` to `taskkill` every terminal64.exe/terminal.exe of the configured edition (destructive).

ParameterTypeDescription
all_instancesbooleanfalse = only terminals launched by this server; true = taskkill every terminal of this edition (may hit a live-trading terminal).

tail_log

Tail a MetaTrader log: the EA's LiveLog.txt, the daily Experts journal, or the latest tester journal. Use mode="tester" right after a backtest to see runtime errors and the effective test period.

ParameterTypeDescription
dateJournal date as YYYYMMDD; defaults to today.
linesintegerNumber of lines from the end of the file.
modestring"live" = MQL5/Files/LiveLog.txt written by the EA, "journal" = MQL5/Logs/YYYYMMDD.log (Experts tab), "terminal" = logs/YYYYMMDD.log (Journal tab: connection, tester start), "tester" = newest Tester/lo…
structuredbooleanParse journal lines into {ts, source, message} records (journal/tester modes).

list_experts

List compiled EAs in Experts/ (defaults to *.ex5 for MT5, *.ex4 for MT4).

ParameterTypeDescription
patternGlob pattern; defaults to *.ex5 on MT5 and *.ex4 on MT4.
recursebooleanInclude subfolders of Experts/.

read_tester_report

Parse a Strategy Tester HTML report (MT5 or MT4) into `summary` metrics; the full HTML stays behind `report_uri`. Prefer passing the `report_path` returned by `run_backtest`/`get_backtest`; without `path` the newest report on disk is used, which may belong to an older run. `summary` values are the strings printed in the report ("10 000.00", "359.61 (3.34%)"); use `compare_reports` / `regression_check` for numeric comparison. Read the `mt5://report/{id}` resource only when you need the original HTML.

ParameterTypeDescription
max_tradesintegerMax trade rows to return in `trades` when response_format="detailed".
pathAbsolute path to a report .htm; defaults to the newest report found on disk.
raw_truncateintegerCharacters of raw HTML to inline (0 = none; read report_uri instead).
response_formatstring"concise" = summary metrics + counts + report_uri; "detailed" adds the parsed trade rows.

patch_tester_ini

Set keys in a tester.ini in place, keeping the file's encoding and other lines. `updates` maps "Section.Key" to a value, e.g. {"Tester.Symbol": "EURUSD", "Tester.FromDate": "2025.01.01", "TesterInputs.RiskPct": "1.5"}. Missing sections/keys are added. Run `validate_tester_ini` afterwards; always set Deposit, Currency, Leverage, Model, Optimization, Visual, UseLocal/UseRemote/UseCloud and Report explicitly so a run does not inherit the machine's last UI state.

ParameterTypeDescription
config *stringAbsolute path to the tester.ini file.
updates *objectMapping of "Section.Key" to new value, e.g. {"Tester.Symbol": "EURUSD"}.

compile_and_deploy

Compile a source and, if it succeeds, copy the fresh binary into the terminal's Experts/ folder. Use this before `run_backtest` or `smoke_test`. Returns the `compile` result plus `deploy`; `ok` is false if either stage failed (compile errors are in `compile.errors`).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
ea_nameFile name for the binary inside Experts/; defaults to <stem>.ex5.

deploy

Copy a compiled EA into the terminal's Experts/ folder or a .mqh header into Include/, chosen by extension. Overwrites an existing file of the same name. Use `compile_and_deploy` to build and copy in one step.

ParameterTypeDescription
file *stringAbsolute path to a compiled .ex4/.ex5 (goes to Experts/) or a .mqh header (goes to Include/).
nameFile name to use in the target folder; defaults to the source file name.

inspect_source

Read-only facts about MQL source: `input` declarations, #include tree (with missing files), MetaEditor doc blocks, symbol usages, duplicate magic numbers. Replaces extract_inputs / resolve_includes / extract_doc / find_symbol / find_magic_collision.

ParameterTypeDescription
aspectsarrayWhich analyses to run; defaults to inputs, includes and docs for a source, plus symbol when `symbol` is given and magic when only `root` is given.
limitintegerMax symbol matches to return.
mql_rootMQL root used to resolve <angle> includes; defaults to the active terminal.
rootAbsolute project folder to scan (for symbol, magic); defaults to the source file folder.
sourceAbsolute path to one .mq4/.mq5/.mqh file (for inputs, includes, docs).
symbolIdentifier to grep for (whole word, comments and strings skipped); enables the "symbol" aspect.
var_patternstringSubstring identifying magic-number variables for the "magic" aspect.

analyze_mql

Static checks on MQL source without compiling: structural lint (missing OnInit/OnTick, unused inputs, hardcoded magic/symbol), MT4-style deprecated API calls with MT5 replacements, and size/nesting metrics. Replaces lint_basic / check_deprecated / code_metrics. Use `compile(syntax_only=true)` for real compiler diagnostics.

ParameterTypeDescription
checksarrayWhich checks to run; default all.
rootAbsolute folder to aggregate metrics over every MQL file (metrics check only).
sourceAbsolute path to one .mq4/.mq5/.mqh file.

read_optimization

Read an MT5 optimisation cache (.opt): header, optimised inputs, pass count and the top N passes by `criterion`. Ranking uses every pass in the cache. The best pass of a genetic run is a biased sample; prefer robust neighbourhoods over the single top row. Replaces parse_optimization / top_passes.

ParameterTypeDescription
criterionstringPass field to rank by: profit, profit_factor, expected_payoff, recovery_factor, sharpe_ratio, maxdrawdown, trades, custom_fitness.
descendingbooleantrue = highest first; use false for drawdown-style metrics.
expertExpert name (file stem) used to select the matching cache file.
pathAbsolute path to a Tester/cache/*.opt file; defaults to the newest cache matching expert/symbol/period.
periodTimeframe code such as M15, H1, D1.
symbolSymbol name as shown in Market Watch, e.g. EURUSD.
top_nintegerHow many best passes to return.

compare_reports

Diff two tester reports key by key (absolute and percent deltas), optionally checking guard thresholds. With `guards`, a profit-style metric below its threshold or a drawdown/loss metric above it is a violation. Accepting only improvements across many iterations is selection bias; treat guards as a sanity gate, not proof of robustness. Replaces regression_check.

ParameterTypeDescription
baseline *stringAbsolute path to the baseline tester report (.htm).
candidate *stringAbsolute path to the candidate tester report (.htm).
guardsOptional percent thresholds per summary key, e.g. {"net_profit": -5, "profit_factor": -10, "max_drawdown": 25}; when given, `violations` and `ok` are added.

gen_tester_inputs

Generate a `[TesterInputs]` block from EA inputs. If `write_to` points at a tester.ini, the block is appended/replaced in-place.

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
write_toOptional tester.ini path; when given the [TesterInputs] block is written into it.

validate_tester_ini

Sanity-check a tester.ini. If `source` given, cross-check inputs vs EA declarations.

ParameterTypeDescription
config *stringAbsolute path to the tester.ini file.
sourceOptional EA source; when given, [TesterInputs] keys are cross-checked against its input declarations.

format_mql

Format an MQL file with clang-format (MQL literals such as D'…' and `input group` lines are protected). Default is a dry run reporting whether the file would change; pass `write=true` to apply. Replaces format_check.

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
styleclang-format style string; defaults to an MQL-friendly LLVM-based profile.
writebooleanfalse = report/diff only (default); true = overwrite the file in its original encoding.

rename_symbol

Rename a symbol across MQL files (whole-word match). `dry_run=True` previews only.

ParameterTypeDescription
new *stringNew identifier.
old *stringIdentifier to rename (whole-word match).
root *stringAbsolute path to the project folder to scan recursively for MQL files.
dry_runbooleantrue = preview the change and write nothing; false = apply it to the files.

snapshot_sources

Freeze a copy of source files into a timestamped folder under `dest`.

ParameterTypeDescription
dest *stringAbsolute path to the folder that holds snapshots.
sources *arrayAbsolute paths of the source files to freeze.
labelFolder name for this snapshot; defaults to a timestamp.

list_snapshots

List all snapshot folders under `dest`.

ParameterTypeDescription
dest *stringAbsolute path to the folder that holds snapshots.

select_terminal

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.

ParameterTypeDescription
editionstring"mt5" or "mt4".
hash32-character terminal data folder name under %APPDATA%\\MetaQuotes\\Terminal.
installInstall folder containing terminal64.exe; its data folder is found by scanning origin.txt files.
originInstall path stored in the terminal's origin.txt, e.g. C:\\Program Files\\MetaTrader 5.

smoke_test

One-call health check for an EA: compile, deploy, run a 1-day headless backtest, scan the journal. Catches problems that compile cleanly but fail at runtime (OnInit errors, array out of range, divide by zero). `ok` is true only if every stage passes; `stage` tells where it stopped. Overwrites the EA of the same name in Experts/. Takes 1-10 minutes.

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
daysintegerLength of the backtest window in days (ends 2 days ago).
expert_nameName to use in Expert= of the generated ini; defaults to the binary's stem.
periodstringTimeframe code such as M15, H1, D1.
symbolstringSymbol name as shown in Market Watch, e.g. EURUSD.
timeout_secintegerGive up after this many seconds.

extract_function

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.

ParameterTypeDescription
line_end *integerLast line (1-based, inclusive) of the block to extract.
line_start *integerFirst line (1-based, inclusive) of the block to extract.
new_name *stringName of the new helper function.
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
dry_runbooleantrue = preview the change and write nothing; false = apply it to the files.
return_typestringReturn type of the helper, e.g. void or double.
target_fileOptional .mqh path to append the helper to; defaults to inserting above the enclosing function.

syntax_check

DEPRECATED (removed in 0.6.0): use compile(source, syntax_only=true).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
timeout_secintegerGive up after this many seconds.

deploy_ea

DEPRECATED (removed in 0.6.0): use deploy(file, name).

ParameterTypeDescription
source_ex *stringAbsolute path to the compiled .ex4/.ex5 binary.
nameFile name to use inside Experts/.

install_include

DEPRECATED (removed in 0.6.0): use deploy(file, name) with a .mqh file.

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
target_nameFile name to use inside Include/.

extract_inputs

DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["inputs"]).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.

resolve_includes

DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["includes"]).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
mql_rootMQL root for <angle> includes.

extract_doc

DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["docs"]).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.

find_symbol

DEPRECATED (removed in 0.6.0): use inspect_source(root=..., symbol=...).

ParameterTypeDescription
root *stringAbsolute path to the project folder to scan recursively.
symbol *stringIdentifier to search for.
extsFile extensions to search.
limitintegerStop after this many matches.

find_magic_collision

DEPRECATED (removed in 0.6.0): use inspect_source(root=..., aspects=["magic"]).

ParameterTypeDescription
root *stringAbsolute path to the project folder to scan recursively.
var_patternstringSubstring identifying magic-number variables.

lint_basic

DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["lint"]).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.

check_deprecated

DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["deprecated"]).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.

code_metrics

DEPRECATED (removed in 0.6.0): use analyze_mql(source or root, checks=["metrics"]).

ParameterTypeDescription
rootAbsolute folder to aggregate over.
sourceAbsolute path of one source file.

format_check

DEPRECATED (removed in 0.6.0): use format_mql(source) (dry run by default).

ParameterTypeDescription
source *stringAbsolute Windows path to the .mq4/.mq5/.mqh source file.
styleclang-format style string.

parse_optimization

DEPRECATED (removed in 0.6.0): use read_optimization(...).

ParameterTypeDescription
expertExpert name to select the cache.
pathAbsolute path to a .opt cache.
periodTimeframe to select the cache.
sampleintegerPasses to include in passes_sample.
symbolSymbol to select the cache.

top_passes

DEPRECATED (removed in 0.6.0): use read_optimization(criterion=..., top_n=...).

ParameterTypeDescription
criterionstringPass field to rank by.
descendingbooleantrue = highest first.
expertExpert name to select the cache.
nintegerHow many passes to return.
opt_pathAbsolute path to a .opt cache.
periodTimeframe to select the cache.
symbolSymbol to select the cache.

regression_check

DEPRECATED (removed in 0.6.0): use compare_reports(baseline, candidate, guards=...).

ParameterTypeDescription
baseline *stringAbsolute path to the baseline report.
candidate *stringAbsolute path to the candidate report.
guardsPercent thresholds per summary key.

list_backtests

DEPRECATED (removed in 0.6.0): use get_backtest() without run_id.