| Run an instrumented indicator in MT5, then replay **its logged signals** against broker price bars. | Compile and single-test an EA in MT5, inspect inputs, and run bounded complete or genetic optimization. |
| Inspect entries, exits and ambiguous bars in an HTML report. | Freeze candidates, check later dates, inspect trades on a chart, and optionally resample verified closed trades. |
The rate is in deposit currency **per charged side**: 3.5 on both sides means
7 per lot round trip. Choose `both`, `in` or `out`. Use your terminal's actual
server/account-mode filename and a native settings export inside MBT, not another
broker's margin settings. MBT freezes the template, preserves its account fields,
verifies profile application and checks actual detailed-report deal fees.
Original profiles and exact-prefix optimization caches are preserved/restored;
new caches are retained as run evidence. Price history and `.tst` caches are untouched.
Interrupted recovery blocks further launches until `restore_tester_commissions`
can safely restore the journalled state with MT5 closed. Cache isolation requires
same-filesystem renames and is bounded to 128 files/512 MiB with streaming hashing.
The fee contract is two-decimal cash reports, ordinary single-symbol entry/exit
deals, and fixed instant per-lot fees—not tiered/percentage/daily/monthly/minimum
fees or reversal/Close By histories. Zero-trade reports state that no fee events
were available. Custom commissions require native `forward_mode="off"`; use
independent holdout for paired out-of-sample checks.
`optimize_ea_symbols` runs up to 20 explicit symbols sequentially, with an HTML
comparison report and individual experiment links. Add `cutoff_date` to its
settings for paired holdout. `continue_symbol_optimization` resumes unfinished
markets/candidates. Winners are selected independently per market; this is not a
pooled portfolio or an all-Market-Watch scanner. Scheduling budgets do not impose
CPU/RAM ceilings; native local optimizer agents can still use available cores.
### Monte Carlo from verified trades
> "Shuffle the winner's out-of-sample trades 1,000 times, seed 42, and update the HTML."
> "Also bootstrap those trades to compare sampled profit and drawdown outcomes."
`run_monte_carlo` reads a frozen candidate's verified detailed report. The default
is the original in-sample winner's **holdout** period; choose `period="in_sample"`
explicitly for training-history diagnostics. Periods are never pooled or silently
substituted. It launches no MT5 tests and changes no strategy selection.
Each call returns a saved `analysis_id`. Use `get_monte_carlo_results(run_id,analysis_id)`
to inspect its verified statistics, chart data and assumptions in a later session
without rerunning it; `get_optimization_results` lists the run's analysis IDs.
| Method | What changes | What does not change |
| --- | --- | --- |
| `shuffle` | Order of whole closed trades; balance path and drawdown | Same trades/sizes/costs, so final net profit stays constant |
| `bootstrap` | Trades sampled with replacement; repetitions/omissions, terminal profit and drawdown | Historical recorded cash sizes/costs and number of sampled trades |
Entry fees and partial-exit cash events remain attached to their trade block.
At least five fully closed trades are required; small samples are prominently
flagged. Only unambiguous one-at-a-time single-symbol histories are supported;
overlapping/scale-in/reversal/Close By/open trades or account transfers are rejected.
Every deal's cash/costs must reconcile with balance and detailed-report totals.
Default: 1,000 paths, seed 42. Limits: 100..5,000 paths and at most 2 million
simulated deal events; lower the path count for longer histories. Execution uses
one local Python process, no MT5/GPU/cloud/worker pool, and retains bounded
statistics—not every simulated path. Saved source/analysis hashes are verified
again before the report displays charts.
These are **fixed recorded-cash diagnostics**, not reruns of percentage-risk or
loss-responsive money management. They assume exchangeable trades and do not
preserve market regimes/serial dependence. Synthetic balance bands are pointwise
percentiles, not historical equity or future confidence limits. Resampling does
not remove optimization bias, predict future profitability, or replace genuine
out-of-sample/other robustness checks. A zero-crossing fraction is not a modeled
> **Note:** reports are written to `reports/` on your machine. The tools return
> the local file path; open it in your browser. Automatic opening depends on
> the capabilities of your AI client.
See the [usage workflows](#use-it) for settings, selection, limits and examples.
EA optimization and Monte Carlo require native EA evidence; indicator-only input
sweeps are not implemented. The replay exit optimizer is a separate signal-replay
workflow, not native EA input optimization.
## MT5 directly versus MBT + an AI assistant
MBT is an orchestration/reporting layer, **not a replacement execution engine**.
EA backtests and optimization still run in MT5. This comparison separates native
capabilities from this integration's automation; it does not claim coverage of
every [native tester feature](https://www.metatrader5.com/en/terminal/help/algotrading/strategy_optimization).
The example prompts below are starting points for an MCP-compatible assistant,
not tool commands or guarantees of results. Identify your EA or saved run, and
provide the symbol, timeframe and dates when needed. Ask the assistant to clarify
missing settings rather than silently choosing them. For detailed settings and
limitations, see the [usage workflows](#use-it).
| Task | MT5 Strategy Tester directly | MBT + AI | Example AI prompt |
| --- | --- | --- | --- |
| Discover inputs | Inspect EA properties/dropdowns | Ask for supported inputs/defaults/named choices; source required | Inspect my EA's inputs. Explain their defaults, available choices and which can be optimized. Flag unsupported inputs. |
| Single backtest | Configure inputs and run the EA | Describe the settings; MBT runs the native tester | Propose a baseline backtest for my EA. Confirm the inputs, symbol, timeframe, dates, model and costs before running. |
| Fine-tune inputs | Set ranges/steps for exposed inputs | Describe numeric, boolean or supported enum grids in plain English | Propose a sensible initial grid for my EA. Explain Start, Step and Stop, which inputs to vary together or keep fixed, and the total combinations. Show the plan before running. |
| Complete/genetic search | Choose complete or genetic search and one of eight optimization criteria, such as Profit Factor max or Drawdown min | Pass the selected criterion to MT5; its saved Result ranks eligible passes, and guides genetic search | For this grid, recommend complete or genetic search. Explain the eight criteria, agree on one and a time budget, then report the actual passes and why the winner ranked first. |
| Out-of-sample check | Native Forward optimization | Frozen eligible shortlist plus separate IS/OOS single tests; native forward export availability depends on the terminal setup | Plan independent holdout testing with an explicit cutoff, MT5 criterion, minimum trades and replay budget. Confirm before running; do not select parameters using holdout results. |
| Candidate detail | Select/retest individual passes | Paired reports for completed candidates, resumable budgets and expandable chart details | Show this run's chosen candidates and completed in-sample/out-of-sample reports. State the criterion and winning Result; compare profit, drawdown and trade counts, flag missing periods and retain the original in-sample winner. |
| Account/execution | Broader native tester configuration | Deposit/currency/leverage/fixed delay; random delay for standalone optimization only | Plan a test with a 5,000 USD deposit, 1:30 leverage and fixed 100 ms delay. Show the effective settings and budget before running. |
| Custom commissions | Broader native commission options | Verified fixed instant per-lot fees per entry/exit side; cache isolation/restoration | Plan native commissions of 3.50 in deposit currency per lot per side. Check my matching native profile and export template, explain setup and restoration, and confirm before running. |
| Multiple markets | Market Scanner ("All symbols selected in Market Watch") tests the same fixed inputs across selected symbols; parameter optimization can be run separately per symbol. Multi-symbol EAs can also trade multiple instruments within one test. | Up to 20 explicit symbols sequentially, separate winners and comparison report, not a portfolio | Plan sequential EURUSD and GBPUSD tests with identical inputs and dates, separate winners and an HTML comparison. Show the total workload and budget before running. |
| Balance/equity | Native charts/statistics | Balance/deal-DD charts and opt-in measured equity for recorder-compatible EAs | Show this candidate's saved balance and deal-based drawdown charts. Check whether measured equity capture is supported; explain extra tests and sampling limits before running it. |
| Monte Carlo | Not a standard native optimization mode | Closed-trade shuffle/bootstrap with fixed recorded cash sizes/costs and explicit limitations | Check whether the original winner's holdout trades support shuffle and bootstrap. Explain the fixed-cash assumptions and workload for 1,000 simulations each, seed 42; confirm before running and update the HTML. |
| Inspect/share | Inspect tester tables, graphs, exports and recorded trades on MT5 charts | HTML reports with evidence links, chart tooltips and an Open trades in MT5 button; AI can open saved deals directly | Generate the HTML report from this saved run or market batch without new backtests. Show available candidate detail, then open its recorded trades on an MT5 chart. |
| Resume | Native optimization caches/saved results | Continue unfinished market/candidate batches without repeating completed evidence | Inspect this paused batch and list unfinished work. Propose a continuation budget before resuming; preserve completed results and do not silently retry failed tests. |
MBT does not expose visual debugging, all-Market-Watch scanning, remote/cloud
agents or every input/cost/equity configuration. Neither tool prevents overfitting
automatically. A sensible workflow is **define ranges → optimize in sample → freeze
candidates → inspect untouched later data**, with resampling as a limited extra
diagnostic, not a reason to select a new winner on holdout results.
## Development
Install pytest and run the automated tests from the repository root:
```bash
python -m pip install pytest
python -m pytest tests -q
```
Keep terminal configuration, credentials and generated reports out of version
control. Use `config.example.yaml` as a template for your own installation.
This toolkit was built live on [FX David](https://www.youtube.com/@fxdavid9392) — a series on building, verifying, and backtesting MT5 indicators with Claude AI.