Backtest a MACD Crossover Strategy (Pine & Python)
Run and inspect a 12/26/9 MACD signal-line crossover strategy in Pine Script on historical exchange candles with fees, slippage, and trade markers.
Before you start
A MACD (12, 26, 9) signal-line crossover combined with a slow trend filter (200-bar EMA) captures momentum shifts in the direction of the dominant trend while suppressing counter-trend whipsaws. In QTrader you can test this exact Pine Script v6 setup directly on exchange candles with commission and equity curves.
Follow the workflow
- Open the bundled 4h Pine MACD + EMA 200 example below in the QTrader workbench and inspect its declared
ta.macd(close, 12, 26, 9)andta.ema(close, 200)calls. - Verify warm-up bars: the 200-bar EMA requires 200 prior candles before producing values, so early bars produce no signals.
- Run Backtest and inspect individual entry/exit markers, net fees (commission & slippage) and maximum drawdown rather than win rate alone.
- Add an explicit stop-loss or test alternative markets using controlled parameter comparisons before saving.
Worked example
The complete bundled Pine Script v6 strategy from QTrader's template library requires 100% equity sizing and 0.1% commission by default.
//@version=6
strategy("MACD cross, EMA 200 filter", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)
trend = ta.ema(close, 200)
if ta.crossover(macdLine, signalLine) and close > trend
strategy.entry("Long", strategy.long)
if ta.crossunder(macdLine, signalLine)
strategy.close("Long")
Limits and interpretation
This bundled template contains no hard stop-loss or take-profit, so adverse moves after entry remain open until the MACD line crosses back below its signal line. Choppy sideways markets can still produce consecutive losing crosses; consult backtest validity checks.