Skip to main content
A function that looks at earlier bars, such as talib.sma, talib.ema or talib.rsi, does not read the chart’s bars. It keeps its own history, one per place in your script where you call it (the call site), and that history grows by one entry only on the bars where the call actually runs. Its “previous bar” is the previous time the call ran. So a talib call is correct only when it runs once on every bar. A call that is skipped on some bars gives wrong numbers and no error.

Where a call is skipped

A call does not run on a bar when it sits in an if or switch block whose condition is false, in the unchosen side of c ? a : b (only one side runs; both sides of and and or always run), or in a function that is itself called on some bars only. A call in a loop body is one call site run several times a bar: the passes overwrite each other and only the last is kept. Do not call talib functions inside a loop.

Call it on every bar, then choose

Make the call at the top level, then use its result in the condition:
This is the opposite of the following script, which compiles but averages the last 20 up bars only, because the call runs on up bars only:

The same holds for your own functions

A history reference inside a function (x[1]), a talib call and a static variable all belong to the call site: two calls of one function keep separate histories, and a call skipped on some bars sees only the bars it ran on.
smooth runs on every bar, so x[1] is the previous bar.

Index

A history index counts recorded entries back. For a built-in series (close[1]) every bar is recorded; for your own variable, every bar on which the line that sets it ran (a top-level variable is set on every bar). The reach is 500 entries (see Referencing previous bars).