ScriptingHow toHow to avoid a result that changes after the bar closes

How to avoid a result that changes after the bar closes

Base the result on a bar that has closed.

A value read from the bar under evaluation can still be updating: that is what barstate.isrealtime reports. Shift the read back a bar with the index suffix and the result rests on a bar that is no longer the one under evaluation.

indicator("Settled range", "settled", false)
plot(high[1] - low[1], title = "Previous bar range", color = color.blue)

The cost is one bar of delay. There is no way to have both.

If you need to know which kind of bar you are on

Read the flag rather than guessing.

FlagTrue when
barstate.isrealtimethe bar under evaluation is still updating rather than closed
barstate.ishistorythe bar under evaluation is a historical bar

If the script raises alerts

alert already behaves this way round: it fires only on realtime bars, at most once per bar, and does nothing on historical bars.

What this recipe does not tell you

It does not state the recalculation contract, because this edition does not document one. Nothing here tells you:

  • how often a script is evaluated while a bar is still updating,
  • what triggers each of those evaluations,
  • what a value read on a forming bar becomes once the bar closes,
  • or whether a script is evaluated again over bars it has already seen.

Do not infer any of it from the flags or from this page. Where a result must not move, take it from an earlier bar, as above.

See Recalculation and confirmation and Bar-by-bar evaluation.

Ready to put this into practice?
Try GoCharting Premium
Unlock advanced orderflow, market profile, options desk, and real-time data — everything you just read about, live in your charts.
Upgrade