millionchart
فارسی

Calls that keep a state

Some calls remember what they saw on earlier bars. This page shows what that means for sessions and for the place where such a call may stand.

A call that keeps a state (a moving average, a request, a session value) has one state for each place it is written, and the state advances when execution reaches that place. The diagnostics E3302 and W3302 explain what happens when such a call stands where it might not run.

Session highs#

Sessions with a zone and a value that restarts with each session.

Cuprel
// A trading session is two times and a zone. `state session` keeps a value that restarts at the start of each session,
// so this draws the high of the London session so far, and the high of the New York session so far.
indicator "Session highs"
    edition = 1
    display = price

session london = 08:00 .. 16:30 @ "Europe/London"
session newyork = 09:30 .. 16:00 @ "America/New_York"
state session london london_high = high
state session newyork newyork_high = high
if london.active
    london_high = math.max(london_high, high)
if newyork.active
    newyork_high = math.max(newyork_high, high)
plot(london_high, name = "London high so far", color = color.green)
plot(newyork_high, name = "New York high so far", color = color.orange)

One state for each call#

One function called twice: each call site keeps its own state, shown by a difference of exactly zero.

Cuprel
// Every place where a call that keeps a state is written has a state of its own. smooth() is one function called twice, with two different series,
// and each call keeps its own running average: the difference to the same average written out directly is zero on every bar.
indicator "One state for each call"
    edition = 1
    display = pane

fn smooth(source: float, length: int): float = tech.ema(source, length)

let from_close = smooth(close, 10)
let from_open = smooth(open, 10)
plot(from_close - tech.ema(close, 10), name = "Close, function minus direct", color = color.green)
plot(from_open - tech.ema(open, 10), name = "Open, function minus direct", color = color.red)
plot(from_close - from_open, name = "Close average minus open average", color = color.gray)