Strategy · Pine Script v5 · Own pane

Bollinger Bands %B - Belthold & Inner Candles

by hasnocool

This strategy combines Bollinger %B settings with belthold and inner-candle color toggles and sizes orders as a percentage of equity.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code120
Settings22inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

120 lines of Pine Script v5 from Bollinger Bands -B - Belt Holds & Inner Candles.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Bollinger Bands -B - Belt Holds & Inner Candles.pine
//@version=5
//Created by Tathal
//Credit to Duyck for the ATR function,  mischa23v for testing, review and clean up
strategy(title='Bollinger Bands %B - Belthold & Inner Candles', shorttitle='%BBHIC', format=format.price, precision=2, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
/// Date Functions for backtesting
startDate = input.int(title='Start Date', defval=1, minval=1, maxval=31)
startMonth = input.int(title='Start Month', defval=1, minval=1, maxval=12)
startYear = input.int(title='Start Year', defval=2021, minval=1800, maxval=2100)
endDate = input.int(title='End Date', defval=31, minval=1, maxval=31)
endMonth = input.int(title='End Month', defval=12, minval=1, maxval=12)
endYear = input.int(title='End Year', defval=2021, minval=1800, maxval=2100)
/// Look if the close time of the current bar
/// falls inside the date range
inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)
trailType = input.string('modified', 'Trailtype', options=['modified', 'unmodified'], tooltip = 'Change the stoploss ATR settings')
ATRPeriod = input(28, 'ATR Period', tooltip = 'Change the trailing ATR STOPLOSS period')
ATRFactor = input(5, 'ATR Factor', tooltip ='Change the trailing ATR STOPLOSS Factor')
norm_o = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, open)
norm_h = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, high)
norm_l = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, low)
norm_c = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, close)
//}
//.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:.
//---------------------TRUE RANGE CALCULATIONS---------------------------------
//.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:.
/////////// TRUE RANGE CALCULATIONS /////////////////
HiLo = math.min(norm_h - norm_l, 1.5 * nz(ta.sma(norm_h - norm_l, ATRPeriod)))
HRef = norm_l <= norm_h[1] ? norm_h - norm_c[1] : norm_h - norm_c[1] - 0.5 * (norm_l - norm_h[1])
LRef = norm_h >= norm_l[1] ? norm_c[1] - norm_l : norm_c[1] - norm_l - 0.5 * (norm_l[1] - norm_h)
trueRange = trailType == 'modified' ? math.max(HiLo, HRef, LRef) : math.max(norm_h - norm_l, math.abs(norm_h - norm_c[1]), math.abs(norm_l - norm_c[1]))
//}
loss = ATRFactor * ta.ema(trueRange, ATRPeriod)
Up = norm_c - loss
Dn = norm_c + loss
TrendUp = Up
TrendDown = Dn
Trend = 1
TrendUp := norm_c[1] > TrendUp[1] ? math.max(Up, TrendUp[1]) : Up
TrendDown := norm_c[1] < TrendDown[1] ? math.min(Dn, TrendDown[1]) : Dn
Trend := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1] ? -1 : nz(Trend[1], 1)
trail = Trend == 1 ? TrendUp : TrendDown
ex = 0.0
ex := ta.crossover(Trend, 0) ? norm_h : ta.crossunder(Trend, 0) ? norm_l : Trend == 1 ? math.max(ex[1], norm_h) : Trend == -1 ? math.min(ex[1], norm_l) : ex[1]
sl_inp = input(50.0, title='Percentage Stop Loss')/100
tp_inp = input(15.0, title='Percentage Take Profit %')/100
 
