Donchian Channel MACD Trend strategy in Pine Script
A breakout of the Donchian channel, confirmed by the MACD, with a stop a multiple of the ATR away.
Donchian Channels · MACD · ATR · long and short · by Robrecht99 · Mozilla Public License 2.0
What is its backtest worth?
A parameter sweep finds the best setting of the Donchian Channel MACD Trend strategy. PineTester tells you if it holds up: whether the best result was only picked after the fact, what it makes with fees, what you could have known at the time (a walk-forward on data the pick did not see) and how deep it fell along the way. On the free start, your first own backtest gets the full evaluation; its trade list and result file come with the full report or a plan.
Creates a draft on Binance BTC/USDT 4h over about six and a half years with 0.1% commission per order and 2 ticks slippage; you start it yourself. A backtest uses credits; new accounts receive free credits.
The rules
- Enters long when the close breaks above the highest high of the upper channel and the MACD is above its signal line; short on a break below the lower channel with the MACD below.
- Places a stop an ATR multiple away from the entry; closes the long on a MACD cross down, the short on a cross up.
- Sizes each trade from a fixed risk per trade and the ATR.
What to watch for
- Breakout systems lose often in sideways markets and earn in a few long trends: look at the share of trades with a profit and the largest drop together.
- The position size follows the ATR, so the same signal trades a different amount in calm and in volatile times.
How PineTester judges a backtest, with its sources: how we judge results.
The Pine Script code
The author's code with its licence notice (Mozilla Public License 2.0), with one change marked in the code: the same test conditions for every library strategy in its strategy() line – the whole account per trade (split over the entries where it adds to a position), 0.1% commission per order and 2 ticks slippage; the trading rules are unchanged. Pine Script v5; PineTester converts it to v6 automatically, so results can differ slightly from TradingView.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Robrecht99
// Modified by PineTester (2026-11-14): the same test conditions for every library strategy in strategy(): 100% of equity per entry,
// 0.1% commission per order, 2 ticks slippage, initial capital 10,000. The trading rules are unchanged.
//@version=5
strategy("Trend Following with Donchian Channels and MACD", overlay=true, margin_long=0, margin_short=0, pyramiding=1, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, slippage=2)
// Donchian Channels //
Length1 = input.int(title="Length Upper Channel", defval=50, minval=1, group="Donchian Channels Inputs")
Length2 = input.int(title="Length Lower Channel", defval=50, minval=1, group="Donchian Channels Inputs")
h1 = ta.highest(high[1], Length1)
l1 = ta.lowest(low[1], Length2)
fillColor = input.color(color.new(color.purple, 95), title = "Fill Color", group = "Donchian Channels Inputs")
upperColor = input.color(color.new(color.orange, 0), title = " Color Upper Channel", group = "Donchian Channels Inputs", inline = "upper")
lowerColor = input.color(color.new(color.orange, 0), title = " Color Lower Channel", group = "Donchian Channels Inputs", inline = "lower")
u = plot(h1, "Upper", color=upperColor)
l = plot(l1, "Lower", color=upperColor)
fill(u, l, color=fillColor)
// MACD //
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// ATR Trailing Stops //
xATRPeriod = input.int(14, "ATR Period", group = "ATR Trailing Stop Inputs")
xATRMultiplier = input.float(4, "ATR Multiplier", step = .1, group = "ATR Trailing Stop Inputs")
xATR = ta.atr(xATRPeriod)
Stop = xATRMultiplier * xATR
var xATRTrailingStop = 0.0
xATRTrailingStop := if close>xATRTrailingStop[1] and close[1] > xATRTrailingStop[1]
math.max(xATRTrailingStop[1], close - Stop)
else if close < xATRTrailingStop[1] and close[1] < xATRTrailingStop[1]
math.min(xATRTrailingStop[1], close + Stop)
else if close > xATRTrailingStop[1]
close - Stop
else
close + Stop
var Position = 0.0
Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]
1
else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]
-1
else
Position[1]
PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orange
plot(xATRTrailingStop, color=PlotColor, linewidth = input(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(macd, signal)
entrycondition2 = macd > signal
entrycondition3 = macd and signal > 0
sellcondition1 = ta.crossover(signal, macd)
sellcondition2 = signal > macd
sellcondition3 = macd and signal < 0
// Buy and Sell Signals //
if (close > h1 and entrycondition2 and entrycondition3)
strategy.entry("long", strategy.long, qty=amount)
stoploss = close - atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (sellcondition1 and sellcondition2 and sellcondition3)
strategy.close(id="long")
if (close < l1 and sellcondition2 and sellcondition3)
strategy.entry("short", strategy.short, qty=amount)
stoploss = close + atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (entrycondition1 and entrycondition2 and entrycondition3)
strategy.close(id="short")
Related strategies
- Omar MMR – A MACD crossover in an uptrend of three EMAs, with a fixed take profit and stop loss.
- PresentTrend – An ATR band follows the price and switches sides with the Money Flow Index; a turn of the band opens the trade.
- Dual Supertrend with MACD – Two Supertrends and the MACD histogram must agree before a trade opens; any one of them turning closes it.
- Chandelier Exit + ZLSMA – A Chandelier Exit turn opens a trade only when the price also crosses a zero-lag least squares average (ZLSMA).
- Donchian Breakout + MA – A Donchian channel breakout in the direction of two moving averages, closed when the averages cross back.
Open-source script by Robrecht99, shown under the Mozilla Public License 2.0. Not a recommendation; neither the author nor TradingView endorses PineTester. Backtests are hypothetical results on past data, not a forecast.