My account

Forex Basics · 12 min read

How to Backtest a Trading Strategy In 2026

Learn how to backtest a trading strategy step by step, from writing rules and choosing data to reading results, avoiding overfitting and moving to live trading.

On this page17 sections
  1. 01What is backtesting?
  2. 02Why backtest your trading strategies?
  3. 03Backtesting a trading strategy step by step
  4. 04Step 1: Write the strategy rules precisely
  5. 05Step 2: Choose the market, timeframe and test period
  6. 06Step 3: Get reliable historical data
  7. 07Step 4: Split the data into in-sample and out-of-sample periods
  8. 08Step 5: Set realistic trading costs
  9. 09Step 6: Run the backtest
  10. 10Step 7: Analyse the results
  11. 11Step 8: Validate before trading live
  12. 12Backtesting stocks, indices, commodities and forex
  13. 13How to evaluate risk in a backtest
  14. 14Backtesting checklist
  15. 15Common backtesting mistakes
  16. 16Frequently asked questions
  17. 17Next step

To backtest a trading strategy, you write its rules down precisely, apply them to historical price data, either by hand or with software such as the MetaTrader Strategy Tester, record every trade the rules would have taken, and then judge the results on profit, drawdown and consistency, including realistic costs. A good backtest also holds back part of the data to check the strategy on prices it was not tuned on, because a result that only works on the period it was built from tells you very little about the future.

The steps below work for discretionary and automated strategies alike, with extra detail for Expert Advisors in MetaTrader, since that is where most automated forex strategies are tested, and notes on how the process changes for shares, indices and commodities.

What is backtesting?

In simple terms, backtesting is the process of applying a fixed set of trading rules to historical data to see how those rules would have performed, trade by trade, had they been followed in the past. It turns an idea into a measurable record, showing how often the strategy would have traded, how much it would have won or lost after costs, and how deep its losing periods would have been, so that you can judge its potential performance before any money is at risk.

A backtest is an estimate rather than a forecast. Markets change, live fills differ from simulated ones, and every choice you make during testing, from the date range to the cost settings, affects the accuracy of the result. Treated with that in mind, a careful backtest is one of the most effective ways for traders to learn whether a strategy deserves further work or should be set aside.

Why backtest your trading strategies?

Traders backtest for three practical reasons. The first is evidence: a strategy that looks convincing on a few hand-picked charts often turns out to have no edge once every valid setup over several years is counted. The second is risk: a test reveals the drawdowns, losing streaks and recovery times the strategy produced, which tells you how much capital and patience it needs.

The third is confidence, because knowing that a strategy survived difficult periods in the past makes it easier to keep following the rules during a losing run, which is when many traders abandon a sound approach.

Backtesting a trading strategy step by step

Knowing how to backtest a trading strategy comes down to following the same sequence every time, so that each test is repeatable and comparable with the last:

StepWhat to doWhy it matters
1. Define the rulesWrite entry, exit, stop, size and filters preciselyVague rules produce unrepeatable tests
2. Choose market and timeframePick the symbol and chart you will tradeResults rarely transfer across markets
3. Get reliable dataUse clean history, ideally from your brokerBad data produces misleading results
4. Split the dataReserve an out-of-sample periodChecks the strategy on unseen prices
5. Set realistic costsInclude spread, commission, swap and slippageCosts decide many strategies’ viability
6. Run the testManually or in the Strategy TesterProduces the trade list and statistics
7. Analyse resultsReview profit factor, drawdown, trade countShows whether an edge exists and its risk
8. Validate forwardOut-of-sample test, then demo tradingConfirms behaviour beyond the test period

Step 1: Write the strategy rules precisely

Every decision the strategy makes should be written down before testing begins: what triggers an entry, where the stop loss goes, how the trade exits, how much is risked, and which conditions block a trade, such as sessions, spreads or news. 

If two people following the rules could reach different decisions on the same chart, the rules are not yet precise enough to test.

