Skip to main content

backtest-analysis

Backtesting methodology and performance analysis for MQL5 EAs. Use for: interpreting backtest metrics (Profit Factor, Sharpe, Calmar, Max DD, Recovery Factor); overfitting and curve-fitting detection; walk-forward testing protocol; custom OnTester() optimisation criteria; Monte Carlo simulation framework; MT5 Strategy Tester configuration (tick modes, modelling, spreads, deposits); tester journal patterns; optimisation frames API; full ENUM_STATISTICS reference. Trigger: "backtest", "optimise", "walk-forward", "Monte Carlo", "Profit Factor", "Sharpe Ratio", "overfitting", "curve fitting", "out of sample", "strategy tester", "optimisation criteria", "is this EA prop firm ready", "robustness", "OnTester", "TesterStatistics".

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install metatrader-backtest-analysis
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/metatrader-backtest-analysis/SKILL.md

Setup guide →
0Save

Instructions

Backtest Analysis

Backtesting is hypothesis testing, not validation. Test correctly, interpret
honestly, and avoid the traps that fool most traders.


Purpose

Methodology and interpretation reference for MetaTrader strategy testing —
scoring backtest reports, detecting overfitting, designing walk-forward and
Monte Carlo validation, configuring the MT5 Strategy Tester, and writing
custom optimisation criteria.


When to Use

  • Evaluating whether an EA is ready for funded account trading
  • Deciding if a backtest result represents real edge or curve-fitting
  • Running optimisation in MT5 and needing a better criterion than raw balance
  • Designing a validation pipeline
  • Looking up a specific STAT_* constant or tester configuration option

Do NOT use for:

  • Writing EA entry/exit logic → use signal-engine
  • Post-entry trade management → use trade-manager
  • Performance analytics in Python/pandas → use analytics

Core Guidance

Performance Metric Scorecard

Score any backtest report against this table before drawing conclusions.

Metric               Fail      Acceptable   Good       Excellent
Profit Factor (PF)   <1.2      1.2-1.4      1.4-1.7    >1.7
Win Rate (WR)        <35%      35-45%       45-55%     >55%
Sharpe Ratio         <0.5      0.5-0.9      0.9-1.5    >1.5
Calmar Ratio         <0.5      0.5-1.0      1.0-2.0    >2.0
Max Drawdown         >20%      15-20%       10-15%     <10%
Recovery Factor      <1.0      1.0-2.0      2.0-4.0    >4.0
Expected Payoff      <0        0-5          5-15       >15
Total Trades (3yr)   <100      100-200      200-500    >500
Consecutive Losses   >10       8-10         5-7        <5

The 3 metrics that matter most:

  1. Profit Factor — PF 1.4+ means earning $1.40 per $1 lost. Under 1.2 is not viable.
  2. Max Drawdown — must stay inside the firm's hard limit at every point during the test, not just the final figure.
  3. Recovery Factor — net profit / max DD. Shows recovery efficiency. Target 2.0+ for funded accounts.

Overfitting Detection Checklist

Red flags:

  • Backtest PF >3.0 but forward test PF <1.2
  • Only one narrow parameter range works (sharp peak on optimisation map)
  • Performance collapses outside the tested date range
  • WR >70% with very tight SL
  • <200 trades in a 3-year test period
  • Strategy only works on one specific tick feed
  • Results change dramatically with 1-pip spread increase
  • All profits from a 2-week period

Green flags:

  • Stable PF across broad parameter ranges (flat optimisation map)
  • Out-of-sample last 12 months show similar metrics to in-sample
  • Walk-forward efficiency >70%
  • Monte Carlo 95th percentile drawdown < firm limit
  • Works on multiple similar symbols with similar parameters
  • Performance consistent across different market regimes
  • PF is similar for buy-only and sell-only independently

Walk-Forward Testing Protocol

Total data:      5 years minimum (e.g. 2019-2024)
In-sample (IS):  First 3 years — optimise parameters here
Out-of-sample:   Next 1 year — validate only, do not touch
Forward test:    Final year — treated as live proxy

WF Efficiency = Average OOS PF / Average IS PF
  > 0.85  = Excellent
  0.70-0.85 = Acceptable
  0.50-0.70 = Marginal — likely overfit
  < 0.50  = Reject

Monte Carlo Simulation Framework

