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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Trade Parameters | |||
| Long trades | true | bool | entry Long line 216 line 217 line 237 |
| Short tradesSwitch on/off long and short trades | true | bool | entry Short line 225 line 228 line 229 |
| Use Take ProfitFixed Take Profit value | false | bool | line 162 line 169 plot exit Long exit exit Short exit |
| Use Stop LossFixed Stop Loss value | false | bool | line 163 line 170 plot exit Long exit exit Short exit |
| Use Trailing StopATR Trailing Stop Loss value | true | bool | line 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 hit | true | bool | entry 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 point | 2 | int · min 0 · max 1000 · step 1 | longTrailStart shortTrailStart |
| ATR MultIncrease/decrease to set stops and/or targets further/closer to trade entry price | 9.0 | float · min 0.1 | SLdist longTrailStart shortTrailStart |
| ATR LengthAverage of the \'True Range\' over x past bars | 14 | int · min 0 | atr |
| Risk:RewardMultiplies the take profit distance by this number | 1 | float · min 0 · max 100 · step 0.1 | longTP shortTP |
| Volatility Filters | |||
| High Volatility | true | bool | BBvol Upper BBvol Lower line 84 BBvol Signal Line Base Line |
| Low VolatilityFilters out trade signals during high volatility / low volatility or both. | true | bool | BBvol Upper BBvol Lower line 91 BBvol Signal Line Base Line |
| Volatility FactorLower this number to filter out more trades when volatility at extremes | 5.0 | float · min 0.1 · max 10 · step 0.1 | HighVolLvl LowVolLvl |
| Volatility VisualsPlots additionnal graphs on the chart to illustrate how extreme levels of volatility are defined (how Bollinger Bands are colored) | false | bool | BBvol Upper BBvol Lower BBvol Signal Line Base Line |
| Moving Average & Bollinger Bands | |||
| MA TypeType of moving average used for standard deviation | SMA | string · options ['SMA', 'EMA', 'WMA', 'VWMA', 'HMA'] | line 51 line 53 line 55 line 57 |
| MA LengthMoving average lookback | 200 | int | MA |
| BB MultSet upper & lower bands closer / appart | 2.0 | float · min 0.001 · step 0.01 | BBdev |
| BB LengthBollinger bands, standard deviation lookback | 200 | int | BBdev |
| 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/under | 10 | int · min 0 · max 1000 | line 68 line 73 |
| RSI NeutralDefines the value at wich RSI neutral crossover or crossunder occurs | 50 | int | RSIcrossover RSIcrossunder |
| RSI LengthRelative Strenght Index lookback | 6 | int | RSI |
| Date & Time Filters | |||
| Enable Date FilterTurns on/off date filter | false | bool | DateTime Date Filter |
| Start Date FilterDate & time to start excluding trades | timestamp('1 Jan 2022 00:00 +0000') | time | DateFilter |
| End Date FilterDate & time to stop excluding trades | timestamp('1 Jan 2023 00:00 +0000') | time | DateFilter |
| Enable Session FilterTurns on/off time session filter | false | bool | TimeFilter DateTime Time Filter |
| Trading SessionNo trades will be taken outside of this range | 1000-2200:1234567 | session | TimeFilter 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) | | string | alert |
| Close Long | | string | alert |
| 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) | | string | alert |
| Close Short | | string | alert |
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, 50
SignalLine · line 79 - SMABBvol, 2000
BaseLine · 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
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | longTradesON and validLong and newTradeDirection
or longTradesON and validLong and SPS[1] == 0 and reEnterAfterSLTP
and not (validLong and longSLTPhit) | On | 219 |
| Exit Long exit stop and limit | SPS > 0 | On | 221 |
| Open Short short | shortTradesON and validShort and newTradeDirection
or shortTradesON and validShort and SPS[1] == 0 and reEnterAfterSLTP
and not (validShort and shortSLTPhit) | On | 231 |
| Exit Short exit stop and limit | SPS < 0 | On | 233 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | openLongAlertMessage | 220 |
| (no title) | alert | closeLongAlertMessage | 226 |
| (no title) | alert | openShortAlertMessage | 232 |
| (no title) | alert | closeShortAlertMessage | 238 |
Does it repaint?
No
No repainting patterns in the source.
- 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 | −73.9% | +102.5% | 4 | 0% | 0.00 | 77.3% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −0.1% | +5.5% | 0 | 0% | 0.00 | 4.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +104.8% | +9.8% | 3 | 67% | 11.77 | 37.8% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −6.8% | +8.4% | 3 | 33% | 0.54 | 19.3% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +52.3% | +16.7% | 2 | 100% | 524.25 | 36.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −12.0% | +21.5% | 2 | 50% | 0.02 | 21.9% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −45.7% | +148.3% | 5 | 40% | 0.54 | 109.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −13.3% | +17.1% | 4 | 25% | 0.36 | 24.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 0% | −$1,653.48 |
| Sideways market | 1 | 0% | −$2,642.66 |
| Falling market | 2 | 0% | −$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.
All 4 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 1 Nov 2024 70,292.00 | 11 Nov 2024 88,708.80 | 10 | −$2,642.66 |
| short | 20 Dec 2024 97,461.90 | 10 Jul 2025 113,366.00 | 202 | −$1,653.48 |
| long | 4 Dec 2025 93,429.90 | 3 Feb 2026 73,117.40 | 61 | −$2,191.92 |
| long | 26 Feb 2026 67,988.00 | 4 Jun 2026 62,042.10 | 98 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| MA Bollinger Bands + RSI this page | — | v5 strategy | −73.9% | 4 | 77.3% |
| Multi MA Trend Following Strategy Template by TradeAutomation | ema hma sma vwma wma stdev atr highest lowest | v5 strategy | +12.3% | 3 | 26.9% |
| BTC 15 min by RafaelZioni | sma ema rsi wma stdev highest lowest | v4 strategy | −25.7% | 119 | 38.9% |
| Multi Trend Cross Strategy Template by TradeAutomation | ema hma sma vwma wma stdev highest lowest | v5 strategy | +33.0% | 3 | 7.3% |
| MZ SRSI Strategy V1.0 by MightyZinger | ema sma highest lowest stdev rsi | v4 strategy | No trades on this market | ||
| Bear & Bull Zone Signal Strategy by Solutions1978 | rsi ema highest lowest sma vwma | 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.
- 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.
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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 84 ms | With a workaround 1,000 bars in 198 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 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)