How Backtesting Works: Step by Step
What happens inside a backtesting engine: replaying prices bar by bar or tick by tick, filling orders, charging costs and building the equity curve - and where simulations go wrong.
A backtest looks simple from the outside: press a button, get an equity curve. Inside, the engine is doing something very specific - replaying history one event at a time and pretending to be a broker. Knowing what it does, and what it has to guess, is the difference between a test you can trust and one that flatters you.
Step 1: load the price history
The engine loads historical prices for the symbol and period you chose. The resolution of that data decides how realistic the simulation can be:
- Tick data - every price change, with bid and ask. The most faithful replay, and the slowest.
- One-minute bars - open, high, low and close per minute. A good compromise for most strategies that decide on bar close.
- Higher-timeframe bars - fast, but the engine knows very little about what happened inside each bar.
When only bars are available, the engine reconstructs a path inside each bar (for example open → high → low → close, or open → low → high → close). That reconstructed path decides whether a stop or a take profit was hit first. If both levels sit inside the same bar, the answer is a guess.
Step 2: step through time
The engine moves forward event by event. At each step it:
- Updates the current price (and spread, if the data contains it).
- Lets the strategy react - in cTrader terms,
OnTick()on every price change orOnBar()when a new bar opens. - Processes the strategy’s requests: market orders, pending orders, modifications, closes.
- Checks every open position against its stop loss and take profit.
- Applies financing (swap) at rollover, if the simulation supports it.
- Records balance and equity.
The essential rule is that the strategy may only see the past. At the moment it decides, the current bar is still forming; using its final close would be looking into the future.
Step 3: fill orders like a broker
When the strategy sends a market order, the engine fills it at a simulated price:
- Buy at the ask, sell at the bid. With bar data that has no ask prices, the engine adds the spread you configured.
- Slippage - some engines add it, many do not. If yours does not, the results are optimistic for strategies that trade during fast moves.
- Pending orders fill when price touches the level. In reality, a stop order during a gap fills at the first available price, which can be far worse than the level.
Then costs are charged: commission per trade (often specified per million units traded), spread (already inside the fill prices), and swap for positions held overnight.
Step 4: account and risk bookkeeping
Each simulated trade updates the account:
- Balance changes when positions close.
- Equity changes with every price move while positions are open.
- Margin is reserved for open positions; if free margin runs out, a realistic engine triggers margin calls and stop-outs.
This is why equity drawdown is usually larger than balance drawdown: equity shows the floating losses that the balance only books when trades close.
Step 5: the report
At the end, the engine produces:
- the list of trades with entry, exit, size, profit and duration;
- the equity and balance curves;
- statistics such as net profit, profit factor, maximum drawdown, number of trades, win rate, largest win and loss, average trade;
- a log of everything the strategy printed or every error it hit.
The report is only as honest as the four steps before it.
Where simulations go wrong
| Weak point | What happens | How to guard against it |
|---|---|---|
| Intrabar ambiguity | Stop and target inside one bar; engine picks the lucky order | Use tick data for tight stops; prefer bar-close logic |
| Missing spread history | Fixed spread hides costly news and rollover spikes | Use tick data with real spreads, or test with a higher spread |
| No slippage | Breakouts and stops fill at perfect prices | Add a slippage allowance or test sensitivity to it |
| Look-ahead | Indicator values from the future leak in | Act on closed bars; recheck indicator calculations |
| Gaps and weekends | Stops filled at the level instead of the gap price | Check trades around weekend opens and news |
| Data errors | Spikes and holes create fake trades | Inspect the data before trusting the test |
Bar logic vs tick logic: a practical choice
Many strategies only need one decision per bar. Writing them to act on bar close has three advantages: backtests are faster, results barely change between tick and one-minute data, and live behaviour matches the test because the bot is not reacting to every flicker. Run a tick-data test at the end anyway: if the result changes a lot, the strategy depends on details that bars hide.
Visual mode: watch before you trust
Most platforms, cTrader included, can play a backtest visually on the chart. Watching even fifty trades is the fastest way to catch logic errors: entries on the wrong bar, stops placed on the wrong side, positions that never close. Statistics hide these problems; the chart shows them.
Key takeaways
- A backtester replays history event by event and imitates a broker’s fills and costs.
- Data resolution decides how much the engine has to guess.
- The strategy must only ever see the past; look-ahead is the most expensive bug.
- Check the weak points - intrabar order, spread, slippage, gaps - before believing a result.
Next: how to collect quality historical data and the metrics in the report.
FAQ
Why do tick and bar backtests give different results?
With bars, the engine only knows four prices per bar (open, high, low, close) and has to guess the path between them. With ticks it sees every price change and the real spread. Strategies with tight stops, intrabar exits or tick-based logic can change a lot between the two.
What is look-ahead bias?
Using information in a decision that was not available at that moment, for example deciding at the open of a bar using that bar's close. It makes results look better than anything you could trade.
Should my strategy run on every tick or on bar close?
Most swing and intraday systems only need to decide when a bar closes. That makes backtests faster, more stable between data types and closer to live behaviour. Tick logic is for strategies that genuinely need it, such as tight trailing stops or scalping.
Sources and further reading
- cTrader Help: Backtest a cBot - help.ctrader.com
- cTrader Help: cBot lifecycle (OnStart, OnTick, OnBar, OnStop) - help.ctrader.com