Backtesting

Moving average crossover: how to backtest it honestly

How SMA and EMA crossovers work, why the 9/21 cross is easy to overfit, and how to backtest one on NIFTY options or MCX gold futures with fills and charges.

By
Veloce team
Published
Reading time
9 min read
On this page
  1. How the averages are calculated
  2. A crossover, candle by candle
  3. The built-in crossover option buyer
  4. Warm-up and overnight carry
  5. Whipsaws: where crossovers lose money
  6. Options add time decay
  7. Reading a crossover backtest
  8. SMA or EMA in the same test
  9. Choosing the lengths without fooling yourself
  10. The same crossover on MCX gold futures
  11. A checklist for an honest crossover test
  12. Try it in Veloce

A moving average crossover goes long when a fast average of closing prices crosses above a slow one and short (or flat) when it crosses back below. To backtest it honestly, act only on the candle close that completes the cross, fill at the next candle’s open, charge both sides of every flip, start counting only once the averages have enough candles, and choose the lengths on one period and confirm them on another. On NIFTY options there is one more effect to model: the option you buy loses time value while you wait for the trend. This guide works through a crossover candle by candle with Veloce’s own indicator code, then shows how to set up and sweep the test.

How the averages are calculated

Simple moving average (SMA). The average of the last n closes. A 9-period SMA on 3-minute candles is the average close of the last 27 minutes.

Exponential moving average (EMA). A weighted average that gives more weight to recent closes. Veloce seeds it with the SMA of the first n closes and then updates it on each close:

EMA = previous EMA + α × (close − previous EMA), with α = 2 ÷ (n + 1).

For a 9-period EMA, α = 0.2, so each new close moves the average a fifth of the way towards it.

The signal. The trend is bullish while the fast average is above the slow one and bearish while it is below. The trade happens on the change: the candle where bullish becomes bearish or the other way round.

A crossover, candle by candle

Here is a short series of 3-minute NIFTY candles run through Veloce’s moving-average code with a 3-period fast SMA and a 5-period slow SMA (short lengths so the example fits in a table). The closes are illustrative; the averages and the signal are what the code produces.

Candle Closes at Close Fast SMA (3) Slow SMA (5) Signal
09:15 09:18 25,900 warming up
09:18 09:21 25,890 warming up
09:21 09:24 25,884 25,891.33 warming up
09:24 09:27 25,878 25,884.00 warming up
09:27 09:30 25,875 25,879.00 25,885.40 bearish state, no trade
09:30 09:33 25,872 25,875.00 25,879.80 no change
09:33 09:36 25,880 25,875.67 25,877.80 no change
09:36 09:39 25,896 25,882.67 25,880.20 bullish cross
09:39 09:42 25,910 25,895.33 25,886.60 no change

Three things to notice:

  1. No signal until the slow average is full. The first five candles only fill the averages.
  2. The first state is not a trade. At 09:30 the fast average is below the slow one, but nothing crossed; the averages simply started there. Veloce trades only on a change of direction, so the first trade waits for an actual cross.
  3. The cross is known at 09:39, not before. The 09:36 candle closes at 09:39 with the fast average above the slow one. That is the first moment a trader could know.
NIFTY candle 09:36 to 09:39 option candle 09:39 to 09:42 09:39 close: fast above slow strategy targets one lot of the ATM call bought at this open + 1 tick
The cross is decided on the index candle's close; the option is bought at the open of its own next candle.

The built-in crossover option buyer

Veloce’s moving-average option buyer turns this signal into option trades on NIFTY (or SENSEX, or BANK NIFTY):

Setting Default
Averages 9-period and 21-period SMA
Candle 3 minutes
Bullish cross Buy one lot of the at-the-money call, nearest expiry
Bearish cross Sell the call if held, buy one lot of the at-the-money put
Entries Candles closing from 09:15 to 15:00
Signal cutoff Index candles closing after 15:15 are ignored
Square off Everything is closed at 15:15
Risk Buys only what the cash on hand pays for

As a spec, with a 30% stop on the premium paid added:

{
  "name": "nifty-sma-buyer",
  "candle_minutes": 3,
  "entry": {
    "signal": { "kind": "moving_average_cross", "fast": 9, "slow": 21 },
    "signal_cutoff": "15:15",
    "first_entry": "09:15",
    "last_entry": "15:00"
  },
  "legs": [{ "kind": "option", "option_type": "call", "side": "buy" }],
  "bearish_legs": [{ "kind": "option", "option_type": "put", "side": "buy" }],
  "square_off": "15:15",
  "exits": { "rules": [{ "kind": "stop_loss", "amount": { "kind": "share_of_cost", "fraction": "0.3" } }] },
  "risk": { "rules": [{ "kind": "cash" }] }
}

Swap moving_average_cross for ema_cross to test exponential averages with the same lengths.

Warm-up and overnight carry

A 21-period average on 3-minute candles needs 63 minutes of data. On the first day of a backtest, the slow average fills at 10:18, and the first trade waits for a cross after that. From the second day on, the averages carry over from the previous session, so the first candles of the morning are averaged with the previous afternoon. That is how a chart with continuous averages behaves, and it means the opening gap shows up as a sharp move in the fast average. If your rule should start fresh each morning, test a longer candle or later first entry and compare.

Whipsaws: where crossovers lose money

A crossover is profitable when trends run long enough to pay for the false starts. In a range, the averages cross back and forth and each pair of crosses is a small loss plus costs.

Here is one whipsaw with the built-in buyer, using Veloce’s slippage and NSE option charges (premiums illustrative):

Step Fill Charges
Bullish cross: buy the 25,900 call (open ₹110.00) ₹110.05 ₹26.78
Bearish cross 12 minutes later: sell the call (open ₹104.00) ₹103.95 ₹36.54

The round trip lost (103.95 − 110.05) × 65 = ₹396.50 on the price and ₹63.32 in charges, ₹459.82 in total. The charges and the two ticks of slippage (₹6.50) are paid on every round trip regardless of direction: about ₹70 per lot for an at-the-money option near ₹100. A strategy that flips four times a day pays roughly ₹280 per lot per day before the market has moved at all.

When the trend does come, the same arithmetic works in its favour. If the bearish cross that closed the call also bought the 25,900 put at ₹98.05 and the put was sold at ₹120.95 at square-off, that leg made (120.95 − 98.05) × 65 = ₹1,488.50, less ₹65.08 in charges: ₹1,423.42. The backtest’s job is to count how often each kind of day occurs.

Options add time decay

Buying an option on a crossover is not the same as buying NIFTY. An at-the-money option moves roughly half as much as the index at first, and loses time value every minute the trend fails to show up. A crossover that is break-even on NIFTY futures can lose on options. This is why the test should replay the recorded option prices rather than infer them from the index.

Reading a crossover backtest

Trend-following rules often win less often than they lose and rely on a few long trends to pay for many short losses. That makes the headline win rate misleading on its own. Read these together:

  • Win rate and average win against average loss. A 35% win rate is fine if the average winner is three times the average loser, and poor if it is the same size.
  • Profit factor. Gross profit divided by gross loss, after charges. If winning trades made ₹60,000 and losing trades lost ₹50,000, the profit factor is 1.2. Below 1 the strategy lost money; close to 1, small changes in slippage decide the result.
  • Exit reasons. Veloce labels each closed trade with why it closed: the opposite signal, the 15:15 square off, or a stop. If most profit comes from trades closed by the square off, the strategy depends on trends that last until the afternoon.
  • Time of day. Crosses in the first half hour react to the opening gap; crosses after 14:30 have little time before square off. Compare the result with a later first entry or an earlier last entry.
  • Charges as a share of gross profit. If charges take more than a third of what the trades made before costs, the strategy is fragile to any change in brokerage or slippage.
  • Maximum drawdown. A run of whipsaw days produces a long, shallow drawdown rather than one sharp loss. Its length matters as much as its depth, because it is what a trader would have to sit through.

SMA or EMA in the same test

Run the same lengths as an SMA cross and an EMA cross on the same period. The EMA version usually trades more, because it reacts sooner and also reverses sooner. If the EMA wins on the tuning period and the SMA wins on the check period, neither has shown an edge over the other; the difference is noise.

Choosing the lengths without fooling yourself

The 9/21 pair is popular, and forum threads asking which crossover is “best” never settle it, because the answer depends on the period, the candle size and the costs. A sweep can show how sensitive the result is:

