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

//@version=5
indicator("Realtime CVD")
linestyle = input.string(defval='Candle', title='Style', options=['Candle', 'Line'])

varip buyvol = 0.0
varip sellvol = 0.0
varip lastprice = 0.0
varip lastvolume = 0.0
varip cumdelta = 0.0
varip o_ = 0.0
varip c_ = 0.0
varip h_ = 0.0
varip l_ = 0.0

if barstate.isrealtime and lastvolume != volume
    buyvol += close > lastprice ? (volume-lastvolume) : close == lastprice ? (volume-lastvolume)*0.5 : 0
    sellvol += close < lastprice ? (volume-lastvolume) : close == lastprice ? (volume-lastvolume)*0.5 : 0
    lastprice := close
    lastvolume := volume

c_ := buyvol-sellvol + nz(c_[1])
o_ := c_[1]
h_ := buyvol-sellvol > 0 ? o_ + sellvol : c_ + sellvol
l_ := buyvol-sellvol > 0 ? c_ - buyvol : o_ - buyvol

if barstate.isnew
    lastprice := close
    lastvolume := volume
    buyvol := 0
    sellvol := 0

plot(buyvol, color=color.new(color.teal, 30), style=plot.style_columns, title="⇧ Buyvol", display = display.none)
plot(-sellvol, color=color.new(color.red, 30), style=plot.style_columns, title="⇩ Sellvol", display = display.none)
plot(buyvol-sellvol, color=color.new(color.white, 20), style=plot.style_columns, title="Delta", display = display.none)
plot(c_, title="Cum Δ", color=color.new(color.yellow, 0), display = display.none)
colo = buyvol-sellvol > 0 ? color.new(color.teal, 30) : color.new(color.red, 30)
plotcandle(o_, h_, l_, c_, color=colo, title="Cum Δ candle", wickcolor = color.new(color.white, 100))