Per-bar scripts

View as MarkdownOpen the editor

A per-bar script computes each bar from that bar alone: its candle, its inputs and the settings.

When the compiler can prove that, the chart computes only the newly loaded bars on a pan-back and keeps every bar it already drew; when it cannot, every pan-back runs the indicator again over the whole loaded history. This page shows what the proof accepts, what it refuses, why rolling math such as a moving average is a different kind of script rather than a mistake, how rolling math built from finite windows still skips the whole history (it settles within W bars), how a file keeps a second mode behind one setting out of that proof (a mode guard), and where the verdict shows. There is nothing to declare: the compiler reads the code and decides.

What a pan-back recomputes

The chart runs an indicator over the bars it has loaded. Panning back loads earlier bars, and the indicator has to cover them too. Most scripts cannot reuse what they already drew: a running total, a moving average or a bar counter starts at the first loaded bar, so bars added in front can change the values after them, and the chart runs the indicator again from the new first bar to the newest.

A per-bar script carries nothing from one bar to the next. A bar's value is the same whether the run started a thousand bars earlier or at that bar, so the chart runs only the bars that just loaded and keeps the rest:

text
loaded:            bar 5,000 ............................. newest
pan back loads:    bar 1 ... bar 4,999

whole history:     run bar 1 ................................... newest
per-bar script:    run bar 1 ... bar 4,999    keep bar 5,000 ... newest

The forming bar, live updates and a changed setting run as they do for any indicator (Execution model).

What the proof accepts

The compiler proves a file per bar when everything onBar() reads comes from the bar at hand or from a value fixed before the first bar, and every form in the file is one of these:

  • Number and boolean locals with a starting value. const x = bar.close() * 2.0;, let n = 0; or let up = bar.close() > bar.open(); inside onBar() or a helper: made when the bar starts, gone when it ends. A local declared without a value, a string and an object (new Sma(14) included) refuse.
  • Module constants. A top-level const holding a number or a boolean, from literals, arithmetic, earlier constants and the kit helpers below (const TUPLE = 3;, const SPAN = TUPLE * 2 + 1;, const STEP = roundTo(0.125, 2);); Math is refused there. A top-level table of numbers (const WEIGHTS = [0.5, 0.3, 0.2];), read only by index and .length.
  • Module scalars set once in onStart(). A top-level let holding a number or a boolean, given a constant starting value and assigned only in onStart() from settings, constants, Math, the kit helpers below and arithmetic (depth = p_depth_pct() / 100.0;), never from a module let; onBar() reads it and never writes it. onStart() holds locals and assignments only, so a choice there is a ternary, not an if.
  • Scratch made inside onBar(). A local StaticArray of numbers (const sums = new StaticArray<f64>(8);): filled, read and written by index, its .length, and passed to a helper that takes the same shape.
  • This bar's readers. bar.open(), bar.high(), bar.low(), bar.close(), bar.volume() and bar.time(); a feed's in_<name>(); a number or boolean setting's p_<name>() and pb_<name>() (a list setting's reader refuses); and a celled input's count, in_<name>_cells(), with its view read by index through a local const (const cells = in_<name>_view();) (Celled sources).
  • Plain functions. Your own functions that take numbers (or a local StaticArray) and return a number or a boolean; isNaN, isFinite, NaN and Infinity; the Math functions abs, floor, ceil, round, trunc, sqrt, pow, min, max, log, log2, log10, exp, sign, hypot, sin, cos, tan, asin, acos, atan and atan2, and no other Math member (Math.PI, Math.random() and Math.log1p() refuse); and these kit helpers: the colour helpers rgba, rgb, isThemeToken, alpha, mix, fromGradient, lighten, darken, red, green, blue, opacity, transparency, toPacked and fromPacked; the session helpers multiHas, unitToPrice, inSession, sessionDayOpen, sessionTradeDate, sessionWeekOpen and sessionGapBefore; the size helpers sizeUnit and notional; delta, deltaPct, roundTo, roundToTick and epochSec; and the candle tests candles.doji, hammer, shootingStar, bullishEngulfing, bearishEngulfing, insideBar, outsideBar and pinBar. Any other kit function, fromHex for one, refuses.
  • What the chart draws from the bar. out_<name>(value) written from the values above, and what reads only outputs or the bar's cells: lines, bands (range), boxes and segments, a render.legend entry over an output, a render.hud card over outputs, and a heatmap over the bar's own celled block.

