# 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:

Interactive: a 12-bar stepper. Pine executes the script once per bar, left to right. On each bar, close is that bar's close and close[1] is the previous bar's close (na on the first bar). A variable declared with var keeps its value from the previous bar; a plain variable is recalculated from scratch on every bar. ta.sma(close, 3) is na until three 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.

```pine
//@version=6
indicator("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)` (gives `0`) or `nz(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.

```pine
//@version=6
indicator("Counting up bars")
var int ups = 0
if close > open
    ups += 1
plot(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.

> [!WARNING]
> Logic that looks ahead (for example `close[-1]`, or `request.security` with lookahead) can look perfect on history and never happen live. If a backtest looks too good, check for this first.
