Correlated ATR Bands | Adulari
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©Adulari
// @version=5
indicator("Correlated ATR Bands | Adulari", overlay = true)

// Inputs
weight = input.int(5, title='Weight', minval=1, group='General Settings')
length = input.int(200, title='Length', minval=1, group='General Settings')
atrlength = input.int(14, title='ATR Length', minval=1, group='General Settings')
smoothing = input.int(50, title='Smoothing', minval=1, group='General Settings')
source = input(close, title='Source', group='General Settings')
multiplier = input.float(3, title='Multiplier', minval=0.1, step=0.1, group='General Settings')
inverse = input.bool(true, title='Inverse', group='Advanced Settings')
tfAdaptive = input.bool(true, title='Timeframe Adaptive', group='Advanced Settings')
tfMultiplier = input.int(15, title='Multiplier', inline='Timeframe Adaptive', group='Advanced Settings')

// Adaptive Strength
tfStrength = if tfAdaptive
    if timeframe.in_seconds(timeframe.period)/60>=60
        0.0
    else
        tfMultiplier/timeframe.in_seconds(timeframe.period)/60
else
    0.0

// Calculations
var value = 0.
atr = ta.atr(atrlength)
correlation = ta.correlation(atr, source, length)
value := correlation * atr + (1 - correlation) * nz(atr[1], atr)
flength = int(math.max(length/smoothing,2))
ma = (ta.hma((1-(correlation/100*(1+weight/10)))*(ta.sma(source+value, smoothing)+ta.sma(source-value,smoothing))/2,flength)+ta.hma(source,length)*tfStrength)/(1+tfStrength)
if inverse
    value := value/(value/multiplier/100)
svalue = ta.hma(value,length)/(math.max(tfStrength,1))
upperBand = ma+svalue*multiplier //old calculation: ta.hma(atr*multiplier+source, smoothing)
lowerBand = ma-svalue*multiplier //old calculation: ta.hma(source-atr*multiplier, smoothing)

// Colors
beColor = #675F76
buColor = #a472ff
raColor = #b4a7d6

// Plots
pMA = plot(ma, title='Moving Average', color=ma>ma[2] ? buColor : beColor, linewidth=2)
pUB = plot(upperBand, title='Upper Band', color=upperBand>upperBand[2] ? buColor : beColor, linewidth=2)
pLB = plot(lowerBand, title='Lower Band', color=lowerBand>lowerBand[2] ? buColor : beColor, linewidth=2)
fill(pMA,pLB,color=lowerBand>lowerBand[2] ? color.new(buColor,95) : color.new(beColor,95))
fill(pMA,pUB,color=upperBand>upperBand[2] ? color.new(buColor,95) : color.new(beColor,95))