What the proof refuses

Anything that carries a value from one bar into the next, or reads where the bar stands in the run, refuses the proof. The compile names the first one it meets, with its line when it has one:

  • A module variable written in onBar(). A flag, a counter, a running total or the previous close: prev = bar.close(); inside onBar() hands the bar to the next one.
  • An object. new Sma(...), new Ema(...), Cvd, History, List and every other kit class keep earlier bars by design, wherever they are made, and a class of your own refuses too.
  • A module-level array. A StaticArray at the top of the file is memory every bar writes and the next bar reads (a ring buffer, a window): make scratch inside onBar() instead. A table that is written, filled or passed to a helper refuses the same way.
  • Drawings. A drawing handle used in code (draw.label(...), draw.line(...)), a handles.* declaration and a draw.* declaration all live across bars.
  • Text. A string slot and its senders (str_<slot>, the sb_* builders), a string in code, and a text setting's words (pt_<name>()).
  • Where the bar stands. bar.isLast() and bar.count() answer by how many bars the run holds.
  • An input that reaches beyond the bar. An input with its own interval or view, a candles or intrabar stream, a tape history, and a feed beside the chart's own candles that carries its last value into a bar with no reading. Carrying is the default for such a feed: declare missing: "nan" or "zero" on it to keep it per bar (The missing policy).
  • Declarations that draw or act across bars. The renderers render.text, render.label, render.table, render.shape, render.stats_row, render.bgcolor and render.barcolor; frames and the levels and panels they feed; a strategy; an alert; and an output drawn at another bar (displacement_bars).
  • A form outside the proof. A switch (write if and else), an if in onStart() (a mode guard's dispatch aside), an arrow function, an Array written by index (use a StaticArray), a helper that returns an array, a view held in a let, an onReset() with a body, the four-function form, and a second file beside the indicator.

Rolling math is a different kind

Some math needs earlier bars by definition:

  • a moving average at a bar averages the bars before it;
  • a cumulative delta adds the bar's delta to the total of every bar before it;
  • a session profile folds every bar since the session opened;
  • swings, zones and divergences remember where price has been.

These scripts are right to keep state, in a kit class or in module variables, and the per-bar proof is right to refuse them. That is not a mistake to fix, and rolling math bent into another shape to win the proof only gets harder to read. Reach for the per-bar shape when the math is per bar to begin with: a reading of the bar's own candle, book, profile or trades. Rolling math whose every piece of memory has a finite window, such as a moving average, settles within a known number of bars, and the chart uses that (next section); the rest runs again over the whole loaded history on a pan-back, as it always has. The verdict covers the whole file, so one value that never settles anywhere in it makes every pan-back recompute the history.

Rolling math that settles within W

A 20-bar moving average forgets: at any bar it reads that bar and the 19 before it, and nothing earlier. When every piece of memory in a file is an instance of a kit class with a finite window, the compiler adds the windows up into W, the number of earlier bars a fresh run needs before its values match a run from the first bar, bit for bit. On a pan-back the chart then starts a fresh run W bars before the newly loaded bars, drops those W rows, and keeps every bar it already drew:

text
loaded:            bar 5,000 ............................. newest
pan back loads:    bar 1 ... bar 4,999

whole history:     run bar 1 ................................... newest
settles within W:  run W bars before bar 1 ... bar 4,999    keep bar 5,000 ... newest
                   (the W running-start rows are dropped)

Only finite-window kit classes qualify today: Sma, Wma, Hma, Vwma, Alma, Swma, Linreg, Sum, Median, Percentile, Variance, Stdev, Zscore, Correlation, Cmo, Roc, Mom, Change, Cci, Mfi, Wpr, Stoch, Stochastic, Tr, Bb, Donchian, Highest, Lowest, HighestBars, LowestBars, Ichimoku, Rising, Falling, PivotHigh, PivotLow and Cross from ./sdk/ta; Dev, PercentRank, Bbw, Range, Mode, Cog, Wvad, Iii, Efficiency, Ultimate, Vortex, Aroon and Choppiness from ./sdk/ta-plus; LiquidationBurst from ./sdk/orderflow; and History from ./sdk/stats, whose push(...) is its update: pushed once per bar, its size is its window, and ago(n) reads the value pushed n bars back, the fixed delay an offset draws (delay = new History(i32(p_offset() + 1.0)); in onStart(), then delay.push(average); and out_wma(delay.ago(i32(p_offset())));). The smoothing classes (Ema, Rma, Rsi, Atr, Macd, Adx, Tsi, Dema, Tema, Kama and the rest) remember their start for good, so an EMA or RSI script is unchanged: its pan-back still runs the whole history. So are running totals, the other rings (List, ClosedWindow, CandleList), session and calendar classes, swings and zones, and a module variable written in onBar().

The compiler admits such a file when:

  • Each instance is built at the top of the file. let sma = new Sma(20); qualifies as it stands; onStart() may rebuild it from settings (sma = new Sma(i32(p_period()));), and the last top-level rebuild there is the one that counts. A constructor argument is either a number the compiler works out with its own whole-number arithmetic (a literal, a top-level constant, +, - and * over them, a cast: 20 - 10 * i32(1.9) is 10, and a sum that overflows keeps the whole-history run), or one cast around settings added together, each times a positive number, plus or minus a constant (i32(p_len()), i32(p_len() * 2), i32(2 * p_a() + p_b() + 1), i32(p_len() * 1.5), W rounding a fraction up). An onStart() local assigned once stands for its value (const n = i32(p_len() * 3); sma = new Sma(n);). A length that only shrinks one setting counts as that setting where the class's window is its length (every class but Hma, whose window is twice it): i32(Math.floor(f64(p) / 2)) (any divisor of at least 1), i32(Math.sqrt(f64(p))), i32(Math.floor(Math.sqrt(f64(p)))) and i32(Math.round(Math.sqrt(f64(p)))), p the setting's reader (p_len()) or an onStart() local assigned once from it (const p = i32(p_len());). Those are the half and root lengths of a Hull average built from three Wma, each window counted as the full period. A cast inside the arithmetic (i32(p_len()) * 3), a subtracted setting, any other division or root, or a fact the chart fills rather than the settings (chart.interval_sec(), the tick size, the market's zone) keeps the whole-history run.
  • Each instance updates exactly once per bar, in a top-level statement of onBar() before any statement that can return: never under an if, in a loop, in a ternary branch or on the right of && or ||. An update a bar can skip would leave the window short.
  • Instances are touched in onBar() only, through update(...), their fields and their read methods; never in a helper, never copied into another variable, passed or compared. A field or read method is free anywhere in onBar(), under an if or in a loop included: a read reaches an update only through a top-level local or directly in its argument, and the proof follows both.
  • An update reads only this bar's inputs, settings, constants, pure helpers and other instances' values, directly or through onBar() locals assigned in top-level statements before the first one that can return. A local may be assigned several times: the proof follows every assignment that reaches the update, in order. A local assigned under an if or in a loop that feeds an update, and an instance whose update reads itself (directly, through another instance, or through a local that still holds an earlier read), keep the whole-history run.
  • The rest of the file passes the per-bar proof, and every input is the chart's own feed: its candles (bar.close(), input("close", ohlcv.close)) or its bar time (bar.time()), with no market pin, interval or other option. Another market's candles, a book, a tape or a published feed keeps the whole-history run.

W is each instance's window per constructor argument (a period's own length, twice it for Hma, a History's size, one window per length for Stoch, Stochastic, Ultimate and Ichimoku, its displacement included), plus each class's fixed bars (one for a class that reads the bar before, such as Change, Roc or Mfi; two for Tr and Cross; four for Swma), summed over the instances, plus one bar per dependency edge: an instance whose update reads one other instance adds 1, one that reads two others adds 2. The SMA lesson (sma-codefirst) settles within its period: a pan-back over it at period 20 runs 20 hidden bars before the new ones.

A declared warmup(...) or warmup_bars stays out of W: the sheet's history_warmup carries the computed windows alone, and the chart's running start is the larger of the two at the run's settings, so a declaration that matches the period costs nothing extra.

One setting, two modes: the mode guard

A built-in often offers its math on a higher timeframe too: a select picks chart (the chart's own bars) or a timeframe, and the timeframe path builds the higher bars from the chart's own with a Resampler and a ClosedWindow, state anchored to the calendar that never settles within a fixed number of bars. The chart path can, and a mode guard lets the compiler prove it on its own:

wrun
param.int("period", 20, { min: 1, max: 500, label: "Period" });
param.choice("timeframe", ["chart", "5m", "15m", "30m", "1h", "4h"], "chart", { label: "Timeframe" });
param.bool("wait_for_close", true, { label: "Wait for close" });
output("sma", line, overlay);

let atChart: bool = true;                                 // the guard: a module bool, any name
let sma: Sma = new Sma(1);                                // arm A: finite kit windows only
let resampler: Resampler = new Resampler(tf.CHART, true); // arm B: anything
let closes: ClosedWindow = new ClosedWindow(1);

function onStart(): void {
  atChart = p_timeframe() == 0.0;                         // the guard's one write, first
  if (atChart) {
    sma = new Sma(i32(p_period()));                       // arm A
  } else {
    resampler = new Resampler(i32(p_timeframe()), p_wait_for_close() != 0.0); // arm B
    closes = new ClosedWindow(i32(p_period()));
  }
}

function onBar(): void {
  if (atChart) {                                          // the first statement of onBar()
    const v = sma.update(bar.close());                    // each instance once, at the top
    out_sma(v);
    return;                                               // arm A ends with return;
  }
  // arm B: everything after the if
  resampler.update(bar.time(), bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), NaN);
  if (resampler.closed()) closes.push(resampler.source(0, false));
  out_sma(resampler.refused() ? NaN : closes.mean(i32(p_period())));
}

The compiler admits the guard when the file keeps to this shape; a build that breaks it names warmup:guard:<guard> or warmup:mode:<name>:

  • The guard is a top-level let of type bool that starts true or false, written once, as the first statement of onStart() other than admitted abort-only checks (below), from a select compared with 0 (atChart = p_timeframe() == 0.0;, or == 0), or from several joined by && (below), and read only as the whole condition of the two dispatches: never written again, read anywhere else or shadowed by a local.
  • The select is a param.choice(...) whose default is its first option: a select with whole-number options from 0 up that include 0, default 0 and no host. param.timeframe(...) and param.source(...) pin an input for the host, a later default would leave W at the defaults meaningless, and a negative option would sink the mode window below 0, where every reader clamps it away while arm B runs, so each keeps the whole-history run (warmup:guard:<setting>).
  • The dispatches. if (atChart) { ... } else { ... } is the next statement of onStart(), and whatever follows it there runs in both modes. if (atChart) { ...; return; } is the first statement of onBar(), its arm ending with an unconditional return;: what follows that if, and its else when it has one, is arm B. A second dispatch in onStart() refuses.
  • Arm A is proven as if it were the whole file. The compiler keeps everything outside the two dispatches and arm A of each, drops arm B and every top-level variable, helper and class only arm B reaches, and runs the proof of this page on what is left: each instance updated once at the top of the arm, before its return;, and the source picked inline into a local, never through a helper. A dropped variable's initializer still runs when the module starts, so it may only read, compute and allocate: a kit class, an array, or a class of yours whose constructor sets only its own fields and that has no getter, setter, operator or base class. One that calls a helper of yours writing anything, or builds a class that could run other code, keeps the whole-history run (warmup:mode:<variable>), and so does a dropped class whose static fields start from such a call.
  • Nothing crosses the arms. A kit instance both arms reach, a helper both arms call that reaches one, a top-level variable written in onBar() before the dispatch (a bar counter) and a local of onStart()'s arm A that the code after the dispatch would read as another binding keep the whole-history run. A top-level number written only in onStart() (the source pick, a period) may be read by both.
  • Setting checks may stay. A call in onStart() of abort(...), or of a helper that only reads settings and numbers, compares, builds its message and aborts, writing nothing, either ends the run or does nothing: it may stand before the dispatch or in arm A, and the proof sets it aside.

The sheet's history_warmup then carries arm A's windows plus one mode window over the select, { terms: [{ param: "timeframe", multiplier: 1000000000 }], plus: 0, min: 0 } (the kit exports the multiplier as WRUN_WARMUP_MODE_UNBOUNDED). It is a conditional proof encoding, not a bound for arm B: with the select at 0 the window adds nothing and W is arm A's; at any other option W runs past a billion bars, more than any chart holds, so the chart runs the whole history in that mode as it always did. A terminal build says which: pan-back: new bars plus a 20-bar running start (timeframe 0 only).

Several selects, one guard

A built-in often keeps more than one mode behind its settings: a timeframe pick and a smoothing pick (None, SMA, EMA) each leave the plain line at their first option only. Join their comparisons with && in the guard's one write, and arm A is the file with every select at 0:

wrun
param.int("period", 20, { min: 1, max: 500, label: "Period" });
param.choice("timeframe", ["chart", "5m", "15m", "30m", "1h", "4h"], "chart", { label: "Timeframe" });
param.choice("smoothing_type", ["None", "SMA", "EMA"], "None", { label: "Smoothing" });
param.int("smoothing_length", 9, { min: 1, max: 200, label: "Smoothing length" });
param.bool("wait_for_close", true, { label: "Wait for close" });
output("sma", line, overlay);

let atChart: bool = true;                                 // one guard for both selects
let sma: Sma = new Sma(1);                                // arm A: the plain line
let base: Sma = new Sma(1);                               // arm B: its own copy of the line
let resampler: Resampler = new Resampler(tf.CHART, true);
let closes: ClosedWindow = new ClosedWindow(1);
let smaSmoothing: Sma = new Sma(1);
let emaSmoothing: Ema = new Ema(1);

function onStart(): void {
  atChart = p_timeframe() == 0.0 && p_smoothing_type() == 0.0; // every select at 0
  if (atChart) {
    sma = new Sma(i32(p_period()));
  } else {
    base = new Sma(i32(p_period()));
    resampler = new Resampler(i32(p_timeframe()), p_wait_for_close() != 0.0);
    closes = new ClosedWindow(i32(p_period()));
    smaSmoothing = new Sma(i32(p_smoothing_length()));
    emaSmoothing = new Ema(i32(p_smoothing_length()));
  }
}

function onBar(): void {
  if (atChart) {
    const v = sma.update(bar.close());
    out_sma(v);
    return;
  }
  // arm B reads both selects again, as often as it needs
  let v = base.update(bar.close());
  if (p_timeframe() != 0.0) {
    resampler.update(bar.time(), bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), NaN);
    if (resampler.closed()) closes.push(resampler.source(0, false));
    v = resampler.refused() ? NaN : closes.mean(i32(p_period()));
  }
  const smoothing = p_smoothing_type();
  if (smoothing == 1.0) v = smaSmoothing.update(v);
  else if (smoothing == 2.0) v = emaSmoothing.update(v);
  out_sma(v);
}
  • The write is && and nothing else between <select>() == 0.0 comparisons, each on a different select (two spellings of one reader are one select), each select held to the rules above. The guard holds only while every select reads 0; the selects themselves stay readable everywhere, arm B included, and arm B is free to keep its own copy of arm A's math (base here), never arm A's instance.
  • The stamp keeps one mode window, now with a term per select in the write's order: { terms: [{ param: "timeframe", multiplier: 1000000000 }, { param: "smoothing_type", multiplier: 1000000000 }], plus: 0, min: 0 }. The chart adds the terms up, and every option is a whole number from 0, so W is arm A's while both read 0 and runs past every chart's cap once either picks another option.
  • Out of shape keeps the whole-history run with the guard's own words: || or any other operator, a != 0.0 or a comparison with anything but 0, or one select compared twice (warmup:guard:<guard>), a select out of the rules above (warmup:guard:<setting>), or a second guard written from the other select (warmup:mode:<name>).

A terminal build names every select: pan-back: new bars plus a 20-bar running start (timeframe 0, smoothing_type 0 only).

A per-bar indicator

Bid size against ask size near the close, from each bar's own order book: the resting size within a depth window around the close, as a percent of both sides.

param.number("depth_pct", 1.0, { min: 0.1, max: 10, step: 0.1, label: "Depth window in percent", description: "How far from the close a resting order counts, in percent, each side" });
input("close", ohlcv.close); // the primary input: the chart's own candles
input("book", book.cells, { max_cells: 1000, block_size: 10, description: "The resting book at the bar's close, one [price, size, side] level per tuple" }); // side +1 bid, -1 ask
output("imbalance", histogram, lower, { colors: ["#38bdf8", "#f86800"], format: "%", label: "Book imbalance", description: "Bid size minus ask size near the close, as a percent of both" }); // sky above zero, orange below

const TUPLE = 3; // f64s per level: price, size, side
let depth = 0.01; // a module scalar: onStart() sets it from the setting, onBar() only reads it

function onStart(): void {
  depth = p_depth_pct() / 100.0;
}

// Every value comes from this bar: its close, its book and the setting.
function onBar(): void {
  const n = in_book_cells(); // this bar's f64 values: -1 with no book, 0 for an empty one
  const cells = in_book_view(); // the same values in place, read by index
  const close = bar.close();
  let bids = 0.0;
  let asks = 0.0;
  for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) {
    if (Math.abs(cells[i] - close) > close * depth) continue; // outside the window
    if (cells[i + 2] > 0.0) bids += cells[i + 1];
    else asks += cells[i + 1];
  }
  out_imbalance(imbalancePct(bids, asks));
}

