Start
How a script runs
Pine runs your whole script once per bar, oldest to newest. Series, history references, var and na all follow from that.
The single idea behind Pine: your script runs once for every bar on the chart, starting at the oldest and ending at the newest. On each run, close, open, high, low and volume hold that bar's values. Every variable you compute becomes a series: one value per bar.
Step through it yourself:
//@version=6indicator("Bar by bar")up = close > openvar count = 0 // kept between barsn = 0 // starts again each barif upcount += 1n += 1avg = ta.sma(close, 3)
| Variable | On this bar | Why |
|---|---|---|
| bar_index | 0 | which bar is executing |
| close | 1.0848 | this bar's close |
| close[1] | na | one bar back; na on the first bar |
| up | true | recomputed every bar |
| count | 1 | var: survives to the next bar |
| n | 1 | no var: back to 0 every bar |
| avg | na | na until 3 bars exist |
History with []#
x[1] is the value x had one bar ago, x[2] two bars ago, and so on. It works on any series, including ones you compute.
//@version=6indicator("Bar-to-bar change")change = close - close[1]plot(change, "Change", style = plot.style_histogram, color = change >= 0 ? color.teal : color.red)On the very first bar there is no previous bar, so close[1] is na and so is change.
na: no value yet#
na means "no value". It appears when you look further back than the chart goes, and while an average is still warming up: ta.sma(close, 50) is na for the first 49 bars. na spreads through arithmetic: na + 1 is na.
- Test for it with
na(x). - Replace it with
nz(x)(gives0) ornz(x, fallback). - A plot simply leaves a gap where the value is
na.
var: keep a value between bars#
A plain declaration runs again on every bar, so the variable starts fresh. var declares it once, on the first bar, and keeps whatever you assign afterwards.
//@version=6indicator("Counting up bars")var int ups = 0if close > open ups += 1plot(ups, "Up bars so far", color = color.teal)Without var, ups would be 0 or 1 on every bar, never a running total.
The current bar#
On a live chart the newest bar is still forming. The script runs again as its price changes, so values on the last bar can move until it closes. Signals that must not change after they appear should check barstate.isconfirmed, which is true only once a bar has closed.