stop_level = strategy.position_avg_price * (1 + sl_inp)
take_level = strategy.position_avg_price * (1 - tp_inp)
lstop_level = strategy.position_avg_price * (1 - sl_inp)
ltake_level = strategy.position_avg_price * (1 + tp_inp)
/// Toggles
show_bar_color = input(title="Show Candlestick Pattern Colors on Bar?", defval=true)
show_bg_color = input(title="Show Candlestick Pattern Colors on Background?", defval=true)
/// BB%B Calculation
length = input.int(20, minval=1)
src = input(close, title='Source')
mult = input.float(2.0, minval=0.001, maxval=50, title='StdDev')
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
bbr = (src - lower) / (upper - lower)
plot(bbr, 'Bollinger Bands %B', color=color.new(#26A69A, 0), style=plot.style_columns)
/// Overbought / Oversold Line Declaration & Painting
inputoverbought = input(1)
inputoversold = input(0)
inputbuy = input(.3)
inputsell = input(.7)
band1 = hline(inputoverbought, 'Overbought', color=#787B86, linestyle=hline.style_dashed)
band0 = hline(inputoversold, 'Oversold', color=#787B86, linestyle=hline.style_dashed)
bandsell = hline(inputsell, 'Slightly Overbought', color=#787B86, linestyle=hline.style_dashed)
bandbuy = hline(inputbuy, 'Slightly Oversold', color=#787B86, linestyle=hline.style_dashed)
fill(band1, band0, color=color.rgb(38, 166, 154, 90), title='Background')
fill(band1, bandsell, color=color.rgb(255, 0, 0, 90), title='Background')
fill(band0, bandbuy, color=color.rgb(0, 255, 0, 90), title='Background')
/// Inside candle function, default return false, else if inside candle, return true.
icreturn = false
innercandle = if high < high[1] and low > low[1]
    icreturn := true
    icreturn
    
// Bullish Belthold
lowerb = ta.lowest(10)[1]
lbelthold = low == open ?  open < lower ? open < close ? close > ((high[1] - low[1]) / 2) + low[1] :na  : na : na
barcolor(lbelthold and show_bar_color? color.new(color.yellow,0) : na)
bgcolor(lbelthold and show_bg_color ? color.new(color.yellow,90) : na)
// Bearish Belthold
upperb = ta.highest(10)[1]
sbelthold = high == open ?  open > upperb ? open > close ? close < ((high[1] - low[1]) / 2) + low[1] : na : na : na
barcolor(sbelthold and show_bar_color ? color.new(color.purple,0) : na)
bgcolor(sbelthold and show_bg_color ? color.new(color.purple,90) : na)
/// paint inside candles
barcolor(icreturn and show_bar_color ? color.new(color.white,0) : na)
bgcolor(icreturn and show_bg_color ? color.new(color.white,90) : na)
/// long and sell conditions
long = bbr < inputbuy and (icreturn or lbelthold)
sell = bbr > inputsell and (icreturn or sbelthold)
short = bbr > inputsell and (icreturn or sbelthold)
exit = bbr < inputbuy and (icreturn or lbelthold)
// atr or % based stop loss / take profit
stoplosschoiceinput = input.string(title="Stoploss Type :", defval="ATR", options=["ATR", 
                                                                  "Percentage" ])
takeprofitchoiceinput = input.string(title="Take Profit Type :", defval="ATR", options=["ATR", 
                                                                  "Percentage" ])
longstoplosscondition = stoplosschoiceinput == "ATR" ? trail : lstop_level
shortstoplosscondition = stoplosschoiceinput == "ATR" ? trail : stop_level
longtakeprofitcondition = takeprofitchoiceinput == "ATR" ? ex : ltake_level
shorttakeprofitcondition = takeprofitchoiceinput == "ATR" ? ex : take_level
/// order logic
if inDateRange
    strategy.entry('long', strategy.long, when=long)
if inDateRange and strategy.position_size > 0
    strategy.exit("close", "long", profit=longtakeprofitcondition, stop=longstoplosscondition)
    strategy.close("close", when=sell)
if inDateRange
    strategy.entry('short', strategy.short, when=short)
if inDateRange and strategy.position_size > 0
    strategy.exit("cancel", "short", profit=shorttakeprofitcondition, stop=shortstoplosscondition)
    strategy.close("close", when=exit)
Expand (167 lines)

Overview

The user sets band length, source, and deviation, plus buy, sell, overbought, and oversold levels. Exits use either a modified or standard ATR trail and percentage stop-loss and take-profit prices based on the average entry. A date window restricts when orders are allowed. Optional colors mark pattern bars and the background in a separate pane. Exact entry rules are not shown in the provided code.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

Separate pane below the chart

Category

Volatility & bands, Candlestick patterns

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Start Dateint1startDate
Start Monthint1startMonth
Start Yearint2021startYear
End Dateint31endDate
End Monthint12endMonth
End Yearint2021endYear
TrailtypestringmodifiedtrailType
ATR Periodint28ATRPeriod
ATR Factorint5ATRFactor
Percentage Stop Lossfloat50.0sl_inp
Percentage Take Profit %float15.0tp_inp
Show Candlestick Pattern Colors on Bar?booltrueshow_bar_color
Show all 22 settings
SettingTypeDefaultVariable
Show Candlestick Pattern Colors on Background?booltrueshow_bg_color
lengthint20length
Sourcesourceclosesrc
StdDevfloat2.0mult
inputoverboughtint1inputoverbought
inputoversoldint0inputoversold
inputbuyfloat.3inputbuy
inputsellfloat.7inputsell
Stoploss Type :stringATRstoplosschoiceinput
Take Profit Type :stringATRtakeprofitchoiceinput
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

Exceeded Candle [Alorse] is a mean-reversion strategy that identifies candlestick engulfing patterns combined with Bollinger Bands filters. It enters a long position when a green candle surpasses the body of the previous red candle while price is below the mid

Strategy v4 Mean reversionCandlestick patterns
Updated 2 months ago · None stated GitHub repository of Exceeded candle [Alorse]
218 stars

This strategy identifies trade opportunities based on candlestick wick imbalances relative to the Average True Range. It enters positions when candle wicks exceed defined thresholds and filters out doji candles using a minimum body ATR requirement. Exits are h

Strategy v6 Candlestick patternsVolatility & bands Repaints
Updated 3 months ago · None stated GitHub repository of Super Negative R:R Wick Strategy

This tutorial strategy demonstrates lower-timeframe multi-timeframe functionality in Pine Script using request.security_lower_tf. It evaluates synthetic lower-timeframe 1-minute close prices within each chart bar to calculate the intra-bar price range percenta

Strategy v6 Volatility & bands
Updated today · Apache-2.0 GitHub repository of PineForge MTF tutorial — lower-TF intra-bar range

EMA Ribbon MACD

by iamrichardD
57 stars

This strategy combines an EMA ribbon with MACD confirmation and plots in a separate pane. It enters when ribbon alignment, optional MACD zero or signal crosses, volume, smart-money, and multi-timeframe filters agree, then exits with percentage stop loss and ta

Strategy v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon MACD
25 stars

This Pine Script strategy calculates Bayesian probabilities of price breaking up or down relative to Bollinger Bands and a Simple Moving Average. It plots these breakout and breakdown probability lines as oscillators in a separate pane. Long entries trigger wh

Strategy v4 Oscillators & momentumVolatility & bands
Updated 6 years ago · None stated GitHub repository of Bayesian BBSMA Oscillator Strategy

Greeffer BB Strategy

by SammyEnigma
18 stars

This strategy fades Bollinger Band extremes using the close. It enters short when price crosses above the upper band and the 14-period RSI is above 70, and enters long when price crosses below the lower band and RSI is below 30. It closes half of an open short

Strategy v4 Volatility & bandsOscillators & momentum
Updated 6 years ago · None stated GitHub repository of Greeffer BB Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers