Pine Script v5 · Strategy
BT-Bollinger Bands - Trend Following
A Pine Script v5 strategy built on BB (close, 20) and EMA or SMA (close, 100). 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 commits 300 in cash and pays no commission. 15 settings; defaults include BB Length 20, BB StdDev 2 and Type Ema.
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 BT-Bollinger Bands - Trend Following repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 2 of 2 trades.
- How did BT-Bollinger Bands - Trend Following do on BTCUSDT 1D with default settings?
- +3.89%
- From 26 Jan 2024 to 21 Oct 2026, over 16 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does BT-Bollinger Bands - Trend Following run in Pine Script v6?
- Yes
- Same 16 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
- Does BT-Bollinger Bands - Trend Following use a stop loss?
- Yes
- strategy.exit sets a stop on line 74, 84.
- Does BT-Bollinger Bands - Trend Following run in Zeal Terminal?
- Yes
- It compiles in 30 ms and runs 1,000 bars in 79 ms, in the browser.
BTCUSDT · 1D · default settings
- EMA Filter
- Upper Band
- MA Band
- Lower Band
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- +3.89%
- $38.89
- Buy and hold
- +102.5%
- same period
- Closed trades
- 16
- 4 won · 12 lost
- Profitable
- 25.0%
- of closed trades
- Profit factor
- 1.37
- gross profit ÷ gross loss
- Max drawdown
- 5.65%
- −$60.05
One run with the author's default settings, $1,000 starting capital, commission as the script sets it. 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
“Strategy Close Message” is declared but never read.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
2 settings have no label
In the settings dialog initialDate (line 24), finalDate (line 26) show 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 |
|---|---|---|---|
| Time Filters | |||
| Start date | true | bool | inTradeWindow |
| Initial Date (no label in the script)This start date is in the time zone of the exchange | timestamp('01 Jan 2022 00:00 UTC') | time | inTradeWindow |
| End date | true | bool | inTradeWindow |
| Final Date (no label in the script)This end date is in the time zone of the exchange | timestamp('31 Dec 2029 23:59 UTC') | time | inTradeWindow |
| Long/Short Options | |||
| Enable Long Entrys | true | bool | entry Long Entry line 68 |
| Enable Short Entrys | true | bool | entry Short Entry line 79 |
| Bollinger Bands | |||
| BB Length | 20 | int · min 1 · step 5 | bbMiddle bbUpper bbLower |
| BB StdDev | 2 | float · min 0.5 | bbMiddle bbUpper bbLower |
| Moving Average | |||
| Moving Average FilterThis will enable or disable Exponential Moving Average Filter on Strategy | true | bool | emaFilterBuy EMA Filter |
| Type | Ema | string · options ['Ema','Sma'] | ema |
| Source | close | source | ema |
| Length | 100 | int · min 0 | ema |
| Alert Message For Bot | |||
| Strategy Entry Message | | string | entry Long Entry entry Short Entry |
| Strategy Exit Message | | string | exit Long Exit exit Short Exit |
| Strategy Close Message | | string | unused |
What it calculates
- BBclose, BB Length (20), BB StdDev (2)
bbMiddle · line 38 - BBclose, BB Length (20), BB StdDev (2)
bbUpper · line 38 - BBclose, BB Length (20), BB StdDev (2)
bbLower · line 38 - EMA / SMA Source (close), Length (100) · chosen by Type
ema · line 46
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 Entry long | (openLongPosition) and (inTradeWindow) and (checkboxLong) | On | 69 |
| cancel Long Entry | not (openLongPosition) | On | 71 |
| Exit Long Exit stop | (longIsActive) and (inTradeWindow) | On | 74 |
| Open Short Entry short | (openShortPosition) and (inTradeWindow) and (checkboxShort) | On | 80 |
| cancel Short Entry | not(openShortPosition) | On | 82 |
| Exit Short Exit stop | (shortIsActive) | On | 84 |
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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.
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 | +3.9% | +102.5% | 16 | 25% | 1.37 | 5.6% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +4.5% | +5.5% | 13 | 15% | 2.17 | 1.7% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +7.3% | +9.8% | 15 | 40% | 1.51 | 5.1% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +0.5% | +8.4% | 14 | 36% | 1.09 | 2.4% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −3.2% | +16.7% | 14 | 43% | 0.83 | 12.8% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +7.1% | +21.5% | 16 | 38% | 2.28 | 3.1% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −2.8% | +148.3% | 17 | 35% | 0.82 | 11.7% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +4.2% | +17.1% | 14 | 43% | 2.47 | 1.3% | 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 9 | 22% | $3.89 |
| Sideways market | 7 | 29% | $35.00 |
| Falling market | 0 | — | $0.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
8.5%
The 95th percentile of the worst drawdown when the same 16 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 3.6% to 8.5%; the tick is what actually happened, 5.5%. Order luck alone moves it this much.
All 16 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 16 May 2024 66,444.20 | 31 May 2024 66,870.10 | 15 | $1.92 |
| long | 16 Jul 2024 64,900.00 | 31 Jul 2024 64,835.60 | 15 | −$0.30 |
| long | 20 Sep 2024 63,850.00 | 1 Oct 2024 62,247.20 | 11 | −$7.53 |
| long | 7 Nov 2024 76,400.00 | 3 Dec 2024 94,119.70 | 26 | $69.58 |
| long | 16 Dec 2024 105,250.00 | 19 Dec 2024 99,683.10 | 3 | −$15.87 |
| long | 7 Jan 2025 102,480.00 | 8 Jan 2025 96,587.10 | 1 | −$17.25 |
| long | 19 Jan 2025 104,989.00 | 27 Jan 2025 99,912.20 | 8 | −$14.51 |
| short | 6 Feb 2025 96,155.00 | 20 Feb 2025 97,470.50 | 14 | −$4.10 |
| long | 23 Apr 2025 93,888.00 | 29 May 2025 106,156.00 | 36 | $39.20 |
| long | 11 Jul 2025 116,868.00 | 25 Jul 2025 115,937.00 | 14 | −$2.39 |
| short | 1 Aug 2025 115,500.00 | 7 Aug 2025 116,813.00 | 6 | −$3.41 |
| long | 14 Aug 2025 123,668.00 | 15 Aug 2025 117,075.00 | 1 | −$15.99 |
| long | 12 Sep 2025 115,488.00 | 22 Sep 2025 113,907.00 | 10 | −$4.11 |
| long | 3 Oct 2025 121,022.00 | 10 Oct 2025 116,793.00 | 7 | −$10.48 |
| long | 6 May 2026 81,791.50 | 13 May 2026 79,042.80 | 7 | −$10.08 |
| long | 20 Aug 2026 70,000.00 | 8 Sep 2026 77,982.40 | 19 | $34.21 |
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 |
|---|---|---|---|---|---|
| BT-Bollinger Bands - Trend Following this page | — | v5 strategy | +3.9% | 16 | 5.6% |
| Strategy Oil Z Score by jroche1973 | bb ema sma | v4 strategy | No trades on this market | ||
| Strategy- Combo Z Score by jroche1973 | bb ema sma | v4 strategy | No trades on this market | ||
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.7% |
| 4-Hour Stochastic EMA Trend by slymnturkoglu | ema sma | v4 strategy | No trades on this market | ||
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.
- No v6-only features. v6 is not needed to run this script.
Clean v5
VerifiedNothing to change.
Does it run in Pine Script v6?
Yes
Same 16 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
//VERSION =================================================================================================================-//@version=5+//@version=6// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 30 ms | With a workaround 1,000 bars in 79 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 69, 80) so the engine trades the way the script says.
“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.
//VERSION =================================================================================================================//@version=5// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// This strategy is intended to study.// It can also be used to signal a bot to open a deal by providing the Bot ID, email token and trading pair in the strategy settings screen.// As currently written, this strategy uses a Bollinger Bands for trend folling, you can use a EMA as a filter.//Autor Credsonb (M4TR1X_BR)//▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒//STRATEGY ================================================================================================================strategy(title = 'BT-Bollinger Bands - Trend Following', shorttitle = 'BBTF', overlay = true, pyramiding = 0, default_qty_type = strategy.cash, default_qty_value = 300, initial_capital = 1000, max_lines_count = 150, process_orders_on_close=true, max_labels_count = 150)//▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// CONFIG =================================================================================================================// TIME INPUTSusefromDate = input.bool(defval = true, title = 'Start date', inline = '0', group = "Time Filters")initialDate = input.time(defval = timestamp('01 Jan 2022 00:00 UTC'), title = '', inline = "0",group = 'Time Filters',tooltip="This start date is in the time zone of the exchange ")usetoDate = input.bool(defval = true, title = 'End date', inline = '1', group = "Time Filters")finalDate = input.time(defval = timestamp('31 Dec 2029 23:59 UTC'), title = '', inline = "1",group = 'Time Filters',tooltip="This end date is in the time zone of the exchange")// TIME LOGIC inTradeWindow = not usefromDate and not usetoDate or (time >= initialDate and time < finalDate)// ENABLE LONG SHORT OPTIONSstring entrygroup ='Long/Short Options ==================================='checkboxLong = input.bool(defval=true, title="Enable Long Entrys",group=entrygroup)checkboxShort = input.bool(defval=true, title="Enable Short Entrys",group=entrygroup)// BOLLINGER BANDS INPUTS ==================================================================================================string bbgroup ='Bollinger Bands ======================================'bbLength = input.int(defval=20,title='BB Length', minval=1, step=5, group=bbgroup)bbStddev = input.float(defval=2, title='BB StdDev', minval=0.5, group=bbgroup)//BOLLINGER BANDS LOGIC[bbMiddle, bbUpper, bbLower] = ta.bb(close, bbLength, bbStddev)// MOVING AVERAGES INPUTS ================================================================================================string magroup = 'Moving Average ======================================='useEma = input.bool(defval = true, title = 'Moving Average Filter',inline='', group= magroup,tooltip='This will enable or disable Exponential Moving Average Filter on Strategy')emaType=input.string (defval='Ema',title='Type',options=['Ema','Sma'],inline='', group= magroup)emaSource = input.source(defval=close,title=" Source",inline="", group= magroup)emaLength = input.int(defval=100,title="Length",minval=0,inline='', group= magroup)// MOVING AVERAGE LOGICfloat ema = emaType=='Ema'? ta.ema(emaSource,emaLength): ta.sma(emaSource,emaLength)// BOT MESSAGESstring msgroup='Alert Message For Bot ================================'messageEntry = input.string("", title="Strategy Entry Message",group=msgroup)messageExit =input.string("",title="Strategy Exit Message",group=msgroup)messageClose = input.string("", title="Strategy Close Message",group=msgroup)// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// POSITIONS =============================================================================================================//VERIFY IF THE BUY FILTERS ARE ON OR OFF bool emaFilterBuy = useEma? (close > ema):(close >= ema) or (close <= ema) //LONG / SHORT POSITIONS LOGICbool openLongPosition = (close[1] < bbUpper) and (close > bbUpper) and (emaFilterBuy)bool openShortPosition = (close[1] > bbLower) and (close < bbLower) and (emaFilterBuy)//bool closeLongPosition = (close > bbMiddle)//bool closeShortPosition= (close < bbLower)// CHEK OPEN POSITONS =====================================================================================================// open signal when not already into a positionbool validOpenLongPosition = openLongPosition and strategy.opentrades.size(strategy.opentrades - 1) <= 0bool longIsActive = validOpenLongPosition or strategy.opentrades.size(strategy.opentrades - 1) > 0bool validOpenShortPosition = openShortPosition and strategy.opentrades.size(strategy.opentrades - 1) <= 0bool shortIsActive = validOpenShortPosition or strategy.opentrades.size(strategy.opentrades - 1) < 0longEntryPoint = highif (openLongPosition) and (inTradeWindow) and (checkboxLong) strategy.entry(id = 'Long Entry', direction = strategy.long, stop = longEntryPoint, alert_message=messageEntry)if not (openLongPosition) strategy.cancel('Long Entry')//submit exit orders for trailing take profit price if (longIsActive) and (inTradeWindow) strategy.exit(id = 'Long Exit', stop=bbMiddle, alert_message=messageExit)//if (closeLongPosition) // strategy.close(id = 'Long Entry', alert_message=messageClose) shortEntryPoint = low if (openShortPosition) and (inTradeWindow) and (checkboxShort) strategy.entry(id = 'Short Entry', direction = strategy.short, stop = shortEntryPoint, alert_message=messageEntry)if not(openShortPosition) strategy.cancel('Short Entry')if (shortIsActive) strategy.exit(id = 'Short Exit', stop = bbMiddle, alert_message=messageExit)//if (closeShortPosition) //strategy.close(id = 'Short Close', alert_message=messageClose)// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒// PLOTS ===============================================================================================================// TRADE WINDOW ========================================================================================================bgcolor(color = inTradeWindow ? color.new(#089981,90):na, title = 'Time Window')// EMA/SMA var emafilterColor = color.new(color.white, 0)plot(series=useEma? ema:na, title = 'EMA Filter', color = emafilterColor, linewidth = 2, style = plot.style_line)// BOLLINGER BANDSplot(series=bbUpper, title = "Upper Band", color = color.aqua)//, display = display.none)plot(series=bbMiddle, title = "MA Band", color = color.red)//, display = display.none)plot(series=bbLower, title = "Lower Band", color = color.aqua)//, display = display.none)// PAINT BARS COLORSbool bulls = (close[1] < bbUpper[1]) and (close > bbUpper)bool bears = (close[1] > bbLower [1]) and (close < bbLower)neutral_color = color.new(color.black, 100)barcolors = bulls ? color.green : bears ? color.red : neutral_colorbarcolor(barcolors)// ======================================================================================================================