Declares a variable that is set once, on the first bar, and then keeps its value from bar to bar until you reassign it.
Without var, a variable is created fresh on every bar, so total = 0.0 is 0.0 each time the script runs. With var, the initialisation runs only on the first bar, and the variable carries its value forward: var float total = 0.0, then total += volume on a later bar adds to what was there.
Reassign a var variable with := inside your logic. The var initialiser only decides the starting value. It can hold any type, including arrays, maps and objects, which is the usual way to keep a list or a drawing across bars.
Syntax
var variable_name = expressionRemarks
- On a live bar, the value rolls back at every tick to what it was when the bar opened, then the script runs again. Changes made during the bar are discarded and rebuilt, which keeps results consistent with history. varip skips the rollback.
- Variables that are drawings or collections hold a reference: var label l = na then l :=
label.new(...)keeps one label alive across bars. - On Sidechair: var variables keep their value across bars, and the live bar is rolled back and rerun on each update.
Example
//@version=6
indicator("Var")
var float cumulative = 0.0
var int upBars = 0
cumulative += close - open
if close > open
upBars += 1
plot(cumulative, "Cumulative body", color.blue)
plot(upBars, "Up bars so far", color.green)See also
Runs on Sidechair