Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

MA Bollinger Bands + RSI

A Pine Script v5 strategy built on Stdev (close, 200), SMA or HMA or WMA or EMA or VWMA (close, 200) and RSI (close, 6). It has 4 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 10000 in cash and pays 0.1 commission. 30 settings; defaults include Trailing lookback 2, ATR Mult 9.0 and ATR Length 14.

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 MA Bollinger Bands + RSI repaint?
No
No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
How did MA Bollinger Bands + RSI do on BTCUSDT 1D with default settings?
−73.92%
From 26 Jan 2024 to 21 Oct 2026, over 4 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
What alerts does MA Bollinger Bands + RSI have?
4
openLongAlertMessage; closeLongAlertMessage; openShortAlertMessage; closeShortAlertMessage.
Does MA Bollinger Bands + RSI 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: 4 before, 1 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 MA Bollinger Bands + RSI use a stop loss?
Yes
strategy.exit sets a stop on line 221, 233.

BTCUSDT · 1D · default settings

  • Long Signal
  • Short Signal
  • Plot
  • Moving Average
  • BBprice Upper
  • BBprice Lower
  • 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 (30)
50,00075,000100,000125,000AprJulOct2025AprJulOct2026AprJulOct$2,572$20,253Equity from $10,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 219, 231) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
Net profit
−73.92%
−$7,391.74
Buy and hold
+102.5%
same period
Closed trades
4
0 won · 4 lost
Profitable
0.0%
of closed trades
Profit factor
0.00
gross profit ÷ gross loss
Max drawdown
77.26%
−$7,726.16

One run with the author's default settings, $10,000 starting capital, commission as the script sets it. A short 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.

  • Likely bug

    ta.sma(BBvol, 50) ignores the settings line 79

    Line 79 hard-codes 50 where line 50 uses “MA Length”. Changing those settings moves one band but not this one.

    ta.sma(BBvol, 50)ta.sma(BBvol, MAlen)
  • Likely bug

    ta.sma(BBvol, 2000) ignores the settings line 80

    Line 80 hard-codes 2000 where line 50 uses “MA Length”. Changing those settings moves one band but not this one.

    ta.sma(BBvol, 2000)ta.sma(BBvol, MAlen)
  • Note

    No slippage

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

  • Note

    Uses an argument v6 removed

    when = on line 221, 233. The upgraded version below moves each call inside an if block.

Settings

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

SettingDefaultType and rangeFeeds
Trade Parameters
Long tradestrueboolentry Long line 216 line 217 line 237
Short tradesSwitch on/off long and short tradestrueboolentry Short line 225 line 228 line 229
Use Take ProfitFixed Take Profit valuefalseboolline 162 line 169 plot exit Long exit exit Short exit
Use Stop LossFixed Stop Loss valuefalseboolline 163 line 170 plot exit Long exit exit Short exit
Use Trailing StopATR Trailing Stop Loss value trueboolline 164 line 171 plot exit Long exit exit Short exit
Re-Entry after SL/TPAllows to re-enter trades in the same direction as previous trade if previous trade\'s stop loss or take profit was hittrueboolentry Long entry Short line 143 line 151 line 217 line 229
Trailing lookbackHow many bars back will trailing stops look for a swing low (longs) or sing high (short) to get a starting point2int · min 0 · max 1000 · step 1longTrailStart shortTrailStart
ATR MultIncrease/decrease to set stops and/or targets further/closer to trade entry price9.0float · min 0.1SLdist longTrailStart shortTrailStart
ATR LengthAverage of the \'True Range\' over x past bars14int · min 0atr
Risk:RewardMultiplies the take profit distance by this number 1float · min 0 · max 100 · step 0.1longTP shortTP
Volatility Filters
High VolatilitytrueboolBBvol Upper BBvol Lower line 84 BBvol Signal Line Base Line
Low VolatilityFilters out trade signals during high volatility / low volatility or both.trueboolBBvol Upper BBvol Lower line 91 BBvol Signal Line Base Line
Volatility FactorLower this number to filter out more trades when volatility at extremes5.0float · min 0.1 · max 10 · step 0.1HighVolLvl LowVolLvl
Volatility VisualsPlots additionnal graphs on the chart to illustrate how extreme levels of volatility are defined (how Bollinger Bands are colored)falseboolBBvol Upper BBvol Lower BBvol Signal Line Base Line
Moving Average & Bollinger Bands
MA TypeType of moving average used for standard deviationSMAstring · options ['SMA', 'EMA', 'WMA', 'VWMA', 'HMA']line 51 line 53 line 55 line 57
MA LengthMoving average lookback200intMA
BB MultSet upper & lower bands closer / appart2.0float · min 0.001 · step 0.01BBdev
BB LengthBollinger bands, standard deviation lookback200intBBdev
Relative Strength Index
RSI Cross Loockback How many bars back (from price crossing-over lower bound or crossing-under upper bound) to look for corresponding RSI neutral crossover/under10int · min 0 · max 1000line 68 line 73
RSI NeutralDefines the value at wich RSI neutral crossover or crossunder occurs50intRSIcrossover RSIcrossunder
RSI LengthRelative Strenght Index lookback6intRSI
Date & Time Filters
Enable Date FilterTurns on/off date filterfalseboolDateTime Date Filter
Start Date FilterDate & time to start excluding tradestimestamp('1 Jan 2022 00:00 +0000')timeDateFilter
End Date FilterDate & time to stop excluding tradestimestamp('1 Jan 2023 00:00 +0000')timeDateFilter
Enable Session FilterTurns on/off time session filterfalseboolTimeFilter DateTime Time Filter
Trading SessionNo trades will be taken outside of this range1000-2200:1234567sessionTimeFilter DateTime
Alert Messages
Open LongIf you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Long) & \'\'Message to close order at Market Price\'\' (in Close Long) from your 3Commas long bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)stringalert
Close Longstringalert
Open ShortIf you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Short) & \'\'Message to close order at Market Price\'\' (in Close Short) from your 3Commas short bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)stringalert
Close Shortstringalert