// A plain function: numbers in, a number out, nothing kept.
function imbalancePct(bids: f64, asks: f64): f64 {
  const total = bids + asks;
  return total > 0.0 ? (100.0 * (bids - asks)) / total : NaN;
}
BTCUSDT perpetual on Binance, 1 hour bars, Aug 10 to Aug 18, 2026Real output from OpenMarket's engine

Read it line by line

  • TUPLE is a module constant. It is fixed before the first bar and never written.
  • depth is a module scalar set once. onStart() reads the setting into it and onBar() only reads it, so every bar sees the same number whichever bar the run starts at.
  • n, cells, close, bids and asks are locals. Each starts with a value, is made when the bar starts and is gone when it ends.
  • The loop reads the book by index into the locals. in_book_cells() counts this bar's values (-1 with no book, 0 for an empty one) and in_book_view() holds them in place, [price, size, side] back to back. i + TUPLE - 1 < n reads whole levels only and stops at the last one this bar holds, so a bar with no book reads nothing. The view is one buffer reused bar after bar, and every value past this bar's levels reads NaN, in a full run and in a run that starts at this bar alike: an earlier bar's levels never leak in.
  • imbalancePct() is a plain function. Two numbers in, one number out, nothing kept.
  • out_imbalance(...) writes the bar's one value. A bar with nothing inside the window writes NaN and draws nothing.

