Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Trend Following with Donchian Channels and MACD

A Pine Script v5 strategy built on Highest (high[1], 50), Lowest (low[1], 50) and SMA or EMA (close, 12). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade is one contract and pays no commission. 17 settings; defaults include Length Upper Channel 50, Length Lower Channel 50 and Fast Length 12.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Trend Following with Donchian Channels and MACD repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 4 of 4 trades.
How did Trend Following with Donchian Channels and MACD do on BTCUSDT 1D with default settings?
−1.04%
From 26 Jan 2024 to 21 Oct 2026, over 12 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Trend Following with Donchian Channels and MACD run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 12 before, 12 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does Trend Following with Donchian Channels and MACD use a stop loss?
Yes
strategy.exit sets a stop on line 69, 75.
Does Trend Following with Donchian Channels and MACD run in Zeal Terminal?
Yes
It compiles in 25 ms and runs 1,000 bars in 57 ms, in the browser.

BTCUSDT · 1D · default settings

  • Upper
  • Lower
  • ATR Trailing Stop
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (14)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,013,900$2,025,273Equity from $1,000,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots.
Net profit
−1.04%
−$10,404.60
Buy and hold
+102.5%
same period
Closed trades
12
5 won · 7 lost
Profitable
41.7%
of closed trades
Profit factor
0.80
gross profit ÷ gross loss
Max drawdown
2.72%
−$27,152.90

One run with the author's default settings, $1,000,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

What a careful reader of this script would point out, found by checking the source and the backtest.

  • Check

    1 setting does nothing

    “ Color Lower Channel” is declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Donchian Channels Inputs
Length Upper Channel50int · min 1h1
Length Lower Channel50int · min 1l1
Fill Colorcolor.new(color.purple, 95)colorfill
Color Upper Channelcolor.new(color.orange, 0)colorUpper Lower
Color Lower Channelcolor.new(color.orange, 0)colorunused
Fast Length12intfast_ma
Slow Length26intslow_ma
Sourceclosesourcefast_ma slow_ma
Signal Smoothing9int · min 1 · max 50signal
Oscillator MA TypeEMAstring · options ["SMA", "EMA"]fast_ma slow_ma
Signal Line MA TypeEMAstring · options ["SMA", "EMA"]signal
ATR Position Size Inputs
Leverage Used1int · min 1amount
Point Value/ATR Multipliers from Entry4int · min 1amount
ATR Period14int · min 1atr
Risk Per Trade0.01floatamount
ATR Trailing Stop Inputs
ATR Period14intxATR
ATR Multiplier4float · step .1Stop stoploss

What it calculates

  • Highesthigh[1], Length Upper Channel (50)h1 · line 8
  • Lowestlow[1], Length Lower Channel (50)l1 · line 9
  • SMA / EMASource (close), Fast Length (12) · chosen by Oscillator MA Typefast_ma · line 23
  • SMA / EMASource (close), Slow Length (26) · chosen by Oscillator MA Typeslow_ma · line 24
  • SMA / EMAmacd, Signal Smoothing (9) · chosen by Signal Line MA Typesignal · line 26
  • ATRATR Period (14)atr · line 33
  • ATRATR Period (14)xATR · line 38
  • Crossovermacd, signalentrycondition1 · line 59
  • Crossoversignal, macdsellcondition1 · line 62

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

highhighprice dataLength1Length Upper Channelsetting · 50lowlowprice dataLength2Length Lower Channelsetting · 50closecloseprice datasma_sourceOscillator MA Typesetting · EMAfast_lengthFast Lengthsetting · 12slow_lengthSlow Lengthsetting · 26sma_signalSignal Line MA Typesetting · EMAsignal_lengthSignal Smoothingsetting · 9high · low · closehigh · low · closeprice datalengthATR Periodsetting · 14xATRPeriodATR Periodsetting · 14riskRisk Per Tradesetting · 0.01pointvaluePoint Value/ATR Multipl…setting · 4leverageLeverage Usedsetting · 1xATRMultiplierATR Multipliersetting · 4h1Highest→ h1l1Lowest→ l1fast_maSMA / EMA→ fast_ma · by Oscillator MA …slow_maSMA / EMA→ slow_ma · by Oscillator MA …signalSMA / EMA→ signal · by Signal Line MA …atrATR→ atrxATRATR→ xATRentrycondition1Crossover→ entrycondition1sellcondition1Crossover→ sellcondition1macdmacdvaluehisthistvalueamountamountvalueStopStopvaluestoplossstoplossvalueentrycondition2entrycondition2conditionentrycondition3entrycondition3conditionsellcondition2sellcondition2conditionsellcondition3sellcondition3conditionxATRTrailingStopxATRTrailingStopconditionPositionPositionconditionPlotColorColourPlotColorentry:longOpen longstrategy.entryexit:exit slexit exit slstrategy.exitclose:longClose longstrategy.closeentry:shortOpen shortstrategy.entryclose:shortClose shortstrategy.closeplot:13Upperplotplot:14Lowerplotfill:15Fillfillplot:57ATR Trailing Stopplot

