home Scripting Guide

Lifecycle Hooks & Chart Bars

Every script is built around a small set of lifecycle hooks and the bar data that flows through TD.onChartBar. This page covers both in detail, including how the still-forming newest bar is delivered.

Lifecycle Hooks

Add a hook by assigning a function to it - every hook is optional

Hook · When it runs
TD.onStart Runs once, after the chart history has been passed through onChartBar. Use it to subscribe to extra symbols, fetch data, or log a start message. You can also await at the top level of the script instead.
TD.onStop Runs when you click Stop. Use it to unsubscribe, remove temporary drawings, or save state - it has up to 5 seconds to finish.
TD.onChartBar Runs once for every bar on the chart, then every time the newest bar moves and once more when it closes. See Working with Chart Bars below.
TD.onReset Runs when the chart's symbol or timeframe changes, or when you scroll the chart back to load older bars, just before the whole history is replayed.
TD.onError Runs when your code throws an error during start, inside a TD.on listener, or inside a TD.Indicators scan callback.
Resetting state - TD.onReset = (context) => { ... }

Reset every running value here: arrays, maps, counters, averages and "previous" flags. context is the chart as it is now, already updated when the hook runs: { symbol, underlying, exchange, symbolType, interval }. New bars have not arrived yet, so if you need to redraw something that doesn't come from onChartBar, schedule it with setTimeout.

When it fires · What happens to your drawings
Symbol or interval change All shapes and plots from your script are removed, then the history is replayed.
Scroll-back for older bars Drawings stay. Re-plotting at the same bar updates it in place, and per-bar markers and shapes drawn without an id that the new replay no longer produces are removed.
let closes = [], lastTime = null;

TD.onReset = (ctx) => {
    closes = [];
    lastTime = null;
    TD.log("Chart changed to " + ctx.symbol);
};

TD.onError = (err) => TD.log("Error: " + err.message);
info

Scrolling back now calls onReset and replays the whole history from the new first bar, so bars always arrive oldest first. You no longer need to sort or de-duplicate by bar.time.

Working with Chart Bars

TD.onChartBar = (bar, index, isHistory) => { ... }

Argument · Description
bar.time Bar time in epoch milliseconds, always a number - for history and live bars alike.
bar.open/high/low/close Prices
bar.volume 0 or null for symbols without volume, such as cash indices.
bar.closed false while the bar is still forming, true once it is final. See The Forming Bar.
index Position in history (0 = oldest). Live bars always use -1.
isHistory true while existing chart bars replay, false for live bars.
Important behaviour
schedule Live bars arrive at the chart's own timeframe, read straight off the chart, so your values match the chart's indicators tick for tick. You don't need to combine 1-minute bars yourself. To receive 1- or 5-minute bars whatever the chart shows, use TD.on("bar1min") or TD.on("bar5min") (see Live Market Data)
speed Keep it fast and synchronous - it runs for thousands of history bars in a row, so don't await data calls inside it (see the Indicators section for the recommended pattern)
auto_awesome Drawing calls auto-use the current bar's time - TD.Chart.plot() and friends, called inside onChartBar, don't need an explicit time. Plotting a line value, marker or per-bar shape at a bar that already has one updates it instead of adding another
rss_feed It does not subscribe the chart's symbol to tick events. Call TD.Feed.addSymbols([TD.Chart.getSymbol()]) if you need them
bug_report Errors on live bars are logged as Runtime Error in onChartBar (Live)
info

bar.time is always milliseconds, so it can be compared and used as a Map key directly - no conversion needed.

The Forming Bar

The newest bar is still moving, so it is passed to onChartBar more than once

The bar currently forming is passed with closed: false, and passed again with the same time every time it moves. When the next bar opens, it is passed one last time with closed: true. During history replay every bar is closed: true except the last one on the chart.

Rule · Why
Same time as the previous call → replace that bar's value Appending would count the forming bar many times.
Commit running state and fire signals only when bar.closed Markers, alerts and counters should reflect the final bar, not a value that may change before the close.
// Before - appends on every call, so the forming bar is counted repeatedly
TD.onChartBar = (bar) => {
    closes.push(bar.close);
};

// Now
let closes = [], lastTime = null, prevAbove = null;

TD.onChartBar = (bar) => {
    if (bar.time === lastTime) closes[closes.length - 1] = bar.close;   // forming bar moved
    else { closes.push(bar.close); lastTime = bar.time; }
    if (closes.length > 20) closes.shift();
    if (closes.length < 20) return;

    const sma = closes.reduce((a, b) => a + b, 0) / 20;
    TD.Chart.plot("SMA 20", sma);               // fine on every call: re-plotting updates the bar

    if (!bar.closed) return;                    // signals only on finished bars
    const above = bar.close > sma;
    if (prevAbove !== null && above !== prevAbove) {
        TD.Chart.plotMarker(above ? bar.low : bar.high, above ? "buy" : "sell");
    }
    prevAbove = above;
};

TD.onReset = () => { closes = []; lastTime = null; prevAbove = null; };
Recursive indicators (EMA, Wilder's RSI, VWAP)

Keep the state "as of the last closed bar", compute the forming bar's value from it without saving, and save only when bar.closed.

const LEN = 20, K = 2 / (LEN + 1);
let emaClosed = null;                           // EMA as of the last CLOSED bar

TD.onReset = () => { emaClosed = null; };

TD.onChartBar = (bar) => {
    const ema = emaClosed === null ? bar.close : emaClosed + K * (bar.close - emaClosed);
    TD.Chart.plot("EMA 20", ema);               // forming bar: compute from closed state, don't save
    if (bar.closed) emaClosed = ema;            // save only when the bar is final
};
Pattern: keep a rolling series

Hold only as many bars as your logic needs, replace the last one while it is forming, and compare against the previous bar rather than recalculating from scratch.

const bars = [];

TD.onReset = () => { bars.length = 0; };

TD.onChartBar = (bar) => {
    const last = bars[bars.length - 1];
    if (last && last.time === bar.time) bars[bars.length - 1] = bar;   // forming bar moved
    else bars.push(bar);
    if (bars.length > 500) bars.shift();                               // keep memory bounded

    if (!bar.closed || bars.length < 2) return;                        // signals on finished bars only
    const prev = bars[bars.length - 2];
    if (bar.close > prev.high) {
        TD.Chart.plotMarker(bar.low, "buy");
    }
};
tips_and_updates

Always pair TD.onChartBar with TD.onReset. Almost every "my indicator breaks after I change the symbol" or "wrong after scrolling back" problem is state left over from an earlier replay.