Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (15)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,039$2,025Equity from $1,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. 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.
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.

SettingDefaultType and rangeFeeds
Time Filters
Start datetrueboolinTradeWindow
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')timeinTradeWindow
End datetrueboolinTradeWindow
Final Date (no label in the script)This end date is in the time zone of the exchangetimestamp('31 Dec 2029 23:59 UTC')timeinTradeWindow
Long/Short Options
Enable Long Entrystrueboolentry Long Entry line 68
Enable Short Entrystrueboolentry Short Entry line 79
Bollinger Bands
BB Length20int · min 1 · step 5bbMiddle bbUpper bbLower
BB StdDev2float · min 0.5bbMiddle bbUpper bbLower
Moving Average
Moving Average FilterThis will enable or disable Exponential Moving Average Filter on StrategytrueboolemaFilterBuy EMA Filter
TypeEmastring · options ['Ema','Sma']ema
Sourceclosesourceema
Length100int · min 0ema
Alert Message For Bot
Strategy Entry Messagestringentry Long Entry entry Short Entry
Strategy Exit Messagestringexit Long Exit exit Short Exit
Strategy Close Messagestringunused

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 Typeema · 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.

closecloseprice databbLengthBB Lengthsetting · 20bbStddevBB StdDevsetting · 2emaTypeTypesetting · EmaemaLengthLengthsetting · 100highhighprice datalowlowprice datatimetimeprice datainitialDateInitial Datesetting · timestamp('01 Jan 2…finalDateFinal Datesetting · timestamp('31 Dec 2…bbMiddleBB→ bbMiddlebbUpperBB→ bbUpperbbLowerBB→ bbLoweremaEMA / SMA→ ema · by TypeemaFilterBuyemaFilterBuyvaluelongEntryPointlongEntryPointvalueshortEntryPointshortEntryPointvalueinTradeWindowinTradeWindowconditionopenLongPositionopenLongPositionconditionopenShortPositionopenShortPositionconditionlongIsActivelongIsActiveconditionshortIsActiveshortIsActiveconditionvalidOpenLongPositionvalidOpenLongPositionconditionvalidOpenShortPositionvalidOpenShortPositionconditionbullsbullsconditionbearsbearsconditionemafilterColor, neutral_color, barcolorsColouremafilterColor · neutral_colo…entry:Long EntryOpen Long Entrystrategy.entrycancel:Long Entrycancel Long Entrystrategy.cancelexit:Long Exitexit Long Exitstrategy.exitentry:Short EntryOpen Short Entrystrategy.entrycancel:Short Entrycancel Short Entrystrategy.cancelexit:Short Exitexit Short Exitstrategy.exitbgcolor:90Time Windowbgcolorplot:93EMA Filterplotplot:95Upper Bandplotplot:96MA Bandplotplot:97Lower Bandplotbarcolor:103barcolorbarcolor

Order rules

OrderFires whenBy defaultLine
Open Long Entry long(openLongPosition) and (inTradeWindow) and (checkboxLong)On69
cancel Long Entrynot (openLongPosition)On71
Exit Long Exit stop(longIsActive) and (inTradeWindow)On74
Open Short Entry short(openShortPosition) and (inTradeWindow) and (checkboxShort)On80
cancel Short Entrynot(openShortPosition)On82
Exit Short Exit stop(shortIsActive)On84

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.

2/2trades 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 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+3.9%+102.5%1625%1.375.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+4.5%+5.5%1315%2.171.7%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+7.3%+9.8%1540%1.515.1%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.5%+8.4%1436%1.092.4%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−3.2%+16.7%1443%0.8312.8%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+7.1%+21.5%1638%2.283.1%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−2.8%+148.3%1735%0.8211.7%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.2%+17.1%1443%2.471.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 barsTradesWonP&L
Rising market922%$3.89
Sideways market729%$35.00
Falling market0—$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.

0%10%
All 16 trades
SideEntryExitBarsP&L
long16 May 2024 66,444.2031 May 2024 66,870.1015$1.92
long16 Jul 2024 64,900.0031 Jul 2024 64,835.6015−$0.30
long20 Sep 2024 63,850.001 Oct 2024 62,247.2011−$7.53
long7 Nov 2024 76,400.003 Dec 2024 94,119.7026$69.58
long16 Dec 2024 105,250.0019 Dec 2024 99,683.103−$15.87
long7 Jan 2025 102,480.008 Jan 2025 96,587.101−$17.25
long19 Jan 2025 104,989.0027 Jan 2025 99,912.208−$14.51
short6 Feb 2025 96,155.0020 Feb 2025 97,470.5014−$4.10
long23 Apr 2025 93,888.0029 May 2025 106,156.0036$39.20
long11 Jul 2025 116,868.0025 Jul 2025 115,937.0014−$2.39
short1 Aug 2025 115,500.007 Aug 2025 116,813.006−$3.41
long14 Aug 2025 123,668.0015 Aug 2025 117,075.001−$15.99
long12 Sep 2025 115,488.0022 Sep 2025 113,907.0010−$4.11
long3 Oct 2025 121,022.0010 Oct 2025 116,793.007−$10.48
long6 May 2026 81,791.5013 May 2026 79,042.807−$10.08
long20 Aug 2026 70,000.008 Sep 2026 77,982.4019$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.

ScriptSharesTypeNetTradesMax drawdown
BT-Bollinger Bands - Trend Following this page—v5 strategy+3.9%165.6%
Strategy Oil Z Score by jroche1973bb ema smav4 strategyNo trades on this market
Strategy- Combo Z Score by jroche1973bb ema smav4 strategyNo trades on this market
MACD Long Strat by TheGrindTodayema smav4 strategy+24.0%7920.1%
Stock trending strategy by exlux99ema smav4 strategy+35.3%2114.7%
4-Hour Stochastic EMA Trend by slymnturkogluema smav4 strategyNo 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

Verified

Nothing 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.

Download the v6 script

//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

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 30 msWith a workaround 1,000 bars in 79 msNot measured
PineTSNot testedNot testedNot 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)// ======================================================================================================================