หน้านี้ยังไม่ได้แปลเป็นภาษาไทย จึงแสดงเป็นภาษาอังกฤษ

Realtime & replay

Stream live data, aggregate ticks into bars, and replay historical data at controlled speed.

Built-in adapters

All free, no API key — connect any of them the same way:

import { BinanceAdapter, CoinbaseAdapter, BybitAdapter, KrakenAdapter, UpbitAdapter } from '@tradecanvas/chart'

chart.connect({ adapter: new BinanceAdapter(),  symbol: 'BTCUSDT', timeframe: '1m' })
chart.connect({ adapter: new BybitAdapter(),    symbol: 'BTCUSDT', timeframe: '1m' })
chart.connect({ adapter: new KrakenAdapter(),   symbol: 'BTC/USD', timeframe: '5m' })
chart.connect({ adapter: new CoinbaseAdapter(), symbol: 'BTC-USD', timeframe: '15m' })
chart.connect({ adapter: new UpbitAdapter(),   symbol: 'KRW-BTC', timeframe: '1m' })

UpbitAdapter takes Upbit's markets (KRW-BTC, BTC-ETH): candles stream up to 4 hours, the day comes from the ticker, and longer bars are built from days. Its REST API gives 200 candles a call and lets a browser make one call in ten seconds, so a web page passes restBase pointing at a proxy of its own. The data is Upbit's, under its Open API terms. MARKET_UPBIT_KRW gives the KRW market's steps and colours.

A feed the chart pulls from

A DataFeed is the shorter way to plug in your data: two methods, with Promises. The chart asks for bars (getBars) and subscribes to live ones (subscribeBars); it pages back, reconnects, builds the timeframes the feed lacks and subscribes again on a switch, so the feed only answers. Give it to connect or a widget's feed option, where an adapter would go.

import type { DataFeed } from '@tradecanvas/chart'

const feed: DataFeed = {
  name: 'my-api',
  // The newest countBack bars, or the ones before `before` when the chart pages back.
  // An empty array: no more.
  getBars: ({ symbol, timeframe, countBack, before, signal }) =>
    fetch(`/candles?s=${symbol}&tf=${timeframe}&n=${countBack}&before=${before ?? ''}`, { signal })
      .then((r) => r.json()),
  subscribeBars: ({ symbol, timeframe }, on) => {
    const ws = new WebSocket(`wss://example.com/${symbol}/${timeframe}`)
    ws.onmessage = (m) => {
      const k = JSON.parse(m.data)
      on.bar(k.bar, k.closed)   // the forming bar again, a new one, or its final values
    }
    ws.onclose = () => on.connection('disconnected')   // the chart loads and subscribes again
    return () => ws.close()
  },
}

chart.connect({ feed, symbol: 'AAPL', timeframe: '1d' })
new ChartWidget(el, { feed, symbol: 'AAPL' })

The subscriber also takes tick (trades and quotes), connection (a feed that never calls it is taken as connected once subscribeBars returns), symbolInfo and error. The signal is aborted when the chart no longer needs the answer: a symbol switch or a disconnect. What a subscription sends after its unsubscribe is dropped, so a socket that closes late can't put the old symbol's bars on the new one. The optional methods are an adapter's: supportedTimeframes, resolveSymbol, searchSymbols, subscribeQuotes, fetchNews, fetchTrades and subscribeTrades. A feed with only the newest bars sets pagesBack: false, so the chart never asks for older ones. The chart doesn't take a quiet feed for a dead one (a daily chart, a closed market): a feed whose socket can drop silently reports it through connection.

One feed serves any number of charts: each subscribes on its own, so a grid takes one feed for all its charts (widget: { feed } in ChartWidgetGrid, grid.connectAll(feed, symbols, '1h')), where it takes an adapter per chart. Adapters keep working everywhere, and the two convert: feedFromAdapter(new BinanceAdapter()) is a feed, adapterFromFeed(feed) an adapter. A connect with both an adapter and a feed throws.

Bars you push: ManualFeed

For bars your app already has, ManualFeed keeps the history of each symbol and timeframe and sends the bars you push to the charts subscribed to that series. Later loads (a reconnect, a switch back) include them, so the bars have one writer, the feed, instead of setData and appendBar calls next to a stream. A pushed bar older than the newest is the final values of the bar at its time; one the series has no bar for throws.

import { ManualFeed } from '@tradecanvas/chart'

const feed = new ManualFeed()
feed.setBars('AAPL', '1d', history)
chart.connect({ feed, symbol: 'AAPL', timeframe: '1d' })

feed.pushBar('AAPL', '1d', formingBar)        // again and again as it forms
feed.pushBar('AAPL', '1d', finalBar, true)    // closed

DataAdapter interface

interface DataAdapter {
  name: string
  supportedTimeframes?: TimeFrame[]   // left out: it serves every timeframe
  connect(config): void
  disconnect(): void
  getConnectionState(): ConnectionState
  fetchHistory(symbol, timeframe, limit?): Promise<OHLCBar[]>
  on(event, listener): void   // 'bar' | 'barClose' | 'tick' | 'snapshot' | 'connectionChange' | 'error' | 'symbolInfo'
  off(event, listener): void
  dispose(): void

  // Optional
  fetchHistoryBefore?(symbol, timeframe, before, limit): Promise<OHLCBar[]>
  searchSymbols?(query, options?): Promise<SymbolInfo[]>
  resolveSymbol?(symbol): Promise<SymbolInfo | null>
  subscribeQuotes?(symbols, onQuotes): () => void      // a watchlist's rows
  fetchNews?(symbol, limit?): Promise<NewsItem[]>       // the symbol info panel
  fetchTrades?(symbol, limit?): Promise<Trade[]>        // tick charts, with
  subscribeTrades?(symbol, onTrades): () => void        // subscribeTrades
}

searchSymbols and resolveSymbol answer with SymbolInfo: the symbol, and what the feed knows of the rest: a readable name (description), the exchange, the type in the feed's own words ('stock', 'futures', 'Cổ phiếu'…), a logo the widget's symbol search shows, the pricePrecision, minTick, currency, timeZone and sessions. A feed whose prices run behind the market says by how much in delayMinutes (15 for most exchanges' free data): the widget's status bar then reads "Delayed 15 min" where it reads "Live", with a dot of its own.

Timeframes the feed lacks

A feed that lists its supportedTimeframes gets every other timeframe built from the coarsest of them that divides it: 7m from 1m, 4h and 1D from 1h. Days, weeks, months and the hour frames that divide a day (2h, 3h, 4h, 6h, 8h, 12h) start at the midnight of the symbol's exchange, in the timeZone its resolveSymbol names. The chart asks once per symbol, as the first history of such a timeframe is fetched, builds that history once the answer comes, and keeps the zone; 1h and shorter frames don't wait for it. A zone whose days need a finer timeframe than UTC's (Ho Chi Minh City's on a feed of 4h bars) has that history fetched again at it. A feed without resolveSymbol, one that names no zone or UTC, or one whose timeframes can't line up with that midnight (only 4h bars for a zone 7 hours from UTC) gets UTC days, as before. So does one that fails to answer or takes more than 5 seconds, and the symbol's days then stay UTC's until the chart loads the symbol afresh (connects to it, or comes to it from another symbol or timeframe), so older pages and the history after a reconnect never hold a day twice; a fresh load builds them in the zone the feed has named since, or asks it again. The market's zone (setMarket) doesn't move these bars. Daily bars stamped at 00:00 UTC are read as the dates they name. A zone the feed sends later in a symbolInfo event changes the times shown, not where built days start.

Symbol details the feed learns later

A connected chart asks resolveSymbol once. A feed that learns the symbol's details only later (on its first message, say) sends them with a symbolInfo event, and the chart applies them: the symbol's decimals (pricePrecision) on the price scale, the legend and the tags, and on the drawings' labels, the day's price limits, pivot labels, the measure and the market profile too; in the widget, on the data window, the alerts list, the order ticket and the account panel; the scale's ticks on its price step (minTick); the exchange's hours. A market's decimals (setMarket) go to the same places and come before the symbol's. Without either, a drawing's label keeps the decimals of its price's size, grouped in the number locale as the axis is. The widget's watchlist writes each symbol at the pricePrecision its entry in symbols gives, and by the size of its price without one: two decimals from 1,000, four from 1, four significant figures under 1, however small.

emit('symbolInfo', { symbol: 'VNM', pricePrecision: 0, minTick: 10, currency: 'VND' })   // as your adapter sends its other events

A bar the feed corrects

A feed corrects a bar by sending it again, closed, with its own time: { bar, closed: true } from parseMessage, or a bar event. A closed bar older than the newest the stream has seen is the feed's last word on it, a venue's final that came after the next bar's first frame or a revision: the chart replaces the bar with that time wherever it is (updateBar), computes its indicators again from it, and keeps the view. It is no live price: the price line, the orders and the alerts stay with the market. A forming frame older than the newest is stale and left out; it moves nothing. The built-in adapters (WebSocketAdapter, PollingAdapter, the feeds built on them and BinanceAdapter) make a tick from a bar's close only for the newest bar, counting the last bar of the history they served, so a last closed bar a feed sends again on subscribing makes none; an adapter of your own that makes ticks from its bars should leave older ones out too. Without an adapter, call chart.updateBar(bar).

With aggregateTicks the history's last bar is the one the trades build on: the first trade after connecting keeps its open, high, low and volume. A trade for a bar already past, delivered late, is left out, and a closed bar for one corrects it, the forming bar keeping its trades. A trade from after the newest bar starts goes in that bar even when the buckets would start it earlier (daily bars stamped at another hour than midnight, or a symbol whose zone comes after the first trade), so the price follows every trade. On a timeframe built from a finer one, a corrected base bar builds its bar again, for the last two built bars before the forming one; a correction further back is left out.

// in an adapter: the venue's final for a bar already on the chart
parseMessage: (raw) => ({ bar: toBar(raw), closed: true })

// your own bars, without an adapter
const corrected = chart.updateBar(bar)   // false: no loaded bar has bar.time

Any feed in ~20 lines

Extend WebSocketAdapter (live + REST history) or PollingAdapter (REST-only feeds). The base handles the connection lifecycle, reconnect, decoding, and event emission — you supply a URL and a parse function.

import { WebSocketAdapter } from '@tradecanvas/chart'

const myAdapter = new WebSocketAdapter({
  name: 'myexchange',
  wsUrl: (c) => 'wss://api.myexchange.com/ws/' + c.symbol + '@kline_' + c.timeframe,
  fetchHistory: (symbol, tf, limit) => fetch('/candles?...').then((r) => r.json()),
  parseMessage: (raw) => ({ bar: toBar(raw), closed: raw.k.x }),
})

Tick aggregation

Roll raw ticks into OHLC bars per timeframe:

import { TickAggregator } from '@tradecanvas/chart'

const agg = new TickAggregator('1d')
agg.setTimeZone('Asia/Ho_Chi_Minh')         // days start at the exchange's midnight
agg.seed(history.at(-1).time)               // a bar older than the history's last is past
agg.on('barClose', (bar) => console.log(bar))   // a bar whose interval is over
agg.on('correction', (bar) => console.log(bar)) // a closed bar older than the newest
agg.processTick({ time, price, volume })

const current = agg.getCurrentBar()         // forming bar

Weeks start on Monday and months on the 1st. With setTimeZone, days, weeks, months and the hour frames that divide a day start at the exchange's midnight; a chart sets it for its stream's ticks (aggregateTicks) from the symbol's zone, else its market's, and lands their bars on the history's: days are stamped at 00:00 UTC when the history's are, and 2h to 12h bars start at the exchange's midnight only when the history's do, so a feed's own 4h bars (00:00, 04:00… UTC) keep their times. On a timeframe built from a shorter one of the feed's, they start where the built bars start. Built from hours, they start at the midnight of the zone its resolveSymbol named, else UTC's, whatever zone the chart has; built from the feed's days stamped at 00:00 UTC, weeks and months keep its dates, and a trade is dated in the zone it named, else the chart's, as on the feed's own days.

