VolBands
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © danilogalisteu
//@version=4
study("VolBands", overlay=true, precision=3)

PerVol = input(10, "Vol Period", minval=1)
PerPrd = input(7, "Prd Period", minval=1)
PerTrd = input(15, "Trade Period", minval=1)
MulTrd = input(0.5, "Trade Multiplier", minval=0.0, step=0.1)
PerTrn = input(63, "Trend Period", minval=1)
MulTrn = input(4.0, "Trend Multiplier", minval=0.0, step=0.1)
useDay = input(false, "Show daily ranges and levels on all timeframes", type=input.bool)


f_VolYangZhang(period) =>
    k = 0.34 / ( 1.34 + (period + 1) / (period - 1))
    
    No = log(open) - log(close[1])  // normalized open
    Nu = log(high) - log(open)      // normalized high
    Nd = log(low) - log(open)       // normalized low
    Nc = log(close) - log(open)     // normalized close
    
    Noavg = 1 / period * sum(No, period)
    Ncavg = 1 / period * sum(Nc, period)
    
    Vo  = 1 / (period - 1) * sum(pow((No - Noavg),2), period)
    Vc  = 1 / (period - 1) * sum(pow((Nc - Ncavg),2), period)
    Vrs = 1 / period * sum((Nu * (Nu - Nc) + Nd * (Nd - Nc)), period)
    
    Vyangzhang = sqrt(Vo + k * Vc + (1 - k) * Vrs) * 100 * sqrt(252)


f_TrendMagic(PeriodCCI, PeriodATR, CoeffATR) =>
    atr  = sma(tr, PeriodATR) * CoeffATR
    upT  = low  - atr
    dnT  = high + atr
    cciT = cci(close, PeriodCCI)
    
    level = ohlc4
    level := cciT >= 0 ? (upT > nz(level[1]) ? upT : (level[1])) : (dnT < nz(level[1]) ? dnT : (level[1]))


trade_level = security(syminfo.tickerid, "1D", f_TrendMagic(PerTrd, PerTrd, MulTrd), barmerge.gaps_off, barmerge.lookahead_on)
trend_level = security(syminfo.tickerid, "1D", f_TrendMagic(PerTrn, PerTrn, MulTrn), barmerge.gaps_off, barmerge.lookahead_on)
band = security(syminfo.tickerid, "1D", f_VolYangZhang(PerVol) / 100.0 * sqrt(PerPrd / 252), barmerge.gaps_off, barmerge.lookahead_on)

if not useDay
    trade_level := f_TrendMagic(PerTrd, PerTrd, MulTrd)
    trend_level := f_TrendMagic(PerTrn, PerTrn, MulTrn)
    band := f_VolYangZhang(PerVol) / 100.0 * sqrt(PerPrd / 252)

trade_color = close > trade_level ? color.green : close < trade_level ? color.red : color.yellow
trend_color = close > trend_level ? color.green : close < trend_level ? color.red : color.yellow

plot(trade_level * exp(-band), color=color.fuchsia, linewidth=2, title="BRR")
plot(trade_level * exp( band), color=color.fuchsia, linewidth=2, title="TRR")
plot(trade_level, color=trade_color, linewidth=1, title="Trade level")
plot(trend_level, color=trend_color, linewidth=3, title="Trend level")
