How to keep a running total across bars
Declare the total with static and add to it with :=. An ordinary
declaration is made again on every bar, so an ordinary total starts again on
every bar.
indicator("Running total of volume", "cumvol", false)
static float total = 0.0
total := total + volume
plot(total, title = "Total", color = color.blue)static is the only keyword that makes a value persist across bars. A
declaration opening var does not compile.
If the total should reset each session
Test session.isfirst and seed from the bar’s own value instead of from the
previous total. That is the same shape the built-in cumulative delta uses: it
seeds from zero on a session’s first bar and from the previous bar otherwise.
indicator("Volume so far this session", "sessvol", false)
static float total = 0.0
if session.isfirst {
total := volume
} else {
total := total + volume
}
plot(total, title = "Session volume", color = color.blue)If you are accumulating a plain series
talib.cum accumulates a series as the script advances, with no length
argument and no declaration of your own.
talib.cum(series float source) → series floatindicator("Cumulative volume", "cum", false)
plot(talib.cum(volume), title = "Total", color = color.blue)Reach for it in place of a static total unless you need the reset above:
talib.cum takes no condition, so you cannot restart it.
If the total you want is cumulative delta
Do not write it yourself. orderflow.cvd adds each bar’s delta to a running
total, restarts from zero on the first bar of a session, and leaves the total
unchanged on a bar whose delta is na rather than breaking it.
orderflow.cvd() → series intindicator("Cumulative delta", "cvd", false)
plot(orderflow.cvd(), title = "CVD", color = color.blue)The failure to watch for
Every orderflow value reads na on a bar with no footprint data behind it. A
total of your own that adds orderflow.delta directly will carry that na
forward. Guard the addition, or use orderflow.cvd, which already does.
See Values that persist across bars and Orderflow.