A bar older than the newest one seen is past: processBar sends a closed one as correction and leaves out a forming one, and processTick leaves out a trade for one, so a late frame or trade can neither close the forming bar early nor move the price. seed(time) starts from a history's last bar and doesn't move back (unless the trades built the newer bar on buckets they no longer start on, the exchange's zone having come after them: that bar is let go, or the next trades would be left out until the next bucket), and resume(bar) makes that bar, still forming, the one the next trades build on, unless the trades have reached a newer one; a chart's stream does both on every connect, so a reconnect whose history ends on the bar before keeps the forming bar's trades. StreamManager then puts the forming bar, built from trades or from a feed's frames, on top of the history it sends as snapshot, and sends no priceChange for the history's last close, an older price. It sends a correction as barCorrection.

Quotes for many symbols

A feed with subscribeQuotes sends quotes (last price, the day's change, high, low, volume, bid and ask) for many symbols at once until you stop it. BinanceAdapter sends a 24 h snapshot, then its mini-ticker stream; MockAdapter makes quotes up. A widget's watchlist fills its rows from it. Without a quote, the row of the chart's own symbol reads its price and the day's move from the chart's bars, as the symbol info panel does: against the close before the last day, in the exchange's zone, and no move when the bars hold no day before it.

const stop = new BinanceAdapter().subscribeQuotes(['BTCUSDT', 'ETHUSDT'], (quotes) => {
  for (const q of quotes) console.log(q.symbol, q.last, q.changePercent)
})
stop()

readQuote({ symbol: 'AAPL', last: 190, prevClose: 188 })   // → change 2, changePercent 1.06

Tick charts

A tick timeframe — '100T' — draws a bar per 100 trades. It is built from a feed's trades: its recent ones for the history (fetchTrades), then its live ones (subscribeTrades). BinanceAdapter streams aggregate trades. A tick chart has no countdown and pages in no older history; a feed without trades refuses tick timeframes. Tick bars are not evenly spaced in time, so the time axis and the crosshair give times only to bars, not to the empty space beside them.

chart.connect({ adapter: new BinanceAdapter(), symbol: 'BTCUSDT', timeframe: '100T' })
await chart.setTimeframe('500T')

// Your own trades into tick bars
const builder = new TickBarBuilder(100)
builder.push([{ time, price, volume }])   // → [{ bar, closed }]

Who took the trades

A feed can say which side took each trade, the one that crossed the spread: side on a trade ('buy' when the buyer lifted the ask, 'sell' when the seller hit the bid) and buyVolume on a bar, the part of its volume the buyers took. Both are optional. With buyVolume a bar has a delta, bought less sold: barDelta(bar) gives it, or null for a bar that does not say, and the Volume Delta indicator (voldelta) draws it, and its running sum, in place of its estimate. BinanceAdapter fills both in, from the exchange's taker buy volume and its aggregate trades; MockAdapter makes them up.

chart.setData([{ time, open, high, low, close, volume: 1200, buyVolume: 700 }])
chart.addIndicator('voldelta', { mode: 1, anchor: 'session' })   // the cumulative delta, from each session's start

barDelta({ volume: 1200, buyVolume: 700 })   // 200: 700 bought, 500 sold

The chart carries buyVolume wherever it carries the volume. Bars built of other bars (resampleBars, a timeframe the feed lacks) add it up; tick bars, and bars aggregated from ticks, count it from trades that say their side; a replayed bar has it in step with its volume; the CSV and JSON exports write it in a column of its own (Buy Volume), which the import reads back. A bar with a part that does not say has none: half a split is no split.

Three things to know. A trade pushed with chart.updateLastBarFromTick counts too when it has its side; one with a volume and no side leaves the forming bar with no buyVolume. Renko, Kagi, line break, point and figure and range bars are drawn bars, not the feed's: indicators on those charts read the drawn bars, which have no split, so the delta there is the estimate. And where only some bars of a series say, the cumulative delta adds true deltas to estimates, each of which is a bar's whole volume: it steps where the two meet. The JS API and UDF bridges have no field for it.

The footprint chart

chartType: 'footprint' draws, by each bar, what traded at every price inside it: what the sellers took at the bid on the left, what the buyers took at the ask on the right. A row where one side outdid the other is in bold on a stronger tint, the row most traded at has a line round it, and a slim candle stands at the left of each bar. In the widget it is Footprint in the chart type menu, with its settings in Chart Settings.

const chart = new Chart(el, { chartType: 'footprint' })
await chart.connect({ adapter: new BinanceAdapter(), symbol: 'BTCUSDT', timeframe: '1m' })

That is all a feed with trades needs (fetchTrades and subscribeTrades, as BinanceAdapter and MockAdapter have): while the chart shows a footprint it asks the feed for its recent trades, a thousand of them, and follows its live ones, and it stops when the chart type changes. A feed keeps few trades, so at first only the newest bars have a footprint: the bar the recent trades began part way through is left out, the bars before it are slim candles, and the footprint grows with the live trades from there. Another symbol or timeframe starts it again.

A host with trades of its own gives them with chart.addTrades(trades), on any chart type: each is counted in the bar of its time and the row of its price, on the side that took it. A trade with no side is told by the trade before it (bought when the price went up to it, sold when it went down): an estimate, as the delta of a bar with no buyVolume is. A host that keeps the rows gives those, bar by bar, and footprintOf makes them from trades in one call.

import { footprintOf, footprintStats } from '@tradecanvas/chart'

chart.setChartTypeOptions({ footprint: { rowSize: 0.5, collect: false } })   // the rows are the host's
chart.setFootprint([
  { time: bar.time, levels: [{ price: 100, buy: 12, sell: 30 }, { price: 100.5, buy: 41, sell: 9 }] },
])
chart.setFootprint(footprintOf(trades, '1m', 0.5))    // or made from trades

const rows = chart.getFootprint(bar.time)             // { time, levels }, or null for a bar with none
if (rows) footprintStats(rows.levels)                 // { buy, sell, volume, delta, poc, … }
chart.clearFootprint()                                // before another series' rows
SettingDefaultWhat it does
rowSize'auto'The height of a row in price. Auto is about a ten-thousandth of the last price, rounded to 1, 2 or 5 (5 at 60,000), in whole steps of the symbol's price step; with rows given by hand, the smallest step between their prices. Another size starts the footprint again.
cells'bidAsk''bidAsk': the two sides apart. 'delta': bought less sold. 'volume': both together.
imbalance3How many times one side has to outdo the other, a row apart, to be marked: what was bought at a price against what was sold one row below, and what was sold against what was bought one row above. 0 marks none.
collecttruefalse: the chart asks its feed for no trades.
totalstrueUnder each bar, what its rows add up to: bought less sold in the colour of its sign, and both together under that. Written where a bar is wide enough for a number; the price scale leaves them room under the lowest bar. false: none.

The zoom decides what a bar carries. Choosing the footprint zooms in to where the numbers read, and its bars may get much wider than candles do; zoomed out, the numbers give way to a bar for each side, then to plain candles. Rows too thin to read are drawn 2, 5, 10… to one, on round prices. The footprint is kept for the newest 500 bars and is not saved with the chart's state. During a replay the bars not yet shown carry no cells, nor does a bar still forming from finer bars. On a tick chart a trade is counted in the last bar that had opened when it came, so a bar's first trade can fall in the bar before it. It is drawn in Canvas 2D, with the WebGL renderer too. renderPriceChart draws it from footprint, the rows as chart.getFootprint() gives them.

The tape, and the trades themselves

chart.followTrades() follows the trades of the chart's symbol until the function it returns is called: the feed's recent trades, then its live ones, as trades events. The feed is asked once for any number of followers, and a chart that shows a footprint follows them by itself. Trades given with chart.addTrades() are told the same way. No trade of the feed's is told twice: not on another timeframe of the symbol, nor after a reconnect, when only the ones missed are, though later ones were told first. chart.getTrades() gives the trades told lately, up to two thousand, for a listener that comes after they were told.

const stop = chart.followTrades()
chart.on('trades', (e) => {
  // e.payload.trades: oldest first
  // e.payload.recent: the feed's recent trades, not trades made just now
  for (const trade of e.payload.trades) log(trade.time, trade.price, trade.volume, trade.side)
})
stop()   // the feed is let go of once no one follows it and the chart is no footprint

In the widget, tape: true adds the tape (time and sales) to the dock: the trades newest on top, each with its time, its price and its size, the price in the colour of who took it. A bar over the list says how much of the rows the buyers took and how much the sellers, a trade ten times the usual size stands out, and trades under a least size can be left out (tape: { minSize: 0.5 }, or typed in the panel). The widget follows the feed's trades only while the tape is open. widget.openPanel('tape') opens it; its switches are tape and dock.tape.

A menu in the tape's header lists one side's trades alone (bought, or sold), and makes one row of the trades made together: those of one moment, one price and one side, their sizes added, so a market order that took several resting orders reads as the one trade it was. Such a row is measured against the least size, and for being large, by what it adds up to. Both can be set from the start (tape: { side: 'buy', group: true }). What a reader chooses in the panel is kept in the browser and is there the next time: the side and the grouping for every symbol, the least size for the symbol it was chosen on, since a size means one thing on one instrument and another on the next. What the reader chose is used over the option it started from, each choice by itself; persist: false keeps nothing.

Market status and news

marketStatus(info, now) tells whether a symbol's market is open at a moment, from its hours in its exchange's zone (clock changes included), and when that changes. Sessions can name the weekdays they open on. A feed's fetchNews gives headlines for the widget's symbol info panel; readNews keeps only items with a title and a time, and links to web pages.

const info = {
  symbol: 'AAPL',
  timeZone: 'America/New_York',
  sessions: [{ start: '09:30', end: '16:00', days: [1, 2, 3, 4, 5] }],
}
marketStatus(info, Date.now())   // { state: 'closed', next: <next open, ms> } · 'open' · 'always' (24/7)

Reconnect

ReconnectManager handles exponential backoff with a cap and a final give-up.

import { ReconnectManager } from '@tradecanvas/chart'

const rm = new ReconnectManager({ maxRetries: 6, baseDelay: 500, maxDelay: 30_000 })

rm.start()
rm.schedule(() => connectWebsocket())   // call on disconnect; backs off automatically
rm.onConnected()                        // call on a successful connect to reset

Replay mode

Drive a historical DataSeries forward at controlled speed. Decoupled from Chart so it can power both UI replay and headless backtests.

import { ReplayController } from '@tradecanvas/chart'

const replay = new ReplayController({
  data: historicalBars,
  speed: 10,      // bars per second
  startIndex: 0,
})

// Seed the chart with everything before startIndex
chart.setData(replay.getPrefix())

// Wire each emitted bar into the chart
replay.on('bar', ({ bar }) => chart.appendBar(bar))
replay.on('finished', () => console.log('done'))

replay.start()
// replay.pause(); replay.resume(); replay.step(5); replay.seek(200); replay.setSpeed(20)

In the widget's replay mode, click any revealed bar to jump the replay cursor there. More generally, the chart now emits click and barClick events for plain left-clicks (press and release without dragging):

chart.on('barClick', (e) => {
  const { bar, barIndex, point } = e.payload
})

Replay on the chart, in finer steps

chart.replayStart() replays the chart's own series. Give it finer bars as steps (5-minute bars under an hourly chart) and each step grows the forming bar from them, as it grew in the market; closed bars show as they are in the series. startIndex and replaySeekToBar count the chart's bars. In ChartWidget, the replay bar's Step menu offers the finer intervals the feed has (or that the bars you loaded can build).

chart.replayStart({ animate: true, step: 'auto', startIndex: 120, paused: true })
// or finer bars you hold for the bars replayed: { steps, startIndex: 120 }
chart.replayResume()
chart.getReplayBarIndex()      // the chart bar forming now
chart.replaySeekToBar(150)     // to the end of bar 150
chart.replaySeekToTime(t)      // to the bars that closed by t
chart.on('replayStep', (e) => e.payload)    // { barIndex, time, stepTime, until, total, cause }
chart.on('replayComplete', (e) => e.payload) // { barIndex, time }
chart.on('replayState', (e) => e.payload)   // { state: 'playing' | 'paused' | 'stopped' }
chart.replayStop()             // back to the live series

Bars that form as they play

With animate: true each bar grows over its time, as a live bar does: from its open to the extreme its direction says came first (a rising bar dips first), the other, then its close. With step ('auto', or an interval such as '1m') the chart fetches the finer bars of the bars it is about to play through the connected feed's fetchHistoryBefore, a page at a time and only while it plays, and each bar forms along them; 'auto' is the finest the feed serves with at most 60 to a bar. The last frame is always the bar as the series has it. steps you give are used the same way. The clock keeps counting the chart's bars: speed, duration and the indices mean bars, and getReplayBarIndex() is the bar forming. A pause holds a half-drawn bar; a seek or a step shows whole bars. A paper account fills as the drawn price reaches an order. Bars shorter than three frames come whole, and under reduced motion a bar steps from one of its prices to the next. replayStepsLoad tells loading, loaded, end or error; a bar without finer bars forms from its own prices. ChartWidget does this by default: its Step menu starts on Auto; replayStep ('auto', 'bar' or an interval) and replayAnimate: false change it. On a feed without fetchHistoryBefore the widget fetches the finer bars in one request before the replay starts. With replayAnimate: false, Auto replays whole bars; a finer interval picked plays as steps of its own.

The replay bar in ChartWidget

The toolbar's Bar replay button opens a bar under the chart, across the widget, above the status bar: the chart makes room for it, so the volume, the bottom panes and the time axis stay in view. First pick the bar to start from: click it, or press Random bar; Cancel (or Esc) leaves. Then: step back, Play/Pause and step forward; the date and time of the step shown, in the display timezone (the year only when it isn't this one), and a track with the played part filled; Speed as multipliers from 0.1× to 50× (1× plays one bar of the chart a second, whatever the step; the default is 1×); Step; Select bar, which pauses and picks another start among the bars shown, without showing the bars to come (Cancel or Esc returns to the same place); and Back to realtime. On a phone or a narrow chart it takes two rows, the date and the track on top. Keys, for the widget used last: Shift+←/→ step, Space on the chart or the track plays or pauses (outside a replay it fits the chart), and Esc stops picking. A shortcut you add with addHotkey on the same keys comes first. The bar reads the --tcw-* tokens of the look and theme; a host may also set --tcw-replay-btn, --tcw-replay-play or --tcw-replay-track-w on .tcw-replay-bar. Its readout comes from replayStep's stepTime, the time of the step shown.

A replay outlives the bars

A replay is a time over the live series. When the bars change — a new symbol or timeframe through connect or switchStream, setData, older bars paged in, the extended hours, a corrected bar — it goes on over the new bars at the time it had reached, and shows only bars that closed by then. While a new series loads, the replay waits, playing or paused as it was. Indices (barIndex, total, replaySeekToBar) are of the bars replayed now and change with them; keep a position by time. A replay a paper account trades ends when the symbol changes. In ChartWidget the replay bar stays open, says Loading chart and waits while the bars load, then follows their total and the new interval's steps.

chart.replayStart({ startIndex: 300, paused: true })
await chart.setTimeframe('1h')        // the replay waits, then goes on at the same time
const { until } = chart.getReplayProgress()   // keep a position by time, not by index
if (until !== null) chart.replaySeekToTime(until)   // back to it, on any interval
chart.on('replayStep', (e) => {
  if (e.payload.cause === 'series') {}  // carried over: barIndex and total are the new bars'
})
chart.replayStop()                    // call it first to end the replay as before

A replay in your own app

Buy and sell marks and trade zones show as the replay reaches them: a mark once its bar is shown, a trade once entered, drawn open until its exit is reached (revealMarks: false, ChartWidget: replayRevealMarks: false shows them all). startTime starts at a time instead of a bar; hideHistory leaves the bars before the start out until the replay stops; duration plays to the end in about that long however many bars there are, several bars a frame, and a late frame slows it rather than skip ahead.

chart.setSignalMarkers(signals)          // the whole backtest, kept
chart.setTradeZones(trades)
chart.replayStart({
  startTime: Date.now() - 30 * 86_400_000,   // the last 30 days
  hideHistory: true,                          // only them on the chart
  duration: 3500,                             // in about 3.5 s
})
chart.on('replayComplete', () => chart.replayStop())   // then the whole series again
chart.replayStart({ startIndex: 100, revealMarks: false })   // every mark from the start

Paper trading in a replay

An execution adapter with setMarkPrice(price, time, symbol) (as PaperExecutionAdapter has) trades on the replay: during a replay the chart hands it each replayed price and time, so orders and stops fill as the replay passes them and fills land on the replayed bars. Each step's low and high count, and a jump ahead passes every step on the way. It only goes forward: after a seek back it waits until the replay is past the furthest point it has seen. The live price doesn't move it meanwhile; when the replay ends it goes back to the live price, and fills to the clock. Price alerts keep watching the live market throughout; alerts on indicator lines wait for the replay to end. chart.getTradingTime() is the moment an order placed now is placed at: the replay's while the account trades on it, else the clock's. The widget's order ticket counts a good-till-date order's date from it.

chart.connectExecution(new PaperExecutionAdapter())
chart.replayStart({ startIndex: 300, paused: true })
// place orders from the chart or the order ticket, then play

API

MethodPurpose
start()Begin emitting from current index.
pause() / resume()Pause/continue timer.
step(n)Emit N bars synchronously without the timer.
seek(index)Jump without emitting in-between bars.
setSpeed(bps)Bars per second (clamped to >= 0.01).
destroy()Clear timer + listeners.

See Analytics for using replay alongside the backtester.