Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Trend Following with Bollinger Bands

A Pine Script v5 strategy built on SMA (close, 20), Stdev (close, 20) and EMA (close, 40). 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. 16 settings; defaults include Length 20, Source close and StdDev 2.0.

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 Bollinger Bands repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 1 of 1 trades.
How did Trend Following with Bollinger Bands do on BTCUSDT 1D with default settings?
+2.54%
From 26 Jan 2024 to 21 Oct 2026, over 7 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Trend Following with Bollinger Bands 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: 7 before, 7 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 Bollinger Bands use a stop loss?
Yes
strategy.exit sets a stop on line 68, 74.
Does Trend Following with Bollinger Bands run in Zeal Terminal?
Yes
It compiles in 23 ms and runs 1,000 bars in 92 ms, in the browser.

BTCUSDT · 1D · default settings

  • Basis
  • Upper
  • Lower
  • Fast EMA
  • Slow EMA
  • 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,023,440$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
+2.54%
$25,350.60
Buy and hold
+102.5%
same period
Closed trades
7
4 won · 3 lost
Profitable
57.1%
of closed trades
Profit factor
2.10
gross profit ÷ gross loss
Max drawdown
1.69%
−$16,930.40

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

    No commission

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

  • Note

    1 setting has no label

    In the settings dialog length (line 6) shows an empty name. The labels on this page come from the variable names.

  • 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
Bollinger Bands Inputs
Length (no label in the script)20int · min 1basis dev
Sourceclosesourcebasis dev
Offset0int · min -500 · max 500Upper Lower Basis
StdDev2.0float · min 0.001 · max 50dev
Source Fast MAclosesourcefast
Source Slow MAclosesourceslow
Moving Average Inputs
Length Fast MA40int · min 1fast
Length Slow MA120int · min 1slow
Color Fast MAcolor.new(color.red, 0)colorFast EMA
Color Slow MAcolor.new(color.purple, 0)colorSlow EMA
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

  • SMASource (close), Length (20)basis · line 9
  • StdevSource (close), Length (20)dev · line 10
  • EMASource Fast MA (close), Length Fast MA (40)fast · line 25
  • EMASource Slow MA (close), Length Slow MA (120)slow · line 26
  • ATRATR Period (14)atr · line 34
  • ATRATR Period (14)xATR · line 39
  • Crossoverfast, slowentrycondition1 · line 60
  • Crossunderfast, slowsellcondition1 · 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.

closecloseprice datalengthLengthsetting · 20multStdDevsetting · 2.0len1Length Fast MAsetting · 40len2Length Slow MAsetting · 120high · low · closehigh · low · closeprice datalength1ATR Periodsetting · 14xATRPeriodATR Periodsetting · 14riskRisk Per Tradesetting · 0.01pointvaluePoint Value/ATR Multipl…setting · 4leverageLeverage Usedsetting · 1xATRMultiplierATR Multipliersetting · 4basisSMA→ basisdevStdev→ devfastEMA→ fastslowEMA→ slowatrATR→ atrxATRATR→ xATRentrycondition1Crossover→ entrycondition1sellcondition1Crossunder→ sellcondition1upper, lowerupper · lower2 valuesamountamountvalueStopStopvaluestoplossstoplossvalueentrycondition2entrycondition2conditionsellcondition2sellcondition2conditionxATRTrailingStopxATRTrailingStopconditionPositionPositionconditionPlotColorColourPlotColorentry:longOpen longstrategy.entryexit:exit slexit exit slstrategy.exitclose:longClose longstrategy.closeentry:shortOpen shortstrategy.entryclose:shortClose shortstrategy.closeplot:14Basisplotplot:15Upperplotplot:16Lowerplotfill:BackgroundBackgroundfillplot:27Fast EMAplotplot:28Slow EMAplotplot:58ATR Trailing Stopplot

Order rules

OrderFires whenBy defaultLine
Open long long(close > upper and entrycondition2)On66
Exit exit sl stop(close > upper and entrycondition2)On68
Close long(sellcondition1 and sellcondition2)On70
Open short short(close < lower and sellcondition2)On72
Exit exit sl stop(close < lower and sellcondition2)On74
Close short(entrycondition1 and entrycondition2)On76

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.

1/1trades 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+2.5%+102.5%757%2.101.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+1.9%+5.5%1136%1.362.8%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+2.5%+9.8%757%1.961.4%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+4.7%+8.4%838%3.111.6%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−2.4%+16.7%922%0.424.4%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+8.7%+21.5%743%5.431.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.9%+148.3%743%1.421.6%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+3.0%+17.1%933%1.863.0%8 May 2026 – 21 Oct 2026

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

Settings heatmap

Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (Length Fast MA 20, Length Slow MA 168) made +2.7% before 26 Dec 2025 and +0.8% after it, against +0.8% for the defaults. 95% of the 64 combinations made money in-sample and 64% out-of-sample.

