ScriptingHow toHow to reference a value from a previous bar

How to reference a value from a previous bar

Put the index in square brackets after the value. close[1] is the close one bar back from the bar your script is being evaluated on.

indicator("Change since the previous bar", "chg", false)
plot(close - close[1], title = "Change", color = color.blue)

If the index is worked out rather than fixed

The index is an expression, so it need not be a literal.

int back = 3
float earlier = close[back]

A negative index is rejected.

If you are also building a tuple in the same script

Square brackets do two jobs, and position decides which. Written after something they index. Written on their own they build a tuple. Read your own line before assuming which one you wrote.

How far back you may go

At most 500 bars.

The limit is checked while the script runs, not while it is validated, so a script that passes the editor can still stop on this. The diagnostic names the function that asked for the out-of-range bar.

Nothing here tells you what an index reads on the early bars of a chart, where fewer earlier bars exist than you asked for. See Referencing previous bars.

Ready to put this into practice?
Try GoCharting Premium
Unlock advanced orderflow, market profile, options desk, and real-time data — everything you just read about, live in your charts.
Upgrade