ScriptingHow scripts are evaluatedReferencing previous bars

Referencing previous bars

Put an index in square brackets after a value to read what that value was on an earlier bar.

indicator("Close change")

plot(close - close[1])

The suffix attaches to a variable, to a function call or to a parenthesised expression.

The index is an expression

The index need not be a literal. Any expression that yields an index will do.

int back = 3
float earlier = close[back]

A negative index is rejected.

The same brackets build a tuple

Square brackets are also the tuple form, so the same punctuation means two things. Position decides which: a suffix indexes, a standalone bracket list builds a tuple.

float previous = close[1]

return [high, low]

The first line indexes. The second builds a tuple.

How far back

A script can look back at most 500 bars.

The limit is enforced while the script runs, not when it is checked. A script that validates cleanly can still fail on this once it is evaluated. The error names the function that asked for the out-of-range bar.

What this page does not tell you

This page does not state what happens on the early bars of a chart, where fewer than the requested number of earlier bars exist.

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