Nothing survives the bar except the constant and the setting, so Run's compile proves the file per bar and the sheet carries history_independent: true.

Before and after: Book Heat's note

Book Heat paints the chart market's order book behind the candles and plots the same imbalance below them. Its note, one sentence at the top right on a market that served a book on no bar ("No order book on this market", on forex and stocks), is the classic shape that refuses the proof:

wrun
string("note", { max_bytes: 40 }); // the sentence shown when the market serves no order book
handles.label({ anchor: "top_right", align: "right", color: "#94a3b8", size: 12, style: "plain", safe_area: true });

const note = draw.label(0); // a handle the chart keeps across bars
let bookSeen = false; // the market served a book on some bar

function onBar(): void {
  const n = in_book_cells();
  if (n > 0) bookSeen = true; // a module variable written in onBar()
  if (bar.isLast() && !bookSeen) { // where the bar stands: the last one
    sb_clear();
    sb_text("No order book on this market");
    note.set(16.0, 12.0).text(str_note_sb);
  }
  // ... the imbalance, from this bar's levels
}

"No book on any bar" is a fact about the whole history, so the note needs four things the proof refuses: the string slot and the label handle (kept across bars), the bookSeen flag written in onBar() (carried from bar to bar) and the bar.isLast() read (where the bar stands).