Precision matters even more for automated testing, since the code can only do what the rules state. A phrase such as “enter after a pullback” has to become something measurable, such as “enter when price closes above the 20-period moving average after touching it within the previous five bars”.

Step 2: Choose the market, timeframe and test period

Test on the symbol and timeframe you intend to trade, because a strategy that works on EURUSD hourly charts may behave very differently on gold or on a five-minute chart. Choose a test period long enough to include different conditions, such as trending, ranging, calm and volatile phases, which usually means several years for intraday systems and longer for slower strategies.

Volatility deserves particular attention when choosing the period. A breakout strategy tested only during a calm year may look unprofitable, while the same rules tested only during a turbulent year may look exceptional, so the test should include both kinds of market and you should check how results differ between them.

Step 3: Get reliable historical data

Data quality shapes everything that follows. Gaps, bad ticks and inconsistent server times distort results, and data from one broker may differ from another’s, so test with history from the broker you plan to trade with where possible. In MetaTrader 5, the testing report includes a History Quality figure that rates the price data used, which is worth checking before trusting any result.

Survivorship bias in stocks and indices

Traders testing strategies on individual shares face a data problem that forex traders rarely meet: survivorship bias. A dataset built from the companies that are in an index today leaves out the firms that were removed, taken over or delisted during the test period, many of them because their share prices fell. 

A strategy tested only on survivors therefore trades a list of companies already known to have done well, which flatters the results. To avoid this, use historical index membership data that includes delisted stocks, or test on the index itself, through a CFD or futures contract, rather than on today’s constituents.

Commodities and futures bring their own data issue, because each contract expires and a continuous chart has to join successive contracts together. The method used to adjust prices at each roll can change indicator values and test results, so check how your data provider builds continuous series before relying on them.

Step 4: Split the data into in-sample and out-of-sample periods

Use one part of the history to develop and tune the strategy, and hold back another part that you never use for tuning. Once the rules and settings are fixed, run them on the held-back period: if results remain reasonable, the strategy has passed a first test of robustness, whereas a sharp collapse suggests the settings fitted noise in the development period.

The MT5 Strategy Tester includes a Forward setting that reserves the last half, third, quarter or a custom share of the date range for checking selected inputs on unseen data, which automates this split for EA traders.

Step 5: Set realistic trading costs

Spread, commission, swap and slippage can turn a profitable test into a losing live strategy, particularly for systems that trade often or target small moves. Set the spread to a realistic value rather than the tightest possible one, add commission per lot if your account charges it, and consider a stress test with costs pushed higher to see how much margin the strategy has.

Step 6: Run the backtest

Manual backtesting

For discretionary strategies, scroll a chart forward bar by bar with future prices hidden, using a replay tool such as TradingView’s Bar Replay or the visual mode in the MetaTrader Strategy Tester, and record each trade the rules trigger in a spreadsheet: date, direction, entry, stop, target, exit, result and a short note. Decide the sample size or date range in advance and keep going until you reach it, logging every valid setup rather than only the ones that look attractive.

Automated backtesting in MetaTrader 5

  • Open the Strategy Tester and select the Expert Advisor, symbol, timeframe and date range.
  • Choose a modelling mode: the MT5 help lists “Every tick”, “Every tick based on real ticks”, “1 minute OHLC”, “Open prices only” and “Math calculations”.
  • Set the initial deposit, leverage and the EA’s inputs, and enable the Forward setting if you want an out-of-sample check.
  • Run the test, then review the report, graph and trade list.

Use “Every tick based on real ticks” for strategies sensitive to intrabar movement, such as those with tight stops, and faster modes only for systems that act on bar opens. Even real-tick modelling does not reproduce live fills exactly, so treat the result as an estimate.

Manual or automated: which should you use?

Manual backtestingAutomated backtesting
Suits discretionary rulesSuits precisely coded rules
Slower, smaller samplesTests large datasets quickly
No programming requiredNeeds an EA or suitable testing software
Risk of subjective trade selectionRisk of coding or modelling errors

