Cumulative Delta
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © noop42

//@version=5
indicator("Cumulative Delta")

reset_everyday = input.bool(true, "Reset Delta everyday", group="Options")

show_high_low = input.bool(true, "Show Daily High and Low levels", group="Options")
show_histogram = input.bool(true, "Show histogram", group="Options")
show_candles = input.bool(true, "Show candles", group="Options")
show_moving_average = input.bool(true, "Show moving average", group="Options")
ma_len = input.int(50, "Moving average Length", group="Parameters")

ma_color = input.color(color.white, "Moving average color", group="Display colors")
hist_neg_high = input.color(#383838, "Higher negative delta", group="Display colors")
hist_neg_low = input.color(#636161, "Lower negative delta", group="Display colors")
hist_pos_high = input.color(#636161, "higher positive delta", group="Display colors")
hist_pos_low = input.color(#383838, "Lower positive delta", group="Display colors")
reset_color = input.color(color.white, "Reset mark color", group="Display colors")
up_candle = input.color(color.lime, "Up volume", group="Display colors")
down_candle = input.color(#ff0000, "Down volume", group="Display colors")

var counter = 1
var daily_lowest = 0.0
var daily_highest = 0.0

reset_delta = ta.change(dayofweek)
var cvd = 0.0
bot = 0.0
top = 0.0
col = #00000000

if reset_everyday and reset_delta
    daily_lowest := bot
    daily_highest := top
    cvd := 0.0
    counter := 1
    
if open < close
    bot := cvd
    top := cvd+volume
    col := color.lime
    cvd += volume
else
    top := cvd
    bot := cvd-volume
    col := #ff0000
    cvd -= volume

bar_col = (cvd > 0) ? (cvd > cvd[1] ? hist_pos_high : hist_pos_low) : (cvd > cvd[1] ? hist_neg_high: hist_neg_low)
plot(show_histogram ? cvd : na, style=plot.style_columns, color=bar_col)
bgcolor(reset_everyday and reset_delta ? reset_color : na)

plotcandle(show_candles ? top : na, show_candles ?  top : na, show_candles ? bot : na, show_candles ? bot : na, color=col, bordercolor=col)

if top > daily_highest
    daily_highest := top
if bot < daily_lowest
    daily_lowest := bot
plot(show_high_low ? daily_highest : na, color=up_candle)
plot(show_high_low ? daily_lowest : na, color=down_candle)
m = ta.sma(cvd, (counter < ma_len ? counter : ma_len))
plot(show_moving_average ? m : na, color=color.white)
counter += 1