The per-bar variant removes them: the slot, the handle declaration, const note, let bookSeen, its write and the last-bar block. The heatmap still paints each bar's own book, the imbalance still reads it into locals as the sample above does, and the compile proves the file per bar. A market with no book then shows an empty pane and no sentence. Which one to ship is a product choice, not a fix: a script with something to say about the whole history keeps its state, and the chart recomputes that history on a pan-back.

Where the verdict shows

  • The sheet. A proven compile writes history_independent: true beside wasm_sha256, or history_warmup (the windows W sums) for a file that settles within W; a refused one leaves both keys out, never false. Type sheet at the Console prompt after a run to read it (Declarations and the sheet).
  • The Problems tab. One info row, on the construct's line when it has one, for these refusals: a module variable written in onBar(), an object or array the proof cannot admit, a drawing handle, a read of where the bar stands, text written in code, a helper signature the proof cannot admit, an Array that grows, a table that is written or passed, a view not read into a local const, an input with its own interval or view, and a declared handle, string slot or displaced output. The row starts "Scrolling back recomputes the whole history:", names the construct, and says what a per-bar script does instead. It informs and never blocks Run, and the badge does not count it. Every other refusal (a carried feed, a renderer, a frame, a strategy, an alert, a switch, an if in onStart(), an onReset() body, the four-function form, a second file) shows only in the sheet command, as the missing key, and in the line a terminal build prints.
  • A build outside the chart. A build run from a terminal prints the verdict as one line of its output: pan-back: new bars only, pan-back: new bars plus a 20-bar running start (the running start at the settings' defaults: W, or a declared warmup when that is larger; a mode guard's file adds (timeframe 0 only), naming its select, or (timeframe 0, smoothing_type 0 only) for two), or pan-back: whole history with the reason in parentheses.

How to keep a script per bar

  • Keep bar values in locals. What a bar computes lives inside onBar(); a value that must reach the next bar makes the file rolling.
  • Set module scalars once, in onStart(). Read the settings there into top-level numbers, and only read those in onBar().
  • Make scratch inside onBar(). A local StaticArray belongs to the bar; one at the top of the file belongs to every bar.
  • Read celled inputs by index, bounded by the count. in_<name>_cells() counts this bar's values and the view holds them; read whole tuples into locals.
  • Leave the run alone. No bar.isLast(), no bar.count(), no handle or text kept for a later bar.
  • Declare inputs that stay on the bar. A feed beside the chart's candles takes missing: "nan" or "zero"; an interval or view pin and a candles or intrabar stream depend on where the run starts.
  • Let rolling math be rolling. A moving average built from a finite-window kit class settles within W bars and gets a running start; a cumulative delta, a smoothed average or a session profile needs every earlier bar, and the whole-history run on a pan-back is the right one for it.

See also