Many traders use both: a manual pass to sharpen the rules, then an automated test for scale, as covered in our guide to manual vs automated backtesting.

Example: backtesting a moving average strategy

Consider a simple EURUSD strategy on the one-hour chart, used here to illustrate the process rather than as evidence that it works:

  • Buy when the 20-period moving average crosses above the 50-period average at a candle close, and sell on the opposite cross.
  • Exit on the opposite crossover, risking no more than 1% of the account per trade.
  • Include spread, commission and an allowance for slippage.
  • Test on several years of data, reserving the most recent 25% for out-of-sample validation.

Record the total trades, net profit, profit factor and maximum equity drawdown for both periods. If the strategy performs well during development but poorly on the untouched validation period, its historical profitability is unlikely to be robust, and the honest conclusion is to refine or discard it rather than adjust settings until the validation period also looks good.

Step 7: Analyse the results

MetricWhat it tells youWhat to look for
Total tradesSample sizeEnough trades to judge; a few dozen rarely says much
Net profitOverall result after costsPositive, but read alongside risk
Profit factorGross profit divided by absolute gross lossAbove 1; very high values may signal overfitting
Maximum drawdownLargest peak-to-trough fallA level you could tolerate live, in balance and equity terms
Expected payoffAverage result per tradeLarge enough to survive costs and slippage
Equity curveHow results built over timeSteady growth rather than a few large jumps

The calculations behind these metrics are simple, as the hypothetical figures below show:

MetricHypothetical calculation
Win rate60 winning trades out of 100 = 60%
Profit factor6,000 gross profit ÷ 4,000 gross loss = 1.5
Expected payoff2,000 net profit ÷ 100 trades = 20 per trade
Maximum drawdownAccount falls from a 10,000 peak to 8,000 = 20%

The MT5 testing report shows balance and equity drawdown separately, in absolute, maximal and relative forms. Equity drawdown includes losses on open positions, so it gives a fuller picture of the risk the strategy carried than balance figures alone.

Look beyond the headline profit. Check whether results depend on a handful of trades, whether some years lose money, and how long the strategy spent below a previous peak, since a long recovery period is hard to sit through in live trading.

Step 8: Validate before trading live

A strong in-sample result is the start of the process, not the end. Run the fixed rules on the out-of-sample period, test nearby input values to check that results do not depend on one precise setting, and then forward test on a demo account in real time. Only after the live demo results look broadly consistent with the backtest should you move to a live account, starting with reduced size.

Once live, keep comparing the live record with the backtest over matching periods, looking at trade frequency, holding time, costs and drawdown. A tool that lines up a Strategy Tester report against live trades helps here; Account Tracker, which is made by Algo Trading Space, includes a Backtest Comparison tab on its Pro plan for this purpose.

Backtesting stocks, indices, commodities and forex

The method stays the same across markets, but the details that most often distort results change from one to the next:

MarketMain data and cost issuesWhat to check
ForexSpreads that widen at rollover and around news; broker-specific server timesRealistic spreads, swap charges and history from your own broker
StocksMissing delisted companies, dividends and share splits; limited trading hours and overnight gapsAdjusted prices and a dataset that includes delisted shares
IndicesGaps between sessions and different contract specifications between brokersContract size, trading hours and how gaps affect stops
CommoditiesContract rolls on futures, seasonal behaviour and sharp volatility on supply newsHow continuous data is built and how costs change through the year

A strategy that performs well on one market should be tested separately on any other before trading it there, since the volatility, costs and price behaviour that gave it an edge rarely carry across unchanged.

How to evaluate risk in a backtest

Profit attracts attention, but risk decides whether a strategy can be traded. Start with the maximum drawdown and ask whether you would keep trading through a loss of that size, then look at the longest losing streak and the longest period the equity curve spent below its previous high.

It also helps to estimate how bad things could become. Live drawdowns are frequently deeper than the worst one in a backtest, simply because the future contains sequences the past did not, so many traders size positions on the assumption that the next drawdown could be meaningfully larger than the tested maximum. Strategies that add to losing positions, such as grid or martingale systems, need particular care, because their backtests can show smooth equity curves right up until a single adverse move.

