[jav] Better Bollinger Bands
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © javabgar
// @version=4
// ______________________________________________________________________________________________

study("[jav] Better Bollinger", overlay=true) 

// ______________________________________________________________________________________________
// inputs 

per = input(defval = 20    , title = "Bollinger period", type=input.integer)
sel = input(defval = "VWMA", title = "Selection of MAv", type=input.string , options = ["SMA", "EMA", "WMA", "VWMA", "RMA"])
shw = input(defval = false , title = "Show Classic BB?")
mul = input(defval = 2.00  , title = "Bollinger multip", step = 0.05)
// ______________________________________________________________________________________________
// functions 

// Moving Average Selector
MvAvg(_src, _len) => sel == "SMA" ? sma(_src, _len) : sel == "EMA" ? ema(_src, _len) : sel == "WMA" ? wma(_src, _len) : sel == "VWMA" ? vwma(_src, _len) : sel == "RMA" ? rma(_src, _len) : na

// Main function: calculates Better BBs and Classic BBs.
BBB(_src, _per) =>
    _av = MvAvg(_src, _per)         // ema of close
    _s1 = stdev(_src, _per)         // stdev of close
    _df = _src - _av                // difference between close and ema
    _s2 = stdev(_df, _per)          // stdev of that difference
    _vl = MvAvg(high - low, _per)   // ema of high-low difference
    _dn = _av - (_s1 + _s2 + _vl/2) // upper BBB  
    _up = _av + (_s1 + _s2 + _vl/2) // lower BBB
    _di = _dn + _vl/2               // inner lower BBB 
    _ui = _up - _vl/2               // inner upper BBB
    _uB = _av + mul * _s1           // upper classic BB
    _dB = _av - mul * _s1           // upper classic BB
    [_av, _up, _ui, _di, _dn, _uB, _dB]

// ______________________________________________________________________________________________
// results 
 
[av, up, ui, di, dn, uB, dB] = BBB(close, per)

// ______________________________________________________________________________________________
// plots 
 
extcol = color.new(color.red  , 00)
intcol = color.new(color.red  , 80)
avgcol = color.new(color.black, 00)
bbccol = color.new(color.blue , 00)

pav = plot(av, color=avgcol, linewidth=1)
puu = plot(up, color=extcol, linewidth=1)
pll = plot(dn, color=extcol, linewidth=1)
pul = plot(ui, color=intcol, linewidth=1)
plu = plot(di, color=intcol, linewidth=1)

fill(puu, pul, color=intcol)
fill(pll, plu, color=intcol)

puB = plot(shw ? uB : na, color = bbccol, linewidth=1)
pdB = plot(shw ? dB : na, color = bbccol, linewidth=1)

// ______________________________________________________________________________________________
 
