Backtesting

MACD strategies: how to backtest them without fooling yourself

How MACD is calculated, why the 12/26/9 setting is a convention, and how to backtest MACD crosses and ChartArt's MACD + SMA 200 rule on NIFTY options.

By
Veloce team
Published
Reading time
10 min read
On this page
  1. How MACD is calculated
  2. Warm-up
  3. Three common MACD rules
  4. ChartArt’s rule in detail
  5. MACD candle by candle
  6. The built-in MACD strategies
  7. The 200-candle warm-up
  8. As a spec
  9. The classic exponential cross as rules
  10. What one MACD trade costs
  11. Questions traders ask about MACD
  12. Reading a MACD backtest
  13. Choosing the lengths
  14. A checklist for an honest MACD test
  15. Try it in Veloce

MACD (moving average convergence divergence) measures the gap between a fast and a slow moving average of closing prices and compares it with its own average. Strategies built on it trade when that gap changes direction: the MACD line crossing its signal line, the histogram crossing zero, or either of those confirmed by a longer trend filter. To backtest one honestly, compute the indicator only from closed candles, wait for every average to fill, trade on the change rather than the state, fill at the next candle’s open, charge both sides of every trade, and choose the lengths on one period and confirm them on another. This guide works through MACD candle by candle with Veloce’s own indicator code, compares the classic exponential version with ChartArt’s simple-average rule, and shows how to set up and sweep the test.

How MACD is calculated

MACD line. The fast moving average of closes minus the slow one. The classic setting is the 12-period exponential moving average (EMA) minus the 26-period EMA.

Signal line. A moving average of the MACD line itself, classically a 9-period EMA.

Histogram. The MACD line minus the signal line. It is positive when the MACD line is above its signal line.

Veloce’s EMA seeds itself with the simple average of the first n values and then updates on each new value:

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

For a 12-period EMA, α = 2 ÷ 13 ≈ 0.154; for a 26-period EMA, α ≈ 0.074; for the 9-period signal, α = 0.2.

Warm-up

Each average needs its own data. The 26-period EMA has its first value on the 26th candle, which is also the first MACD value. The signal line needs nine MACD values, so it first exists on candle 34 (26 + 9 − 1). Until then there is no histogram and no trade.

On 3-minute candles, 34 candles is 102 minutes, so the signal line first exists on the candle closing at 10:57. A cross needs a previous value to cross from, so on the first day of a backtest a 12/26/9 signal-line cross can first fire on the candle closing at 11:00. From the second day on, the averages carry over from the previous session, so the morning’s first candles are averaged with the previous afternoon, just as on a continuous chart.

Three common MACD rules

Rule Bullish when Bearish when
Signal-line cross MACD line crosses above the signal line MACD line crosses below the signal line
Zero-line cross MACD line crosses above zero MACD line crosses below zero
ChartArt MACD + SMA 200 Histogram crosses above zero, MACD line above zero, fast average above slow, and price above its 200-period average The mirror image

The signal-line cross and the histogram crossing zero are the same event, since the histogram is the difference between the two lines.

ChartArt’s rule in detail

The MACD + SMA 200 strategy published by ChartArt on TradingView in 2015 adds three filters to the histogram cross. Veloce’s macd_trend signal follows its published logic:

  1. Simple averages, not exponential. The fast and slow averages, and the signal line, are simple moving averages. This differs from the textbook MACD, and it changes when crosses happen.
  2. The MACD line must agree. A bullish histogram cross only counts while the MACD line is above zero, and a bearish one while it is below.
  3. The trend filter uses a lagged close. The close compared with the 200-period simple average is the close from slow candles ago (26 by default), not the latest close.

The rule returns a direction only on the candle where all conditions hold together. On every other candle it says nothing, so a position is held until the opposite signal, a stop, or the square off.

MACD candle by candle

Here is an illustrative series of 5-minute NIFTY closes run through Veloce’s code, with short lengths so the example fits in a table: fast 3, slow 6, signal 3 and a 10-candle trend average. The closes are invented; the indicator values and signals are what the code produced.

Candle Close SMA MACD SMA histogram Lagged close vs trend ChartArt signal EMA histogram
10 25,890 13.83 −0.33 25,830 vs 25,845.9 none −0.10
11 25,898 14.33 0.11 25,845 vs 25,855.7 blocked: lagged close below trend −0.24
17 25,874 −10.83 −1.33 25,898 vs 25,884.3 none −1.56
18 25,888 −4.00 4.78 25,905 vs 25,886.1 blocked: MACD below zero 0.95
26 25,962 5.33 −0.94 25,920 vs 25,923.8 none 0.88
27 25,975 11.67 4.56 25,931 vs 25,933.9 blocked: lagged close below trend 1.52
31 25,975 −2.00 −5.00 25,945 vs 25,955.5 none −0.19
32 25,992 3.67 2.89 25,962 vs 25,960.7 bullish 1.72

Over 32 candles, the simple-average histogram crossed above zero four times. Only the last one passed every filter. Three things stand out:

  1. The filters do most of the work. Two crosses failed the trend filter by a few points, and one failed because the MACD line was still negative. Whether that is good depends on what those trades would have done, which only a backtest over months can say.
  2. The two MACD versions disagree on timing. The exponential histogram crossed zero at candle 18 and again at candle 26, one candle earlier than the simple-average version at 27. At candle 11 the simple version crossed while the exponential one did not cross at all. Same closes, same lengths, different trades.
  3. The trend filter compares an old close. At candle 32, the comparison is the close from six candles earlier (25,962) against the 10-candle average (25,960.7). Using the latest close (25,992) would have passed at candle 27 too.
0 11: trend filter 18: MACD below 0 27: trend filter 32: bullish
Four histogram crosses above zero; three are blocked by ChartArt's filters. Bar heights are proportional to the illustrative values.

The built-in MACD strategies

Veloce has two built-in strategies on the ChartArt signal:

Setting MACD buyer MACD seller
Lengths 12, 26, 9, trend 200 12, 26, 9, trend 200
Candle 3 minutes 5 minutes
Bullish signal Buy the at-the-money call Sell a put credit spread
Bearish signal Buy the at-the-money put Sell a call credit spread
Spread Short strike 2 steps from the money, wing 4 steps further
Exits Opposite signal, square off at 15:15, optional stop Half the credit as target, one times the credit as stop, one day before expiry
Entries 09:15 to 15:00 09:15 to 15:00, at least 2 days to expiry

Both ignore index candles closing after 15:15, so the cash market’s closing auction does not feed the indicator.

The 200-candle warm-up

The trend filter needs 200 candles. With the 15:15 signal cutoff, a session supplies 120 three-minute candles (closing from 09:18 to 15:15). The first possible signal of a backtest therefore comes on its second trading day, after 80 more candles, at 13:15 at the earliest. On 5-minute candles the filter needs about 2.8 sessions. Start the backtest a few days before the period you care about, or accept that the first days will be quiet.

As a spec

The buyer as a strategy spec:

{
  "name": "nifty-macd-buyer",
  "candle_minutes": 3,
  "entry": {
    "signal": { "kind": "macd_trend", "fast": 12, "slow": 26, "signal": 9, "trend": 200 },
    "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",
  "risk": { "rules": [{ "kind": "cash" }] }
}

The classic exponential cross as rules

To test the textbook signal-line cross instead, describe it with indicator rules. Each MACD indicator defaults to 12, 26 and 9 exponential lengths:

{
  "kind": "rules",
  "indicators": [
    { "name": "macd", "kind": "macd" },
    { "name": "signal", "kind": "macd_signal" }
  ],
  "bullish": [{ "left": "macd", "comparison": "crosses_above", "right": "signal" }],
  "bearish": [{ "left": "macd", "comparison": "crosses_below", "right": "signal" }]
}

A zero-line rule compares the MACD line with a number: { "left": "macd", "comparison": "crosses_above", "right": 0 }. Rules can combine conditions, so “MACD crosses above its signal while above zero” is two bullish conditions that must both hold.

What one MACD trade costs

Each MACD trade in an option is a round trip. For one lot of an at-the-money NIFTY call near ₹120, bought at ₹120.05 and sold at ₹101.95 after a failed signal (illustrative prices, Veloce’s November 2026 NSE charges):

Fill Price Charges
Buy ₹120.05 ₹27.11
Sell ₹101.95 ₹36.33

The loss is (101.95 − 120.05) × 65 = ₹1,176.50 on price and ₹63.44 in charges. The charges plus two ticks of slippage (₹6.50) come to about ₹70 per round trip. A signal-line cross on 3-minute candles can fire six or more times on a choppy day; the ChartArt filters cut that sharply. The backtest’s job is to tell you whether the trades the filters remove were the losing ones.

Questions traders ask about MACD

What MACD setting works best for intraday? Forum threads and broker blogs suggest faster settings such as 5/13/5 or 8/17/9 for intraday charts. None of those is a finding; they are starting points. Sweep a few and look for a plateau of settings that all work, not a single peak.

Does the histogram lead the MACD line? The histogram turns before the MACD line crosses zero, because it measures the line against its own average. That makes it earlier and noisier. In the table above, the histogram turned positive at candle 18 while the MACD line was still at −4.00.

Why do MACD crosses fail in trends? In a strong trend, the MACD line can stay far above zero while the histogram oscillates around zero, producing crosses in both directions. A trend filter or a zero-line condition removes counter-trend crosses at the cost of missing reversals.

Should I use MACD divergence? Divergence (price making a new high while MACD does not) is hard to define as a mechanical rule, because it depends on which peaks you compare. If you cannot write it as conditions on closed candles, you cannot backtest it honestly.

Reading a MACD backtest

  • Trade count by rule. Compare the signal-line cross, the zero-line cross and the ChartArt rule on the same period. Fewer trades are only better if the average trade improves by more than the lost count.
  • Win rate with average win against average loss. Trend-following rules can win less than half the time and still be profitable if winners are larger.
  • Exit reasons. If most profit comes from trades closed by the 15:15 square off, the strategy depends on afternoon trends.
  • Time of day. Signals near the open react to the gap; signals after 14:30 have little time before the square off.
  • Charges as a share of gross profit. Over a third means the result is fragile.
  • Maximum drawdown and its length. See the drawdown guide.

Choosing the lengths

Sweep input Values
Tuning period April 1 to August 31, 2026
Check until October 31, 2026
Fast 8, 12
Slow 21, 26
Trend 100, 200
Candle 3 minutes, 5 minutes
Settings to check Best 3

That is 16 combinations: fast 8 or 12, slow 21 or 26, trend 100 or 200, and a 3 or 5 minute candle.

Sixteen combinations is enough to find one that looks good by luck. The Monte Carlo guide shows how to judge how much of a result could be noise, and the walk-forward guide explains what a single check period does and does not prove.

A checklist for an honest MACD test

Check Why
Know whether your MACD uses EMAs or SMAs ChartArt’s rule uses simple averages; the textbook uses exponential
Wait for every average to fill 34 candles for 12/26/9, 200 for the trend filter
Trade on the cross, not the state A positive histogram is not a new signal
Decide on the close, fill at the next open Avoids trading at the price that created the signal
Keep the closing auction out of the indicator The last minutes of the cash session are an auction
Count charges and slippage on every trade Frequent crosses are where MACD loses
Replay option prices, not the index Time decay and delta change the outcome
Tune on one period, check on a later one The best lengths in hindsight are partly luck

Try it in Veloce

Veloce backtests MACD strategies on NIFTY 50 weekly, BANK NIFTY monthly and SENSEX weekly options, and on MCX gold and gold mini futures with indicator rules, all on one-minute data with next-open fills and itemised charges. The MACD buyer and seller are built-in strategies, the strategy builder lets you write MACD rules without code, and sweeps vary the lengths with a held-back check period. The glossary defines the terms used here.

Create a free Veloce account and compare the ChartArt rule with a plain signal-line cross on the same period. For another trend signal, see the moving average crossover guide.

Frequently asked questions

How is MACD calculated?
The MACD line is a fast exponential moving average of closes minus a slow one, by default the 12-period EMA minus the 26-period EMA. The signal line is a 9-period EMA of the MACD line, and the histogram is the MACD line minus the signal line.
Is 12, 26, 9 the best MACD setting for intraday NIFTY?
There is no best setting. 12, 26 and 9 come from daily charts and are a convention, not a finding about NIFTY. Treat the three lengths and the candle size as settings, test a few combinations on one period and confirm the choice on a later one.
What is the MACD + SMA 200 strategy?
A rule published by ChartArt on TradingView: go long when the MACD histogram crosses above zero while the MACD line is positive, the fast average is above the slow one and price is above its 200-period simple average, and the reverse for short. It uses simple moving averages throughout, not exponential ones.
How many candles does a MACD strategy need before it can trade?
An EMA-based MACD with 12, 26 and 9 needs 34 candles before the signal line exists. The MACD + SMA 200 rule needs 200 candles for its trend filter, which on 3-minute candles is more than one trading session.
Why does my MACD backtest trade so often?
MACD line and signal line crosses happen many times a day on short candles, especially in ranges. Each cross costs charges and slippage on two fills. Longer candles, a trend filter or a zero-line condition reduce the count; a backtest shows whether the fewer trades are better ones.
Should I trade MACD signals with options or futures?
Options cap the loss at the premium paid but lose time value while the move develops; futures have no decay but unlimited risk on each side. Replay the recorded prices of whichever instrument you trade, because the index's own result says little about an option's.

Sources

  1. Investopedia: What is MACD?investopedia.com, accessed
  2. TradingView: MACD + SMA 200 Strategy (by ChartArt)tradingview.com, accessed
  3. TradingQnA: MACD cross-over doesn't work on streaks?tradingqna.com, accessed
  4. NSE circular NSE/FAOP/70616: revision in market lot of derivative contracts on indices (October 3, 2025)nsearchives.nseindia.com, accessed
esc
↑↓Move↵Open