ATR vs Daily Delta
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © seancsnm

//@version=4
study("ATR vs Daily Delta")
atr_length = input(14, minval=1)
num_devs = input(1.0, minval=0.0)
normalize = input(false)
show_minmax = input(true)
show_std_dev_bands = input(true)

// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350

diff = close > close[1] ? max(high-low, high-close[1]) : min(low-high, low-close[1])
TR = normalize ? (diff) / close[1] : diff
//var d = 0.0
var accum_pos = 0.0
var pos_days = 0
var accum_neg = 0.0
var neg_days = 0

//get means
for i = 0 to atr_length-1
    //d := close[i] - close[i+1]

    if nz(TR[i], 0) > 0
        accum_pos := accum_pos + nz(TR[i], 0)
        pos_days := pos_days + 1
    else
        accum_neg := accum_neg + nz(TR[i], 0)
        neg_days := neg_days + 1
    
avg_pos = accum_pos / pos_days
avg_neg = accum_neg / neg_days
avg_neutral = (avg_pos + avg_neg) / 2
accum_pos := 0
accum_neg := 0


var res_pos = 0.0
var res_neg = 0.0

//get standard deviations
for i = 0 to atr_length-1
    if nz(TR[i], 0) > 0
        res_pos := res_pos + pow((nz(TR[i], 0)-avg_pos), 2)
    else
        res_neg := res_neg + pow((nz(TR[i], 0)-avg_neg), 2)

std_pos = sqrt(res_pos/pos_days)
std_neg = sqrt(res_neg/neg_days)

//reset variables
pos_days := 0
neg_days := 0
res_pos  := 0
res_neg  := 0

atr_val = atr(atr_length)


plot(TR, title="Daily Deltas", style=plot.style_columns, color=(TR>=0 ? (TR[1] < TR ? col_grow_above : col_fall_above) : (TR[1] < TR ? col_grow_below : col_fall_below)), transp=0)
plot(show_std_dev_bands ? num_devs*std_pos + avg_pos : na, color=color.teal)
plot(show_std_dev_bands ? -num_devs*std_neg + avg_neg: na, color=color.maroon)
//plot(atr_val)
plot(avg_pos, color=color.green)
plot(avg_neg, color=color.red)
//dd = plot(TR)
plot(avg_neutral, color=color.gray)


max_TR = TR
max_TR := max(nz(max_TR[1], 0.0), TR)
min_TR = TR
min_TR := min(nz(min_TR[1], 0.0), TR)
//if max_TR[1] > TR
//    max_TR := max_TR[1]
//plotchar(max_TR, "max_TR", "", location=location.top)
plot(show_minmax ? max_TR : na, color=color.green)
plot(show_minmax ? min_TR : na, color=color.red)

//if barstate.islast
//plotchar(max_TR, "Max TR", location.top)