Run 1,000 simulations before live deployment:

  1. Sequence shuffle — randomly reorder trades
  2. Trade skip — randomly skip 10% of trades (missed signals)
  3. Result noise — adjust each trade result by +/-20% (slippage)
Required outputs:
  95th percentile Max DD   -> must be < firm limit
  5th percentile Net Profit -> must still be positive
  Probability of ruin       -> P(DD > hard limit) must be < 5%

Tools:
  MT5 built-in Monte Carlo (optimisation results tab)
  Quant Analyzer (standalone)
  Manual: export trades to CSV, run in Python/Excel

Code Patterns

Custom Optimisation Criterion (OnTester)

double OnTester() {
   double pf             = TesterStatistics(STAT_PROFIT_FACTOR);
   double maxDD          = TesterStatistics(STAT_EQUITY_DD);
   double netProfit      = TesterStatistics(STAT_PROFIT);
   double totalTrades    = TesterStatistics(STAT_TRADES);
   double sharpe         = TesterStatistics(STAT_SHARPE_RATIO);
   double recoveryFactor = TesterStatistics(STAT_RECOVERY_FACTOR);
   double balance        = TesterStatistics(STAT_INITIAL_DEPOSIT)
                         + TesterStatistics(STAT_PROFIT);

   if(totalTrades < 100)   return 0;
   if(pf < 1.1)            return 0;
   if(netProfit <= 0)      return 0;
   if(maxDD > balance * 0.08) return 0;  // exceed configurable DD limit

   double ddPenalty = 1.0 - (maxDD / (balance * 0.08));
   double score     = pf * recoveryFactor * sharpe * ddPenalty;
   double tradeBonus = MathMin(totalTrades / 500.0, 1.0);
   return score * (0.8 + 0.2 * tradeBonus);
}

Common Mistakes

  • Running "Open Prices Only" and missing intrabar SL hits
  • Not including commission — always include $5-8/lot round-trip
  • Testing on a single year with one market regime
  • Accepting the first optimisation pass without OOS validation
  • Using ACCOUNT_BALANCE for DD limits instead of equity
  • Full Kelly instead of half-Kelly
  • Not resetting daily drawdown limits on a new trading day

References

FileContentsRead when
references/tester-configuration.mdTick generation modes, execution delay, forward period, spread/deposit/leverage config, common mistakesSetting up a Strategy Tester run; choosing tick mode
references/metric-definitions.mdDrawdown types (balance vs equity DD, absolute/maximal/relative), Profit Factor, Recovery Factor, Sharpe, History QualityInterpreting the Results tab; understanding MT5 metric calculations
references/historical-data.mdPre-start buffer requirements per timeframe, start date shift journal message, tick/history storage paths, multi-currency setupFixing "start time changed" warnings; preparing data for a test
references/optimization-modes.mdSlow/Genetic/All Symbols types, genetic algorithm internals, optimisation criteria (Balance/PF/DD/Sharpe/Custom/Complex), forward behaviourChoosing optimisation method; selecting the right criterion
references/tick-generation.mdEvery Tick algorithm, Open Prices Only limits, Real Ticks specifics, exchange instrument order triggering, spread handlingUnderstanding tick modelling accuracy; debugging tick-related anomalies
references/tester-journal-agents.mdJournal message patterns, local/remote/cloud agent architecture, agent limitations, global variables during testsInterpreting tester journal output; configuring remote/cloud agents
references/optimization-frames-api.mdFrameAdd/FrameNext/FrameFilter, ParameterSetRange, controller pattern, MQL5 Cloud limits, full function referencePassing custom data from test agents to controller; dynamic parameter ranges
references/enum-statistics.mdFull ENUM_STATISTICS table — all STAT_* constants with types and descriptionsLooking up TesterStatistics() constants for OnTester() or frame output
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
market-regimeMarket regime detection and filtering for MQL5 EAs. Use for all logic that determines WHETHER to trade: trend vs range classification via ADX; volatility regime via ATR (high/normal/reduced); session filtering (London/NY/Asian killzones); news event avoidance; spread spike detection; weekend and holiday blocking. This is Layer 2 — signals are never generated without passing through regime first. Trigger: "market regime", "trending vs ranging", "session filter", "news filter", "volatility filter", "spread filter", "when to trade", "ATR regime", "ADX trend strength", "killzone", "dead zone", "regime detection", "Layer 2".0 installsstdlib-utilitiesMQL4/MQL5 language and runtime utilities reference skill. Use for: magic number isolation; OrderSend retry logic; .set file parameter presets; MQL4 vs MQL5 differences; file I/O and sandbox rules; string manipulation; array operations; date/time functions; terminal global variables; SQLite database access; runtime error codes; type conversion; matrix/vector stubs. Trigger: "magic number", "OrderSend retry", ".set file", "MQL4 vs MQL5", "file I/O", "string functions", "array functions", "date and time", "global variables", "database", "type conversion", "runtime error", "MqlDateTime", "terminal global".0 installspythonMetaTrader 5 Python package (MetaTrader5 module) integration. Use for: connecting Python code to a local MT5 terminal; initialising and shutting down sessions; reading account, terminal, symbol, tick, rate, order, position, and deal data; calculating margin or profit; validating and sending trade requests; building pandas-based MT5 data workflows; converting MT5 responses into DataFrame-friendly structures. Trigger: "MetaTrader5", "MT5 Python", "python mt5", "initialize MT5", "mt5 login", "mt5 order_send", "mt5 copy_rates", "mt5 account info", "pandas mt5", "mt5 symbol select".0 installstrade-managerPost-entry trade lifecycle management for MQL5 EAs. Use for: ATR-based, swing-based, and chandelier trailing stops; breakeven logic; partial close and scale-out strategies; multi-target take profit; position scaling (pyramiding); trade modification via CTrade; managing multiple open positions; OrderSend/OrderSendAsync retcode handling; position, order, and history iteration APIs; pre-trade margin and profit calculation; standard-library trade wrapper classes (CTrade, CPositionInfo, COrderInfo, CDealInfo, CSymbolInfo, CAccountInfo). Trigger: "trailing stop", "breakeven", "partial close", "scale out", "pyramiding", "take profit", "manage positions", "move SL", "CTrade", "position management", "trade modification", "multi-target TP", "trail", "BE", "OrderSend", "OrderCheck".0 installssignal-engineEntry and exit signal generation for MQL5 EAs. Use for: STradeSignal contract design; signal generation flow with confluence scoring (min 2 factors); SMC/ICT concepts (Order Blocks, Fair Value Gaps, CHoCH, BoS, liquidity sweeps); multi-timeframe analysis; technical indicator handles (ATR, EMA, RSI, ADX, MACD, Bollinger); candlestick pattern detection; breakout and mean reversion entries; multi-asset signal profiles; MQL5 Signals subscription API. Every signal requires minimum 2 confluence factors. Pair with market-regime to gate signals by market state. Trigger: "entry logic", "signal", "Order Block", "FVG", "CHoCH", "SMC", "ICT", "buy signal", "sell signal", "confluence", "indicator", "pattern", "liquidity sweep", "signal engine".0 installsimported-backtestHandles importing MT5 Strategy Tester HTML reports uploaded by users as first-class backtest results. Covers parsing via the canonical ReportParser, equity reconstruction from broker or Darwinex fallback price data, broker server resolution, and integrating imported results into comparison and analysis pipelines. Use for: uploading .htm reports from external MT5 sessions; reconstructing equity curves when no live terminal is available; making imported tests indistinguishable from native runs. Trigger on: "import backtest", "upload HTML report", "imported test", "import report".0 installs

More from MetaTrader Skills

View source →
multi-assetMulti-asset and multi-pair EA management for MQL5. Use for all logic involving trading more than one instrument: per-symbol configuration profiles (SSymbolConfig struct); 17 pre-built asset profiles across forex, metals, indices, and crypto CFDs; portfolio-level risk with correlation group limits; CMultiAssetManager class for position discovery, group counting, and total-risk enforcement; magic number assignment per symbol; multi-symbol OnTick architecture that processes each symbol independently. Trigger: "multi-pair", "portfolio EA", "multiple symbols", "all pairs", "forex and gold", "symbol manager", "asset class", "per-pair settings", "correlation management", "basket trading", "run on all symbols", "trade everything", "SymbolInfoInteger", "SymbolSelect".0 installsrisk-engineIndestructible risk management for MQL5 EAs. Use for: position sizing (fixed %, ATR-based, volatility-scaled, half-Kelly); daily and total drawdown guards; equity-stop implementation; configurable prop firm rule sets; consecutive loss tracking with auto-risk reduction; correlation-based exposure limits; and any "how do I protect the account" question. This module is always Layer 1 — the first gate before any trade. Trigger: "position size", "lot size", "drawdown", "risk", "prop firm", "daily loss limit", "max DD", "equity stop", "Kelly", "correlation risk", "exposure", "account protection", "halt trading".0 installsfintech-web-systemsElite TypeScript/React fintech and trading systems engineering skill. Use for ALL web-based trading infrastructure: decimal-safe money arithmetic, core trading metric implementations (Sharpe, Calmar, Drawdown, Profit Factor), real-time WebSocket market data feeds using Cloudflare Durable Objects, React hooks for live prices, trading dashboard UI components (PriceTicker, OrderBook), and OHLCV data ingestion pipelines. Precision is non-negotiable — never approximate money calculations. Trigger on: "trading dashboard", "live prices", "WebSocket feed", "order book", "price ticker", "OHLCV ingestion", "Sharpe Ratio TypeScript", "money arithmetic", "Decimal library", "profit factor", "fintech frontend". Note: For MQL5 EA implementations, use the mql5-* skills instead.0 installsplatformMetaTrader 5 platform operations reference skill. Use for: installing MT5 on Windows/macOS/Linux; configuring startup modes and CLI keys; managing SSL certificates and 2FA/TOTP; understanding file/folder layout; managing accounts and transfers; reading platform logs, Task Manager, and live update behaviour; keyboard shortcuts; chart analysis workspace and templates; trading UI, DOM, Market Watch, margin models; platform drawing objects; custom symbols; MQL5 chart operations API; MQL5 object API. For MQL5 constants, use the constants skill. For the Python module, use the python skill. For the HTTP bridge, use the httpapi skill.0 installsjournal-monitorParse MT5 terminal journal logs (JournalLog-*.log) and surface execution anomalies — connection drops, slow fills, slow SL/TP modifies, failed orders, and fast SL hits — across one or many broker accounts. Trigger this skill whenever the user asks to analyse, compare, or monitor MT5 journals; investigate broker execution quality; compare latency or drops across brokers; set up nightly journal monitoring or alerts; debug why an EA performed differently on different accounts; or uploads files named JournalLog-<account>-<date>.log. Also trigger when the user mentions MT5 journal logs, broker execution quality, connection drops, slow fills, or fast SL hits, even if they do not explicitly say "journal".0 installsea-architectMaster MQL5 Expert Advisor architecture reference. Use for: wiring the 5-layer EA model (risk, regime, signal, trade mgmt, analytics); writing OnInit/OnTick/OnDeinit event handlers; setting up IsNewBar gating; designing include file layouts and .mqh module interfaces; applying naming conventions across all EA files; reading symbol properties in a broker-agnostic way; and integrating CExpert/CExpertSignal/CExpertMoney standard-library classes. Trigger: "5-layer architecture", "module wiring", "OnInit", "OnTick", "IsNewBar", "include files", "mqh", "CExpert", "event handlers", "EA template", "naming conventions", "broker-agnostic", "symbol data access".0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about backtest-analysis

What does the backtest-analysis skill do?

Backtesting methodology and performance analysis for MQL5 EAs. Use for: interpreting backtest metrics (Profit Factor, Sharpe, Calmar, Max DD, Recovery Factor); overfitting and curve-fitting detection; walk-forward testing protocol; custom OnTester() optimisation criteria; Monte Carlo simulation framework; MT5 Strategy Tester configuration (tick modes, modelling, spreads, deposits); tester journal patterns; optimisation frames API; full ENUM_STATISTICS reference. Trigger: "backtest", "optimise", "walk-forward", "Monte Carlo", "Profit Factor", "Sharpe Ratio", "overfitting", "curve fitting", "out of sample", "strategy tester", "optimisation criteria", "is this EA prop firm ready", "robustness", "OnTester", "TesterStatistics". It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the backtest-analysis skill?

Run `npx @skills-hub-ai/cli install metatrader-backtest-analysis` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/metatrader-backtest-analysis/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does backtest-analysis work with?

backtest-analysis runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the backtest-analysis skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use backtest-analysis after installing it?

In Claude Code, type `/metatrader-backtest-analysis` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the backtest-analysis skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.