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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Bollinger Bands Inputs | |||
| Length (no label in the script) | 20 | int · min 1 | basis dev |
| Source | close | source | basis dev |
| Offset | 0 | int · min -500 · max 500 | Upper Lower Basis |
| StdDev | 2.0 | float · min 0.001 · max 50 | dev |
| Source Fast MA | close | source | fast |
| Source Slow MA | close | source | slow |
| Moving Average Inputs | |||
| Length Fast MA | 40 | int · min 1 | fast |
| Length Slow MA | 120 | int · min 1 | slow |
| Color Fast MA | color.new(color.red, 0) | color | Fast EMA |
| Color Slow MA | color.new(color.purple, 0) | color | Slow EMA |
| ATR Position Size Inputs | |||
| Leverage Used | 1 | int · min 1 | amount |
| Point Value/ATR Multipliers from Entry | 4 | int · min 1 | amount |
| ATR Period | 14 | int · min 1 | atr |
| Risk Per Trade | 0.01 | float | amount |
| ATR Trailing Stop Inputs | |||
| ATR Period | 14 | int | xATR |
| ATR Multiplier | 4 | float · step .1 | Stop 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, slow
entrycondition1 · line 60 - Crossunderfast, slow
sellcondition1 · 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | (close > upper and entrycondition2) | On | 66 |
| Exit exit sl stop | (close > upper and entrycondition2) | On | 68 |
| Close long | (sellcondition1 and sellcondition2) | On | 70 |
| Open short short | (close < lower and sellcondition2) | On | 72 |
| Exit exit sl stop | (close < lower and sellcondition2) | On | 74 |
| Close short | (entrycondition1 and entrycondition2) | On | 76 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +2.5% | +102.5% | 7 | 57% | 2.10 | 1.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +1.9% | +5.5% | 11 | 36% | 1.36 | 2.8% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +2.5% | +9.8% | 7 | 57% | 1.96 | 1.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +4.7% | +8.4% | 8 | 38% | 3.11 | 1.6% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −2.4% | +16.7% | 9 | 22% | 0.42 | 4.4% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +8.7% | +21.5% | 7 | 43% | 5.43 | 1.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.9% | +148.3% | 7 | 43% | 1.42 | 1.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +3.0% | +17.1% | 9 | 33% | 1.86 | 3.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.
| Length Slow MA ↓ · Length Fast MA → | 20 | 24 | 28 | 34 | 40 | 48 | 56 | 68 |
|---|---|---|---|---|---|---|---|---|
| 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% |
| Length Slow MA ↓ · Length Fast MA → | 20 | 24 | 28 | 34 | 40 | 48 | 56 | 68 |
|---|---|---|---|---|---|---|---|---|
| 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 0 | — | $0.00 |
| Sideways market | 5 | 80% | $44,682.90 |
| Falling market | 2 | 0% | −$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.
All 7 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 7 Sep 2024 53,963.00 | 23 Sep 2024 64,686.40 | 16 | −$10,000.00 |
| long | 30 Oct 2024 72,736.40 | 25 Feb 2025 89,524.60 | 118 | $19,715.50 |
| short | 7 Apr 2025 78,430.00 | 22 Apr 2025 91,600.00 | 15 | −$9,332.27 |
| long | 9 May 2025 103,262.00 | 21 Aug 2025 112,033.00 | 104 | $7,455.08 |
| long | 12 Sep 2025 115,483.00 | 10 Oct 2025 111,465.00 | 28 | −$3,698.61 |
| short | 7 Nov 2025 101,346.00 | 22 Apr 2026 79,418.50 | 166 | $13,440.30 |
| short | 23 May 2026 75,539.50 | 19 Aug 2026 69,321.20 | 88 | $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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Trend Following with Bollinger Bands this page | — | v5 strategy | +2.5% | 7 | 1.7% |
| [KL] BOLL + MACD Strategy v2 (published) by DojiEmoji | sma stdev ema atr | v4 strategy | −32.1% | 28 | 54.0% |
| [EURUSD60] BB Expansion Strategy by kasaism | sma stdev ema atr | v4 strategy | No trades on this market | ||
| [KL] Bollinger bands + RSI Strategy by DojiEmoji | sma stdev atr ema | v4 strategy | +28.2% | 30 | 14.7% |
| [KL] Bollinger Bands Consolidation Strategy by DojiEmoji | sma stdev atr ema | v4 strategy | +39.1% | 33 | 19.6% |
| Full strategy AllinOne with risk management MACD RSI PSAR ATR MA by SoftKill21 | sma stdev ema atr | v4 strategy | +2,985,110.0% | 3 | 2,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.
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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 23 ms | Yes 1,000 bars in 92 ms | Not measured |
| PineTS | Not tested | Not tested | Not 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")