Examples
Session VWAP with deviation bands
A volume-weighted average price that restarts at each CME session, with bands at a chosen number of standard deviations. It shows how var keeps running totals from bar to bar and how to reset them.
indicator "Session VWAP" { overlay: true }
mult = input.float("Band width (std devs)", 1.0, min: 0.5, step: 0.5)
var pv = 0.0 // sum of price × volume
var pv2 = 0.0 // sum of price² × volume
var vol = 0.0 // sum of volume
if session.is_new {
pv = 0.0
pv2 = 0.0
vol = 0.0
}
tp = (high + low + close) / 3
pv += tp * volume
pv2 += tp * tp * volume
vol += volume
vwap = vol > 0 ? pv / vol : na
sd = vol > 0 ? sqrt(max(pv2 / vol - vwap * vwap, 0)) : na
pv_ = plot(vwap, #e8c15a, title: "VWAP", width: 2)
pu = plot(vwap + mult * sd, #e8c15a80, title: "Upper band")
pl = plot(vwap - mult * sd, #e8c15a80, title: "Lower band")
fill(pu, pl, #e8c15a10)What to notice:
varvariables keep their value from one bar to the next; plain variables (tp,vwap) are recomputed on each bar;session.is_newis true on the first bar of each CME session (18:00 New York);max(…, 0)protects the square root from tiny negative values caused by rounding.