Before 26 Dec 2025 · in-sample
Length Slow MA ↓ · Length Fast MA →2024283440485668
60+2%+2%+1%+1%+1%+1%+1%−0%
72+1%+1%+1%+1%+0%+1%+0%+2%
84+1%+1%+1%+0%+1%+0%+2%+0%
102+1%+0%+0%+1%+1%+2%+1%−0%
120+1%+1%+1%+1%+2%+2%+0%+0%
144+1%+1%+2%+2%+0%+0%+0%−1%
168+3%+2%+1%+1%+1%+0%+0%+1%
204+2%+2%+2%+2%+1%+2%+2%+2%
From 26 Dec 2025 · out-of-sample
Length Slow MA ↓ · Length Fast MA →2024283440485668
60−1%−1%−1%−2%−2%−2%−2%+3%
72−1%−1%−1%−1%−2%−2%−0%+0%
84−1%−1%−1%−1%−1%+0%+0%+1%
102−1%−1%−1%+0%+0%+1%+1%+1%
120−1%+0%+0%+1%+1%+1%+1%+1%
144+1%+1%+1%+1%+1%+1%+1%+1%
168+1%+1%+1%+1%+1%+1%+1%+1%
204+1%+1%+1%+1%+1%+1%+1%+1%

Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market0—$0.00
Sideways market580%$44,682.90
Falling market20%−$19,332.30

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

How bad could the drawdown be?

2.3%

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

0%3%
All 7 trades
SideEntryExitBarsP&L
short7 Sep 2024 53,963.0023 Sep 2024 64,686.4016−$10,000.00
long30 Oct 2024 72,736.4025 Feb 2025 89,524.60118$19,715.50
short7 Apr 2025 78,430.0022 Apr 2025 91,600.0015−$9,332.27
long9 May 2025 103,262.0021 Aug 2025 112,033.00104$7,455.08
long12 Sep 2025 115,483.0010 Oct 2025 111,465.0028−$3,698.61
short7 Nov 2025 101,346.0022 Apr 2026 79,418.50166$13,440.30
short23 May 2026 75,539.5019 Aug 2026 69,321.2088$7,770.58

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 Bollinger Bands this page—v5 strategy+2.5%71.7%
[KL] BOLL + MACD Strategy v2 (published) by DojiEmojisma stdev ema atrv4 strategy−32.1%2854.0%
[EURUSD60] BB Expansion Strategy by kasaismsma stdev ema atrv4 strategyNo trades on this market
[KL] Bollinger bands + RSI Strategy by DojiEmojisma stdev atr emav4 strategy+28.2%3014.7%
[KL] Bollinger Bands Consolidation Strategy by DojiEmojisma stdev atr emav4 strategy+39.1%3319.6%
Full strategy AllinOne with risk management MACD RSI PSAR ATR MA by SoftKill21sma stdev ema atrv4 strategy+2,985,110.0%32,350,820.0%

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 7, 21, 22, 33). 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 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 7: input() → input.source()
  • Line 21: input() → input.source()
  • Line 22: input() → input.source()
  • Line 33: input() → input.float()
  • Line 58: input() → input.int()
⋯length = input.int(20, minval=1, group="Bollinger Bands Inputs")-src = input(close, title="Source", group="Bollinger Bands Inputs")+src = input.source(close, title="Source", group="Bollinger Bands Inputs")mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")⋯len2 = input.int(120, minval=1, title="Length Slow MA", group="Moving Average Inputs")-src1 = input(close, title="Source Fast MA")+src1 = input.source(close, title="Source Fast MA")-src2 = input(close, title="Source Slow MA")+src2 = input.source(close, title="Source Slow MA")maColorFast = input.color(color.new(color.red, 0), title = "Color Fast MA", group = "Moving Average Inputs", inline = "maFast")⋯length1 = 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(length1)⋯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: 7 before, 7 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 Bollinger Bands", overlay=true, margin_long=0, margin_short=0, pyramiding=1)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 23 msYes 1,000 bars in 92 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 Bollinger Bands", overlay=true, margin_long=0, margin_short=0, pyramiding=1)// Bollinger Bands //length = input.int(20, minval=1, group="Bollinger Bands Inputs")src = input(close, title="Source", group="Bollinger Bands Inputs")mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")basis = ta.sma(src, length)dev = mult * ta.stdev(src, length)upper = basis + devlower = basis - devoffset = input.int(0, "Offset", minval = -500, maxval = 500, group="Bollinger Bands Inputs")plot(basis, "Basis", color=color.orange, offset = offset)p1 = plot(upper, "Upper", color=color.orange, offset = offset)p2 = plot(lower, "Lower", color=color.orange, offset = offset)fill(p1, p2, title = "Background", color=color.rgb(255, 0, 255, 95))// Moving Averages //len1 = input.int(40, minval=1, title="Length Fast MA", group="Moving Average Inputs")len2 = input.int(120, minval=1, title="Length Slow MA", group="Moving Average Inputs")src1 = input(close, title="Source Fast MA")src2 = input(close, title="Source Slow MA")maColorFast = input.color(color.new(color.red, 0), title = "Color Fast MA", group = "Moving Average Inputs", inline = "maFast")maColorSlow = input.color(color.new(color.purple, 0), title = "Color Slow MA", group = "Moving Average Inputs", inline = "maSlow")fast = ta.ema(src1, len1) slow = ta.ema(src2, len2)plot(fast, color=maColorFast, title="Fast EMA")plot(slow, color=maColorSlow, title="Slow EMA")// 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")length1 = 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(length1)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(fast, slow)entrycondition2 = fast > slowsellcondition1 = ta.crossunder(fast, slow)sellcondition2 = slow > fast// Buy and Sell Signals //if (close > upper and entrycondition2)    strategy.entry("long", strategy.long, qty=amount)    stoploss = close - atr * xATRMultiplier    strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)if (sellcondition1 and sellcondition2)    strategy.close(id="long")if (close < lower and sellcondition2)    strategy.entry("short", strategy.short, qty=amount)    stoploss = close + atr * xATRMultiplier    strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)if (entrycondition1 and entrycondition2)    strategy.close(id="short")