Backtesting checklist

Before trusting any result, run through this list and fix whatever is missing:

  • Entry, exit, position sizing and filter rules written so precisely that two people would take the same trades.
  • Historical data of known quality, covering several market regimes, with gaps and bad ticks checked.
  • An in-sample period for development and an untouched out-of-sample period for validation.
  • Spreads, commission, swaps and slippage set at realistic or slightly pessimistic levels.
  • Every qualifying trade logged, with no skipped or discretionary exceptions.
  • Maximum equity drawdown, profit factor, expectancy and trade count reviewed together rather than net profit alone.
  • Robustness checked by nudging key inputs and confirming the results do not collapse.
  • A period of demo or small-size forward testing compared against the backtest before committing full risk.

Common backtesting mistakes

  • Overfitting: tuning inputs until the historical curve looks perfect, which usually fails on new data.
  • Testing only survivors: testing shares only on companies that still exist today, which leaves out the failures.
  • Look-ahead bias: using information that was not available when the trade was taken, such as a bar’s close before it finished.
  • Ignoring costs: testing with zero or unrealistically tight spreads and no commission.
  • Too short a period: testing only one market regime, so the result reflects conditions rather than the strategy.
  • Cherry-picking: changing rules mid-test or skipping trades in a manual test.
  • Treating backtest drawdown as a ceiling: live drawdowns can be deeper than anything in the test.

Frequently asked questions

How long should a backtest period be?

Long enough to cover several market conditions. For intraday strategies that often means several years of data; for slower strategies, longer still. The aim is enough trades and enough variety to judge the strategy fairly.

How many trades do I need for a reliable backtest?

There is no fixed number, but more trades give more reliable statistics. Many traders look for at least a few hundred trades, and results based on a few dozen trades rarely say much about an edge.

Can I backtest without coding?

Yes. Manual backtesting with a chart replay tool needs no code, and ready-made Expert Advisors can be tested in the MetaTrader Strategy Tester without programming, provided the EA’s inputs match the strategy you want to test.

Is backtesting reliable?

Backtesting shows how rules would have performed on past data, which is useful evidence, but it cannot predict future results. Its reliability depends on data quality, realistic costs, sample size and whether the strategy was validated on data it was not tuned on.

What software can I use to backtest a trading strategy?

MetaTrader 4 and 5 include a Strategy Tester for Expert Advisors, and TradingView offers Bar Replay for manual testing alongside its own strategy testing tools. Other trading platforms and programming libraries can also run backtests; the right choice depends on the market you trade and whether your rules are coded or discretionary.

What is the difference between backtesting and forward testing?

Backtesting applies rules to historical data, while forward testing runs the strategy in real time, usually on a demo account, to see how it behaves on prices it has never seen.

Next step

Write your strategy’s rules on one page, choose a test period that covers several market conditions, and run a first test with realistic costs, holding back the most recent part of the data. If the strategy survives the out-of-sample check, move it to a demo account and compare its behaviour with the backtest before risking real money. Trading involves real risk, and past performance in a backtest does not guarantee future results.

Share this article

WhatsApp
Petko Aleksandrov

About the author

Petko Aleksandrov · Chief Mentor & Founder

Founder of EA Academy and Algo Trading Space with over 100,000 students educated globally. Petko combines practical trading experience with rigorous testing methodology, setting new standards for transparency in the algorithmic trading industry.

View profile →

Comments

No comments yet. Be the first to comment!

Leave a Comment

Your email address will not be published. Required fields are marked with *

Not sure where to start?

Most people start with our free robot

ATS Bootstrap EA is our own EURUSD robot for MetaTrader 5. It is free with an account and runs on up to 5 of your accounts. You can follow the same robot on our live account, month by month.

Looking for something else?

Trading with robots can lose money, and past results don’t guarantee future results.