Order rules

OrderFires whenBy defaultLine
Open long long(close > h1 and entrycondition2 and entrycondition3)On67
Exit exit sl stop(close > h1 and entrycondition2 and entrycondition3)On69
Close long(sellcondition1 and sellcondition2 and sellcondition3)On71
Open short short(close < l1 and sellcondition2 and sellcondition3)On73
Exit exit sl stop(close < l1 and sellcondition2 and sellcondition3)On75
Close short(entrycondition1 and entrycondition2 and entrycondition3)On77

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source, and the live replay matched history.

4/4trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−1.0%+102.5%1242%0.802.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+1.3%+5.5%1136%1.292.5%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+4.0%+9.8%967%3.401.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+2.8%+8.4%933%2.051.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−3.4%+16.7%1118%0.403.6%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+3.7%+21.5%1145%1.952.3%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−1.2%+148.3%1040%0.732.7%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−2.8%+17.1%1421%0.605.4%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market20%−$13,573.00
Sideways market757%$12,043.90
Falling market333%−$8,875.46

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

4.6%

The 95th percentile of the worst drawdown when the same 12 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 2.3% to 4.6%; the tick is what actually happened, 2.1%. Order luck alone moves it this much.

0%5%
All 12 trades
SideEntryExitBarsP&L
short2 May 2024 58,365.0020 May 2024 71,167.8018−$10,000.00
short5 Jul 2024 57,050.0017 Jul 2024 65,540.1012−$10,170.80
long27 Sep 2024 65,174.0013 Jan 2025 90,013.20108$27,847.10
short26 Feb 2025 88,680.402 May 2025 96,489.9065−$5,721.37
long2 May 2025 96,489.9022 Jun 2025 99,649.5051$2,710.33
long11 Jul 2025 116,010.0021 Aug 2025 112,033.0041−$3,573.02
short30 Aug 2025 108,377.003 Oct 2025 121,610.0034−$10,000.00
short5 Nov 2025 101,497.0014 Jan 2026 95,414.0070$3,822.09
long14 Jan 2026 95,414.0025 Jan 2026 86,573.8011−$8,717.42
short1 Feb 2026 78,741.1026 Mar 2026 71,336.5053$5,942.89
long18 Apr 2026 77,072.001 Jun 2026 72,245.3044−$4,647.59
short3 Jun 2026 66,760.808 Aug 2026 64,923.2066$2,103.15

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
Trend Following with Donchian Channels and MACD this page—v5 strategy−1.0%122.7%
ATR + STC + MA by Romediusema lowest highest atr smav5 strategy−1.2%153.3%
-NoSKi Hammer-Star -w angle of ema Backtester - by noski1atr ema sma highest lowestv5 strategydoes not run in Zeal Terminal
LONG SAZB $ by stevenz17ema sma atr lowest highestv4 strategyNo trades on this market
MACD Strategy by maxencetajetatr highest lowest ema smav5 strategy+5.8%56.9%
DC Breakout Strategy - This is simplicity at its finest. by Robrecht99sma highest lowest atrv5 strategy+10.8%578.3%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • 4 settings use the untyped input() (line 17, 18, 19, 32). It still compiles in v6; input.int, input.float or input.source state the type.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

Same 12 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 17: input() → input.int()
  • Line 18: input() → input.int()
  • Line 19: input() → input.source()
  • Line 32: input() → input.float()
  • Line 57: input() → input.int()
⋯// MACD //-fast_length = input(title="Fast Length", defval=12)+fast_length = input.int(title="Fast Length", defval=12)-slow_length = input(title="Slow Length", defval=26)+slow_length = input.int(title="Slow Length", defval=26)-src = input(title="Source", defval=close)+src = input.source(title="Source", defval=close)signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9)⋯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")+risk = input.float(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")atr = ta.atr(length)⋯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")+plot(xATRTrailingStop, color=PlotColor, linewidth = input.int(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")// Buy and Sell Conditions //⋯

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 12 before, 12 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © Robrecht99-//@version=5+//@version=6strategy("Trend Following with Donchian Channels and MACD", overlay=true, margin_long=0, margin_short=0, pyramiding=1)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 25 msYes 1,000 bars in 57 msNot measured
PineTSNot testedNot testedNot measured

The engine and this page's reading of the source count a different number of settings, so one of them has missed one.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © Robrecht99//@version=5strategy("Trend Following with Donchian Channels and MACD", overlay=true, margin_long=0, margin_short=0, pyramiding=1)// 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_masignal = 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 * xATRvar xATRTrailingStop = 0.0xATRTrailingStop := 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 + Stopvar Position = 0.0Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]    1else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]    -1else    Position[1]PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orangeplot(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 > signalentrycondition3 = macd and signal > 0sellcondition1 = ta.crossover(signal, macd)sellcondition2 = signal > macdsellcondition3 = 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")