Skip to main content
Put the number of bars back in square brackets after the value. close[1] is the close one bar before the bar the script is on; close[0] is the current bar.
The index may be a variable or any expression that gives a number, and [] works on built-in series, your own variables and call results:

How far back

  • At most 500 bars. A larger index passes the editor’s check and stops the script when it runs, with the message “The script is trying to access historical data outside allowed range (501). The allowed range is 0 to 500.” The same limit bounds the length of a talib window (talib.ema refuses a longer one when the script is added to the chart).
  • On the first bars of the chart, where fewer than n earlier bars exist, close[n] is na.

The last time something happened

To read a value from the last bar where a condition was true, or to count the bars since, use talib.valuewhen(condition, source, occurrence) (occurrence 0 is the latest, the current bar included) and talib.barssince(condition):
To keep several earlier values, put them in an array (see How to keep the last N values in an array).

The mistakes to avoid

A negative index. The compiler says: History index must be >= 0. Got -1.
Also, [] on an array is the history operator, not an element index: use array.get(a, i) (see Arrays). Square brackets after a call that returns a tuple are refused (see How to return more than one value from a function). See Referencing previous bars.