Documentation/AlgoCode/Function reference

state

Remember a value from bar to bar.

Reference/Language/Language

state name = expression

Ordinary assignments such as fast = ema(9) are recalculated on every bar. state keeps a value until a when rule changes it. The starting expression runs on the first bar only. Each later bar begins with the previous bar's value. Assign the name inside when to update the current bar. state name = … is the declaration. A line that is only state = 1 is still a normal variable named state.

Return value

Series

Note

  • Values are causal: bar N cannot see bar N+1.
  • A when condition sees the value carried into the bar. Assignments update that bar for later bars.
  • long / flat on the entry bar still describe the position at the start of the bar.
  • max skips na. Use replaceMissing(name, high) when the stored value may be na.
  • Each script run has its own state. It is not shared across symbols or timeframes.
  • Declare state at the top of the script, not inside when or a function.

Example

state highestSinceEntry = na

when close > open and flat
  buy
when long
  highestSinceEntry = max(replaceMissing(highestSinceEntry, high), high)
plot highestSinceEntry as "Highest since entry"

See also