What it calculates

  • Stdevclose, BB Length (200)BBdev · line 49
  • SMA / HMA / WMA / EMA / VWMAclose, MA Length (200)MA · line 50
  • RSIclose, RSI Length (6)RSI · line 64
  • CrossoverRSI, RSI Neutral (50)RSIcrossover · line 65
  • CrossunderRSI, RSI Neutral (50)RSIcrossunder · line 66
  • SMABBvol, 50SignalLine · line 79
  • SMABBvol, 2000BaseLine · line 80
  • ATRATR Length (14)atr · line 129
  • Lowestlow, Trailing lookback (2)longTrailStart · line 148
  • Highesthigh, Trailing lookback (2)shortTrailStart · line 149

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.

The script has 79 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long longlongTradesON and validLong and newTradeDirection or longTradesON and validLong and SPS[1] == 0 and reEnterAfterSLTP and not (validLong and longSLTPhit)On219
Exit Long exit stop and limitSPS > 0On221
Open Short shortshortTradesON and validShort and newTradeDirection or shortTradesON and validShort and SPS[1] == 0 and reEnterAfterSLTP and not (validShort and shortSLTPhit)On231
Exit Short exit stop and limitSPS < 0On233

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

Alerts

AlertCallMessageLine
(no title)alertopenLongAlertMessage220
(no title)alertcloseLongAlertMessage226
(no title)alertopenShortAlertMessage232
(no title)alertcloseShortAlertMessage238

Does it repaint?

No

No repainting patterns in the source.

Not measuredAn engine gap, not the scriptThe script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script. The answer comes from the checks on the source alone.
  • 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−73.9%+102.5%40%0.0077.3%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−0.1%+5.5%00%0.004.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+104.8%+9.8%367%11.7737.8%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−6.8%+8.4%333%0.5419.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+52.3%+16.7%2100%524.2536.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−12.0%+21.5%250%0.0221.9%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−45.7%+148.3%540%0.54109.6%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−13.3%+17.1%425%0.3624.1%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 market10%−$1,653.48
Sideways market10%−$2,642.66
Falling market20%−$3,085.60

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

How bad could the drawdown be?

73.8%

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

0%85%
All 4 trades
SideEntryExitBarsP&L
short1 Nov 2024 70,292.0011 Nov 2024 88,708.8010−$2,642.66
short20 Dec 2024 97,461.9010 Jul 2025 113,366.00202−$1,653.48
long4 Dec 2025 93,429.903 Feb 2026 73,117.4061−$2,191.92
long26 Feb 2026 67,988.004 Jun 2026 62,042.1098−$893.68

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
MA Bollinger Bands + RSI this page—v5 strategy−73.9%477.3%
Multi MA Trend Following Strategy Template by TradeAutomationema hma sma vwma wma stdev atr highest lowestv5 strategy+12.3%326.9%
BTC 15 min by RafaelZionisma ema rsi wma stdev highest lowestv4 strategy−25.7%11938.9%
Multi Trend Cross Strategy Template by TradeAutomationema hma sma vwma wma stdev highest lowestv5 strategy+33.0%37.3%
MZ SRSI Strategy V1.0 by MightyZingerema sma highest lowest stdev rsiv4 strategyNo trades on this market
Bear & Bull Zone Signal Strategy by Solutions1978rsi ema highest lowest sma vwmav4 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.

  • 2 strategy calls use the when = argument (line 221, 233). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

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

  • Line 221: when = SPS > 0 → if block
  • Line 233: when = SPS < 0 → if block
⋯    alert(openLongAlertMessage  , alert.freq_once_per_bar_close)-strategy.exit(id='Long exit', from_entry='Long',- stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBupper : na,- limit = useTP ? TPsaved : na,- when  = SPS > 0)+if SPS > 0+    strategy.exit(id='Long exit', from_entry='Long',+     stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBupper : na,+     limit = useTP ? TPsaved : na)if longSLTPhit or (shortTradesON and validShort and newTradeDirection)⋯    alert(openShortAlertMessage , alert.freq_once_per_bar_close)-strategy.exit(id='Short exit', from_entry='Short',- stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBlower : na,- limit = useTP ? TPsaved : na,- when  = SPS < 0)+if SPS < 0+    strategy.exit(id='Short exit', from_entry='Short',+     stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBlower : na,+     limit = useTP ? TPsaved : na)if shortSLTPhit or (longTradesON and validLong and newTradeDirection)⋯

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: 4 before, 1 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.

⋯// Scipt Author: © LucasVivien-//@version=5+//@version=6strategy('MA Bollinger Bands + RSI (Strategy)', shorttitle='MABB+RSI (Strat)', calc_on_order_fills=true,  overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=10000, commission_value=0.1)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 84 msWith a workaround 1,000 bars in 198 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 219, 231) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“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 close code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// Special credits: ChartArt / Matthew J. Slabosz / Zen & The Art of Trading // Scipt Author: © LucasVivien//@version=5strategy('MA Bollinger Bands + RSI (Strategy)', shorttitle='MABB+RSI (Strat)', calc_on_order_fills=true,  overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=10000, commission_value=0.1)//==============================================================================//================================   INPUTS   ==================================//==============================================================================var g_trades = '     Trade Parameters'longTradesON     = input.bool (title='Long trades'         , defval=true , group=g_trades, inline='a', tooltip='')shortTradesON    = input.bool (title='Short trades'        , defval=true , group=g_trades, inline='a', tooltip='Switch on/off long and short trades')useTP            = input.bool (title='Use Take Profit'     , defval=false, group=g_trades, inline='' , tooltip='Fixed Take Profit value')useSL            = input.bool (title='Use Stop Loss'       , defval=false, group=g_trades, inline='' , tooltip='Fixed Stop Loss value')useTSL           = input.bool (title='Use Trailing Stop'   , defval=true , group=g_trades, inline='' , tooltip='ATR Trailing Stop Loss value ')reEnterAfterSLTP = input.bool (title='Re-Entry after SL/TP', defval=true , group=g_trades, inline='' , tooltip='Allows to re-enter trades in the same direction as previous trade if previous trade\'s stop loss or take profit was hit')TSLlookback      = input.int  (title='Trailing lookback'   , defval=2    , group=g_trades, inline='' , tooltip='How many bars back will trailing stops look for a swing low (longs) or sing high (short) to get a starting point', minval=0, maxval=1000, step=1)atrMult          = input.float(title='ATR Mult'            , defval=9.0  , group=g_trades, inline='' , tooltip='Increase/decrease to set stops and/or targets further/closer to trade entry price', minval=0.1)atrLen           = input.int  (title='ATR Length'          , defval=14   , group=g_trades, inline='' , tooltip='Average of the \'True Range\' over x past bars', minval=0)rr               = input.float(title='Risk:Reward'         , defval=1    , group=g_trades, inline='' , tooltip='Multiplies the take profit distance by this number ', minval=0, maxval=100, step=0.1)var g_volatility = '     Volatility Filters'UseVolHigh = input.bool (title='High Volatility'   , defval=true , group=g_volatility, inline='b', tooltip='')UseVolLow  = input.bool (title='Low Volatility'    , defval=true , group=g_volatility, inline='b', tooltip='Filters out trade signals during high volatility / low volatility or both.')BBvolX     = input.float(title='Volatility Factor' , defval=5.0  , group=g_volatility, inline='' , tooltip='Lower this number to filter out more trades when volatility at extremes', maxval=10, minval=0.1, step=0.1)AddVol     = input.bool (title='Volatility Visuals', defval=false, group=g_volatility, inline='' , tooltip='Plots additionnal graphs on the chart to illustrate how extreme levels of volatility are defined (how Bollinger Bands are colored)')var g_MABB = '     Moving Average & Bollinger Bands'MAtype = input.string(title='MA Type', defval='SMA', group=g_MABB, inline='c', tooltip='Type of moving average used for standard deviation', options=['SMA', 'EMA', 'WMA', 'VWMA', 'HMA'])MAlen  = input.int   (title='MA Length', defval=200, group=g_MABB, inline='c', tooltip='Moving average lookback')BBX    = input.float (title=' BB Mult', defval=2.0 , group=g_MABB, inline='d', tooltip='Set upper & lower bands closer / appart', step=0.01, minval=0.001)BBlen  = input.int   (title='BB Length', defval=200, group=g_MABB, inline='d', tooltip='Bollinger bands, standard deviation lookback')var g_RSI = '     Relative Strength Index'RSINlen = input.int(title='RSI Cross Loockback ', defval=10, group=g_RSI, tooltip='How many bars back (from price crossing-over lower bound or crossing-under upper bound) to look for corresponding RSI neutral crossover/under', minval=0, maxval=1000)RSIN    = input.int(title='RSI Neutral'         , defval=50, group=g_RSI, tooltip='Defines the value at wich RSI neutral crossover or crossunder occurs')RSIlen  = input.int(title='RSI Length'          , defval=6 , group=g_RSI, tooltip='Relative Strenght Index lookback')var g_datetime = '     Date & Time Filters'UseDateFilter  = input.bool   (title='Enable Date Filter'   , defval=false                              , group=g_datetime, tooltip='Turns on/off date filter')StartDate      = input.time   (title='Start Date Filter'    , defval=timestamp('1 Jan 2022 00:00 +0000'), group=g_datetime, tooltip='Date & time to start excluding trades')EndDate        = input.time   (title='End Date Filter'      , defval=timestamp('1 Jan 2023 00:00 +0000'), group=g_datetime, tooltip='Date & time to stop excluding trades')UseTimeFilter  = input.bool   (title='Enable Session Filter', defval=false                              , group=g_datetime, tooltip='Turns on/off time session filter')TradingSession = input.session(title='Trading Session'      , defval='1000-2200:1234567'                , group=g_datetime, tooltip='No trades will be taken outside of this range')var g_messages = '     Alert Messages'openLongAlertMessage   = input.string(title='Open Long'  , defval='', group=g_messages, inline='e', tooltip='If you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Long) & \'\'Message to close order at Market Price\'\' (in Close Long) from your 3Commas long bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)')closeLongAlertMessage  = input.string(title='Close Long' , defval='', group=g_messages, inline='e', tooltip='')openShortAlertMessage  = input.string(title='Open Short' , defval='', group=g_messages, inline='f', tooltip='If you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Short) & \'\'Message to close order at Market Price\'\' (in Close Short) from your 3Commas short bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)')closeShortAlertMessage = input.string(title='Close Short', defval='', group=g_messages, inline='f', tooltip='')//==============================================================================//================================   SIGNALS   =================================//==============================================================================//----------------------------   BOLLINGER BANDS   -----------------------------BBdev = ta.stdev(close, BBlen) * BBXMA = ta.sma(close, MAlen)if MAtype == 'HMA'    MA := ta.hma(close, MAlen)if MAtype == 'WMA'    MA := ta.wma(close, MAlen)if MAtype == 'EMA'    MA := ta.ema(close, MAlen)if MAtype == 'VWMA'    MA := ta.vwma(close, MAlen)BBupper = MA + BBdevBBlower = MA - BBdevBBbull  = open < BBlower and close > BBlowerBBbear  = open > BBupper and close < BBupper//----------------------------------   RSI   -----------------------------------RSI           = ta.rsi(close, RSIlen)RSIcrossover  = ta.crossover(RSI, RSIN)RSIcrossunder = ta.crossunder(RSI, RSIN)RSIbull = falsefor i = 0 to RSINlen by 1    if RSIcrossover[i]  == true        RSIbull := true        RSIbullRSIbear = falsefor i = 0 to RSINlen by 1    if RSIcrossunder[i] == true        RSIbear := true        RSIbear//------------------------------   VOLATILITY   --------------------------------BBvol      = BBupper - BBlowerSignalLine = ta.sma(BBvol, 50)BaseLine   = ta.sma(BBvol, 2000)HighVolLvl = BaseLine + BaseLine * BBvolX / 10LowVolLvl  = BaseLine - BaseLine * BBvolX / 10var volExtrmHigh = falseif BBvol > HighVolLvl and UseVolHigh    volExtrmHigh := true    volExtrmHighelse    volExtrmHigh := false    volExtrmHighvar volExtrmLow  = falseif BBvol < LowVolLvl and UseVolLow    volExtrmLow  := true    volExtrmLowelse    volExtrmLow  := false    volExtrmLow//---------------------------   DATE/TIME FILTER   -----------------------------In(t)      => na(time(timeframe.period, t)) == falseTimeFilter = UseTimeFilter and not In(TradingSession) or not UseTimeFilterDateFilter = time >= StartDate and time <= EndDateDateTime   = (UseDateFilter ? not DateFilter : true) and (UseTimeFilter ? In(TradingSession) : true)//--------------------------   SIGNALS VALIDATION   ----------------------------validLong  = BBbull and RSIbull and not volExtrmHigh and not volExtrmLow and DateTime and barstate.isconfirmedvalidShort = BBbear and RSIbear and not volExtrmHigh and not volExtrmLow and DateTime and barstate.isconfirmed//==============================================================================//========================   STOP LOSS & TAKE PROFIT   =========================//==============================================================================//------------------------   TRADE DIRECTION CHANGE   --------------------------var lastsignalislong  = falsevar lastsignalisshort = falsevar newTradeDirection = falseif validLong    lastsignalislong  := true    lastsignalisshort := false    lastsignalisshortif validShort    lastsignalislong  := false    lastsignalisshort := true    lastsignalisshortif  lastsignalislong  == true and lastsignalislong[1]  == false or lastsignalisshort == true and lastsignalisshort[1] == false    newTradeDirection := true    newTradeDirectionelse    newTradeDirection := false    newTradeDirection//---------------------------   DATA & VARIABLES   -----------------------------SPS = strategy.position_sizeatr = ta.atr(atrLen)var SLsaved = 0.0var TPsaved = 0.0var float TSLsaved = navar float entryPrice = na//----------------------------   STRAIGHT STOPS   ------------------------------SLdist      = atr * atrMultlongSL      = close - SLdistlongSLDist  = close - longSLlongTP      = close + longSLDist * rrshortSL     = close + SLdistshortSLDist = shortSL - closeshortTP     = close - shortSLDist * rrif validLong and SPS[1] <= 0 or validShort and SPS[1] >= 0 or (validLong or validShort) and SPS[1] == 0 and reEnterAfterSLTP    SLsaved := validLong ? longSL : validShort ? shortSL : na    TPsaved := validLong ? longTP : validShort ? shortTP : na    TPsaved//----------------------------   TRAILING STOPS   ------------------------------longTrailStart  = ta.lowest(low, TSLlookback) - atr * atrMultshortTrailStart = ta.highest(high, TSLlookback) + atr * atrMultif validLong and SPS[1] <= 0 or validShort and SPS[1] >= 0 or (validLong or validShort) and SPS[1] == 0 and reEnterAfterSLTP    TSLsaved := validLong ? longTrailStart : validShort ? shortTrailStart : na    entryPrice := closeif SPS > 0    TSLsaved := math.max(longTrailStart , TSLsaved, TSLsaved[1])if SPS < 0    TSLsaved := math.min(shortTrailStart, TSLsaved, TSLsaved[1])if SPS[1] != 0 and SPS == 0    TSLsaved := na//------------------------------   SL TP HITS   --------------------------------var longSLTPhit  = falseif SPS[1] > 0 and((useTP ? high >= TPsaved[1] : false) or (useSL  ? low  <= SLsaved[1]  : false) or (useTSL ? low  <= TSLsaved[1] : false))     longSLTPhit  := trueelse    longSLTPhit  := falsevar shortSLTPhit = falseif SPS[1] < 0 and ((useTP ? low  <= TPsaved[1] : false) or (useSL  ? high >= SLsaved[1]  : false) or (useTSL ? high >= TSLsaved[1] : false))     shortSLTPhit := trueelse    shortSLTPhit := false//==============================================================================//=================================   PLOTS   ==================================//==============================================================================//--------------------------------   SIGNALS   ---------------------------------plotchar(validLong , title='Long Signal' , char='⬆', location=location.belowbar, size=size.tiny, color=color.new(#3064fc, 0))plotchar(validShort, title='Short Signal', char='⬇', location=location.abovebar, size=size.tiny, color=color.new(#fc1049, 0))//----------------------------   STRAIGHT STOPS   ------------------------------plot(useTP and SPS != 0 and not newTradeDirection ? TPsaved : na, color=color.new(color.green, 0), style=plot.style_linebr)plot(useSL and SPS != 0 and not newTradeDirection ? SLsaved : na, color=color.new(color.red, 0), style=plot.style_linebr)//----------------------------   TRAILING STOPS   ------------------------------TSLcolor = SPS > 0 and entryPrice > TSLsaved ? color.red : SPS > 0 and entryPrice < TSLsaved ? color.green :           SPS < 0 and entryPrice < TSLsaved ? color.red : SPS < 0 and entryPrice > TSLsaved ? color.green : naplot(useTSL and SPS != 0 and not newTradeDirection ? TSLsaved : na, color=TSLcolor, style=plot.style_linebr)//----------------------------   BOLLINGER BANDS   -----------------------------plot(MA, title='Moving Average', color=color.new(color.white, 50))PriceUpperLine = plot(BBupper, title='BBprice Upper', color=color.new(color.gray, transp=60))PriceLowerLine = plot(BBlower, title='BBprice Lower', color=color.new(color.gray, transp=60))fill(PriceUpperLine, PriceLowerLine, title='BBprice Fill', color= volExtrmHigh and BBvol > BBvol[1] ? color.new(#ff1010, 70) : volExtrmHigh and BBvol < BBvol[1] ? color.new(#ff1010, 75) :  volExtrmLow  and BBvol < BBvol[1] ? color.new(#10ff10, 70) :  volExtrmLow  and BBvol > BBvol[1] ? color.new(#10ff10, 75) :  color.new(color.white, 90))//------------------------------   VOLATILITY   --------------------------------plot((UseVolHigh or UseVolLow) and AddVol ? BBvol      : na, title='BBvol'      , color=color.new(color.blue   , 10))plot((UseVolHigh or UseVolLow) and AddVol ? SignalLine : na, title='Signal Line', color=color.new(color.fuchsia, 10))plot((UseVolHigh or UseVolLow) and AddVol ? BaseLine   : na, title='Base Line'  , color=color.new(color.yellow , 10))VolUpperLine = plot((UseVolHigh or UseVolLow) and AddVol ? HighVolLvl : na, title='BBvol Upper', color=color.new(color.yellow, 70))VolLowerLine = plot((UseVolHigh or UseVolLow) and AddVol ? LowVolLvl  : na, title='BBvol Lower', color=color.new(color.yellow, 70))fill(VolUpperLine, VolLowerLine, title='BBvol Fill', color=color.new(color.yellow, 98))//---------------------------   DATE/TIME FILTER   -----------------------------bgcolor(DateFilter and UseDateFilter ? color.rgb(255, 70, 70, 85) : na, title='Date Filter')bgcolor(TimeFilter and UseTimeFilter ? color.rgb(255, 70, 70, 85) : na, title='Time Filter')//==============================================================================//===========================   STRATEGY & ALERTS    ===========================//==============================================================================//---------------------------------   LONGS   ----------------------------------if  longTradesON and validLong and newTradeDirection or longTradesON and validLong and SPS[1] == 0 and reEnterAfterSLTP  and not (validLong and longSLTPhit)    strategy.entry(id='Long', direction=strategy.long)    alert(openLongAlertMessage  , alert.freq_once_per_bar_close)strategy.exit(id='Long exit', from_entry='Long', stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBupper : na, limit = useTP ? TPsaved : na, when  = SPS > 0)if longSLTPhit or (shortTradesON and validShort and newTradeDirection)    alert(closeLongAlertMessage , alert.freq_once_per_bar)//--------------------------------   SHORTS   ----------------------------------if  shortTradesON and validShort and newTradeDirection or shortTradesON and validShort and SPS[1] == 0 and reEnterAfterSLTP  and not (validShort and shortSLTPhit)    strategy.entry(id='Short', direction=strategy.short)    alert(openShortAlertMessage , alert.freq_once_per_bar_close)strategy.exit(id='Short exit', from_entry='Short', stop  = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBlower : na, limit = useTP ? TPsaved : na, when  = SPS < 0)if shortSLTPhit or (longTradesON and validLong and newTradeDirection)    alert(closeShortAlertMessage, alert.freq_once_per_bar)