Sweep input Values
Tuning period April 1 to August 31, 2026
Check until October 31, 2026
Fast 5, 9, 13
Slow 21, 34
Candle 3 minutes, 5 minutes
Settings to check Best 3

That is 12 combinations. Read the result for:

  • Plateaus. If 9/21 and 13/21 both work and 5/21 does not, the strategy is less fragile than if only one pair works.
  • Trade counts. Shorter lengths and candles trade more. Compare charges between rows.
  • Check-period decay. The best tuning result almost always falls on the check period. The overfitting guide shows how much of a tuning result can be luck.

Avoid adding filters until the plain version is understood. Every filter (ADX above 20, RSI above 50, price above a 200-period average) adds settings to tune and makes the best result look better for reasons that may not repeat.

The same crossover on MCX gold futures

Crossovers are also common on commodity futures, where there is no time decay to fight. Veloce’s futures trader runs a crossover on MCX gold or gold mini futures with your own rules; its default rule is a 9 and 21 EMA cross on 5-minute candles, long on the bullish cross and short on the bearish one, with entries from 09:00 to 23:00 and everything closed at 23:15. A risk rule blocks a share of each lot’s value as margin (10% by default) out of equity, so the number of lots is limited by the account.

Futures differ from options in the costs too: MCX futures pay commodity transaction tax on sells rather than STT, and a gold mini lot is 10 units against gold’s 100. The MCX gold futures page covers the contract details.

A checklist for an honest crossover test

Check Why
Trade on the change, not the state The first reading after warm-up is not a cross
Decide on the close, fill at the next open Avoids trading at the price that created the signal
Count charges and slippage on every flip Whipsaws are where crossovers lose
Replay option prices, not the index Time decay and delta change the outcome
Ignore the closing auction NIFTY’s last minutes reflect the cash market auction since August 3, 2026
Fix the lot size for the period NIFTY went from 75 to 65 per lot from January 2026 expiries
Tune on one period, check on a later one The best lengths in hindsight are partly luck
Look at trending and range-bound months separately A crossover’s results depend heavily on the mix

Try it in Veloce

Veloce backtests moving average and EMA crossovers on NIFTY 50 weekly, BANK NIFTY monthly and SENSEX weekly options, and on MCX gold and gold mini futures, all on one-minute data with next-open fills and itemised charges. The crossover buyer and the futures trader are built-in strategies, sweeps vary the lengths and candle size with a held-back check period, and the engine page explains how each order fills.

Create a free Veloce account and run the 9/21 crossover over your own period. For other indicator signals, see the Supertrend and RSI guide; for the full method, see how to backtest an options strategy.

Frequently asked questions

What is a moving average crossover strategy?
A rule that turns bullish when a faster moving average of closing prices crosses above a slower one and bearish when it crosses below. The 9 and 21 period pair is a common intraday choice, but the lengths are settings to test, not facts.
Is an EMA crossover better than an SMA crossover?
Neither is better in general. An exponential average reacts faster to recent prices, so it crosses earlier and more often, which helps in clean trends and hurts in choppy markets. Test both on the same period with charges and compare on a held-back check period.
Why do crossover strategies look good on charts but lose in backtests?
Charts make the big trends easy to see and the many small whipsaws easy to ignore. Each whipsaw costs charges and slippage on two fills. A backtest counts every one of them, and buying options adds time decay on top.
When does a crossover signal become tradable?
Only after the candle that produced the cross has closed. Veloce then fills the order at the open of the traded contract's next candle, so a cross on the candle closing at 09:39 fills at the 09:39 open of the option.
What candle size should I test a crossover on?
Test a few. Smaller candles give more signals, more whipsaws and more charges; larger ones fewer and later signals. In Veloce the candle size is a setting you can vary in a sweep, built from one-minute data.

Sources

  1. NSE circular NSE/FAOP/70616: revision in market lot of derivative contracts on indices (October 3, 2025)nsearchives.nseindia.com, accessed
  2. Union Budget 2026-27, Memorandum explaining the provisions of the Finance Bill (STT on options and futures)indiabudget.gov.in, accessed
  3. TradingQnA: Which is the best EMA crossover strategy?tradingqna.com, accessed
esc
↑↓Move↵Open