Esta página ainda não foi traduzida, por isso aparece em inglês.
API reference
Public surface of the top-level classes: Chart, ChartWidget, ChartWidgetGrid and ChartGrid.
Chart
Headless renderer. Bring your own UI; subscribe to events; mutate state imperatively.
Construction
new Chart(host: HTMLElement, options?: ChartOptions) Data
| Method | Purpose |
|---|---|
setData(data) | Replace the entire series. |
appendBar(bar) | Append a new bar; auto-scroll if enabled. |
appendBars(bars) | Batch append; recalculates indicators once. |
updateLastBar(bar) | Mutate the current forming bar. |
updateLastBarFromTick(tick) | Merge a tick into the last bar. |
addTrades(trades) | Trades into the footprint: each in the bar of its time and the row of its price, on the side that took it. |
followTrades() | Follow the feed's trades, its recent ones and then its live ones, as trades events, until the function it returns is called. See the tape. |
getTrades() | The trades told lately, oldest first: the feed's and those given by hand. For a listener that comes after trades were told. |
setFootprint(bars) / getFootprint(time?) / clearFootprint() | The footprint's rows, bar by bar: given by hand, read back (a bar's, or every bar's), forgotten. |
updateBar(bar) | Correct a loaded bar: the one with the same time, anywhere in the series. The view stays; false when no loaded bar has that time. |
getData() | Read the raw OHLC series. |
A bar from appendBar, appendBars or updateLastBar, and a tick, is the live price: the price line, the alerts and the orders' P&L follow it, as they follow a connected stream and setCurrentPrice. A new bar sends dataUpdate; a tick on the forming bar sends none.
A bar your feed corrects goes in with updateBar(bar): it replaces the loaded bar with the same time, wherever it is in the series, and returns true. The indicators are computed again from that bar on, Heikin-Ashi, Renko and the other types built from the bars follow, and the view stays where it is; corrections before the next frame are computed once, from the earliest. It returns false and changes nothing when no loaded bar has that time (a new bar is appendBar's, older ones prependBars') or the chart can't take the bar. It is no live price: the orders and the alerts don't follow it, no alert fires on it, and alerts on indicator lines aren't checked against the corrected values. A corrected last bar moves the price line, as after setData. During a replay it corrects the live series: a bar the replay has passed shows corrected at once, a later one when the replay reaches it; a bar in the extended hours, while they are hidden, shows when they are shown. The bar loaded, sent again, changes nothing; a missing volume is 0, as with setData, so send the bar whole. It sends dataUpdate with { kind: 'correction', time, index }. In ChartWidget, widget.getChart().updateBar(bar) corrects the bars of a connected feed; bars you gave the widget with setData are a copy it builds its timeframes from again, so a correction to them lasts only until the next timeframe switch (a widget method for these is to come).
Bar times are epoch milliseconds or seconds, one unit for the whole series. The chart reads it once, from the newest bar: barTimeUnit(data) gives 1 (milliseconds, from 1e11 up) or 1000 (seconds). So a series in milliseconds keeps its dates before 2001 too, though they are below 1e12. Keep a series in one unit; the times the chart hands back (events, getData()) are in it.
Chart type & theme
| Method | Purpose |
|---|---|
setChartType(type) | One of 25 types — see Chart types. |
getChartType() | The type the chart is drawn as ('candlestick' by default). |
setTheme(name | theme) | Switch between built-in themes, or set your own. getTheme() gives it back as set. |
applyOverrides(patch, { layer }) | Style any part of the chart by key ('grid.vertical.visible', 'series.candlestick.upColor'…); null takes a key away. See Styling. |
setOverrides(overrides, { layer }) · resetOverrides(keys?, { layer }) | All of a layer at once; take keys (or all) away. |
getOverrides({ layer }) · getStyle() · getStyleValue(key) | A layer's overrides; the looks as resolved; what one key resolves to. |
setTimeframe(tf) | Switch active timeframe; rewires the live stream. |
Renderer
| Method | Purpose |
|---|---|
renderer option | 'canvas' (default), 'webgl', or 'auto' (WebGL on a hardware GPU only). |
setRenderer(mode) | Switch at runtime. Resolves to what draws now: 'canvas' where WebGL 2 can't be had. |
getRenderer() | 'canvas' or 'webgl'. |
What the GPU draws, and the numbers: Performance → WebGL renderer.
Indicators
| Method | Purpose |
|---|---|
addIndicator(id, params?, position?) | Adds an overlay or panel indicator. Returns instance id. |
whenIndicatorsReady() | Resolves once the code of every built-in indicator on the chart is in and their values computed. In 3.x a chart has every built-in's code at once, so it resolves at once; from 4.0 a built-in's code loads the first time one is added, and its output is pending till then: awaiting this before a read keeps it right. |
Chart.preloadIndicators(ids?) | Loads the built-ins' code now, the ones named or all, for every chart on the page. Resolves at once in 3.x, where every built-in's code is in; from 4.0 a chart made after it has their values as they are added. |
updateIndicator(instanceId, params) | Mutate a live indicator. |
removeIndicator(instanceId) | Remove and tear down. |
removeIndicators(instanceIds) | Remove several, as one undo step. |
removeAll(what?) | Every drawing ('drawings'), every indicator ('indicators') or both ('all'), as one undo step; locked drawings stay. Returns how many of each went. |
takeBackDrawing(id) | Take back a drawing just made, as a Cancel right after it: with the step that made it when that is the last one, so nothing is left to undo or redo. The drawingCreate event says drawn: true for a drawing the pointer just made. |
updateIndicatorStyle(instanceId, style) | Colours, line widths, opacity, and each plot's dash and visibility (plots: { signal: { lineStyle: 'dashed' } }), and a markers plot's shape and size. |
setIndicatorDefaults(id, style | null) | The style indicators of a kind start with from now on. |
setIndicatorIntervals(instanceId, intervals | null) · getIndicatorIntervals(instanceId) | The intervals it shows on ({ minutes: false, hours: [1, 4] }); null: all of them. Saved with the layout. |
setDataTimeframe(timeframe | null) | The interval of bars set with setData: the legend names it, and indicators kept to some intervals follow it. |
setPaneStyle(instanceId, { background, separator } | null) · getPaneStyle(instanceId) | A pane's own look, saved with its indicator. |
Axis & scale
The price axis (right strip) and time axis (bottom strip) accept direct pointer interaction, with the gestures traders already know:
| Gesture | Effect |
|---|---|
| Drag price axis up / down | Compress / expand the vertical price range (disables auto-scale). |
| Drag time axis left / right | Zoom in / out on the time axis. |
| Double-click price axis | Re-enable auto-scale. |
| Double-click time axis | Fit all data to the viewport. |
Time zone. The time axis, the crosshair's time, the tooltip, the day
breaks and the range presets follow the browser's zone by default. Give the chart an
IANA zone (daylight saving included), a fixed offset in minutes east of UTC, or 'exchange' for the symbol's zone (SymbolInfo.timeZone), else its
market's: as the timeZone option, from the widget's settings, or directly:
new Chart(host, { timeZone: 'America/New_York' }) // from the start
chart.setTimeZone('America/New_York') // New York's time, daylight saving included
chart.setTimeZone(330) // UTC+5:30, in minutes
chart.setTimeZone(null) // the browser's
chart.setTimeZone('exchange') // the symbol's zone, else its market's
chart.getTimeZone() // 'exchange', as set
chart.getEffectiveTimeZone() // the zone it stands for: 'Asia/Ho_Chi_Minh' on HOSE The chart's methods and types spell it timeZone, as Intl.DateTimeFormat does. The 1.x spellings (setTimezone and the rest, SymbolInfo.timezone) were removed
in 2.0: see Moving to 2.0.
The same effects are also available programmatically:
chart.setAutoScale(false) // hold the price range on screen (a new series is fitted once)
chart.setLogScale(true) // switch to logarithmic price scale
chart.setInvertScale(true) // upside down (Alt+I in the widget)
chart.fitContent() // zoom out to all data (Alt+R in the widget, with auto scale)
chart.scrollToEnd()
chart.setVisibleRangePreset('3M') // 1D 5D 1M 3M 6M YTD 1Y 5Y All
chart.setMinBarUnit(0.05) // narrower bars, so 'All' fits a long series (0.25 by default)
chart.goToTime(Date.UTC(2025, 0, 1)) // centre that bar (Alt+G in the widget)
chart.setVisibleRange(from, to) // the bars between two times, edge to edge (Go to's Custom range)
chart.getVisibleTimeRange() // { from, to }: the first and last bars on screen, or null Long ranges. A bar slot is never narrower than 0.25 px, so a range longer than that allows (26 years of days on a laptop) shows its newest part. In the widget a long range on the range bar switches to the timeframe whose bars fit, at 2 px a bar or more: 5Y of days goes to weeks, All to months; a short range goes back to the timeframe you picked, never finer. It switches only to timeframes your feed serves (or the bars here resample to). features: { 'statusBar.rangeTimeframe': false } keeps the timeframe. On a bare Chart, minBarUnit (an option, or setMinBarUnit) lets slots go down to 0.02 px, drawn a pixel column at a time.
Price scale modes. Beyond regular and logarithmic, the axis
can rebase its labels against the first visible bar — percentage shows % change, indexedTo100 rebases the baseline to 100. Regular,
percentage, and indexed share the same linear geometry; only the labels
differ. Settable from the chart-settings panel or directly:
chart.setScaleMode('percentage') // axis labels: +12.34% from first visible bar
chart.setScaleMode('indexedTo100') // first visible bar reads as 100
chart.setScaleMode('logarithmic')
chart.getScaleMode() Price and time formats
Prices can read in your own words, or in fractions of a point the way bonds and their
futures are quoted (101'16 is 101 and 16/32). The format reaches
everything that prints a price on the price scale: axis, crosshair, last-price tag,
legend, tooltips, orders, alerts and drawing labels; the axis puts its ticks on whole
fractions and roundPrice rounds to them. Indicator panes keep their own
numbers. Without a format of your own, prices are grouped in the number locale; the
axis's tick labels show only the decimals their step needs (73,500), while the last
price, the crosshair and the tags beside the axis show every decimal. With no decimals set by the symbol or the market, those are one more than the scale's step needs, and for a price under 1 at least four significant figures of it (0.000004349, where the step alone gave 0.00000435). Times can read your way too; the formatter is told what a label is.
new Chart(host, { priceFormat: { denominator: 32 } }) // 101'16
chart.setPriceFormat({ denominator: 32, subDenominator: 2 }) // 101'165: 16½ 32nds
chart.setPriceFormat((p) => '$' + p.toFixed(2))
chart.setPriceFormat(null) // decimals again
chart.setTimeFormatter((time, { kind, timeZone }) =>
// kind: 'year', 'month', 'day' (the step a label starts), 'time' (within a day), 'crosshair'
new Intl.DateTimeFormat('en-GB', { timeZone: typeof timeZone === 'string' ? timeZone : undefined, hour: '2-digit', minute: '2-digit' }).format(time)) How the axes choose their labels
The time axis labels the bars that start the largest calendar steps: a year (in bold), a month, a day, a round hour, at least 80 px apart. So at 5Y it reads 2022 · Jul · 2023, at a month Oct · 8 · 15, within a day 12:00 · 18:00. The labels belong to bars, not to the screen: panning moves them with their bars, and history loaded in front leaves them where they were. Left of the oldest bar there are none. Where no new year is labelled, a tag at the left end, in the style of the timezone tag at the right, writes what the labels leave out, as of the first bar on view: the year among months, Mar 2023 among days, the whole date among the times of one day. Over a label at the left end it stands in for it and says what it said (Mar 2023 over Mar). Panned back into history, the year is always on the axis. Month names follow setNumberLocale, and the grid's lines go where the labels are.
The price scale fits as many labels as its height does, at least 30 px apart, on the market's price step. On a log scale its step grows with the price, so the bottom is labelled as well as the top; on a percent or indexed scale its labels are round percents or index points from the baseline. Indicator panes count their labels by their height too.
Markets: price steps, limits and sessions
setMarket gives the chart an exchange's rules: candle colours, decimals, the
price step (which can depend on the price), the daily ceiling and floor, and the lot. roundPrice and getPriceStep follow the step of the price's band, so
prices from the chart's menus land on valid prices, and the widget's order ticket checks
an order against the step, the day's limits and whole lots. A preset also carries the
exchange's sessions and time zone, for getCurrentSession and your own code; the
chart's session shading and extended hours come from setSymbolInfo. Presets cover the Vietnamese exchanges as of May 2025: HOSE (10, 50 or
100 dong a step by price, ±7%), its ETFs and covered warrants (10 dong), HNX (±10%, a
post-close session), UPCoM (±15%) and VN30 index futures (0.1 a point, ±7%, from 8:45);
shares and lots of 100, green up and red down, purple ceiling, cyan floor and yellow
reference. Their prices are in thousands of dong, as price boards show them; scaleMarketPrices(preset, 1000) reads prices in dong.
import {
MARKET_HOSE, scaleMarketPrices, priceStepAt, roundToPriceStep, getCurrentSession,
vn30fContracts, vn30fLastTradingDay,
} from '@tradecanvas/chart'
chart.setMarket(MARKET_HOSE) // or scaleMarketPrices(MARKET_HOSE, 1000) for 25350
chart.setTimeZone('exchange') // the axis in the market's zone: Asia/Ho_Chi_Minh
chart.setPriceLimits(25.35) // the reference: yesterday's close
chart.getPriceLimits() // { ceiling: 27.1, floor: 23.6, reference: 25.35 }
chart.roundPrice(25.37) // 25.35, a 50-dong step
chart.getPriceStep(9.5) // 0.01 below 10,000 dong
// The rules on their own
priceStepAt(25.35, MARKET_HOSE) // 0.05
roundToPriceStep(10.486, MARKET_HOSE, 'down') // 10.45
getCurrentSession(MARKET_HOSE.sessions, Date.now(), MARKET_HOSE.timeZone) // { name: 'ATC', type: 'preClose', … }, by the clock only
// VN30 futures: the four listed contracts and their last trading days
vn30fContracts(Date.now()) // [{ symbol: 'VN30F2611', lastTradingDay: '2026-11-19', … }, …]
vn30fLastTradingDay(2026, 12, (day) => holidays.has(day)) // the third Thursday, earlier on a holiday Korea, as of September 2026: MARKET_KRX for KOSPI and KOSDAQ shares in won
(1 to 1,000 won a step by price; ±30%, the move rounded down to the reference's step
first, as KRX rounds it; the opening and closing calls, the regular session and the
After-Market until 20:00), MARKET_NXT for Nextrade (KRX's steps and limits,
its own sessions from 8:00 to 20:00) and MARKET_UPBIT_KRW for Upbit's KRW
market (steps from 1,000 won down to a hundred-millionth of a won, no limits). They draw
rising prices red and falling ones blue (KR_COLORS); createMarketTheme(theme, KR_COLORS) gives any theme those candles, and formatVolumeLoc(value, 'ko') shortens volumes in 만, 억 and 조.
With numberLocale: 'ko-KR' the chart writes them so too: the legend, the
crosshair tooltip, ChartWidget's data window and the Date and Price Range box.
import { MARKET_KRX, KR_COLORS, createMarketTheme, LIGHT_THEME, formatVolumeLoc } from '@tradecanvas/chart'
chart.setMarket(MARKET_KRX) // red up, blue down
chart.setPriceLimits(9980) // the reference: yesterday's close
chart.getPriceLimits() // { ceiling: 12970, floor: 6990, reference: 9980 }
chart.roundPrice(72340) // 72300, a 100-won step
createMarketTheme(LIGHT_THEME, KR_COLORS) // a theme with Korea's candles
formatVolumeLoc(345_000_000, 'ko') // '3.45억' A market of your own is a MarketConfig: priceStep, or priceSteps: [{ from, step }] for bands, priceLimits, volumeUnit (the lot), sessions, timeZone and colorScheme. A symbol's own minTick comes before the market's
step. Exchanges change their rules from time to time; check a preset against your
exchange's current rules before you rely on it.
The limits are drawn as dashed lines named CE, FL and REF, with a tag on the axis, in the
market's colorScheme colours, else the theme's priceLimits. A colour
that doesn't read at 4.5:1 on the theme's background is shaded toward its text until it does, so the
price board's bright magenta, cyan and yellow keep their hue on the light theme.
A theme of your own without priceLimits takes the light theme's on a light background, the dark theme's on a dark one.
The day's limits as the broker gives them
setPriceLimits takes the day's ceiling, floor and reference as they are for the symbol, in place of the
reference alone. Pass them where your broker or the exchange gives them: a special band, or a stock's first session
on another exchange, is no percentage of the reference, and the market's percentages are then only what is used when
nothing better is known. The lines on the chart, the prices an order may be dragged to and the ticket's checks all
follow what is given. The widget's order ticket shows the three over its price, each a press that sets the price; priceLimitOrder puts them in the order of your board, and leaves out the ones not named.
The ticket itself is a page of the dock beside the chart (widget.openPanel('orderTicket')); ticketPlace: 'dialog' makes it a dialog over the chart, as it is on a phone.
chart.setMarket(MARKET_HOSE)
chart.setPriceLimits({ ceiling: 27.1, floor: 23.6, reference: 25.35 }) // as the broker gives them for the symbol
chart.setPriceLimits(25.35) // or the reference alone: the market's percentages of it
new ChartWidget(host, { trading: true, priceLimitOrder: ['reference', 'ceiling', 'floor'] }) // the ticket's row, in your board's order Comparing symbols
Another symbol's percent change on the price scale (addCompareSymbol), or
its price on a scale of its own, in a pane of its own, or the spread or ratio of the
chart's close to it — those last are indicators (compareSymbol, compareSymbolPane, spread), with legends, value tags, alerts and saved layouts like any
other. The other symbol's bars line up with the chart's by time. The chart asks for
the bars it needs; give them again after a timeframe change. correlation (of the closes)
and correlationlog (of bar-to-bar returns) read the other symbol the same way, from −1 to 1.
chart.addCompareSymbol('eth', 'ETHUSDT', ethBars, '#7c4dff') // percent change, on this scale
chart.addIndicator('compareSymbol', { symbol: 'ETHUSDT' }, 'bottom', { scale: 'left' }) // own scale
chart.addIndicator('compareSymbolPane', { symbol: 'ETHUSDT' }) // own pane, own scale
chart.addIndicator('spread', { symbol: 'ETHUSDT', mode: 'ratio' }) // own pane
chart.addIndicator('correlation', { symbol: 'ETHUSDT', length: 20 }) // −1 to 1, own pane
chart.on('symbolSeriesRequest', async ({ payload }) =>
chart.setSymbolSeries(payload.symbol, await adapter.fetchHistory(payload.symbol, '1h', 1000)))
chart.getRequiredSymbols() // what to fetch again on a new interval
chart.setPaneScale(spreadId, { percent: true }) // a pane in percent of its first value A percent line starts at the chart's own close on the first bar on screen, the price a percent
scale reads 0% at, from the other symbol's own first bar there; one whose bars begin later
starts at 0% too. With the price scale in percent (chart.setScaleMode('percentage'))
each line then reads its own change since the first bar on screen, which moves as you pan.
Its label is at its end. chart.getCompareValues(barIndex?) gives each line at a
bar (the last by default), for a legend of your own: { id, label, color, visible, close, change, stale }, where close is the
other symbol's close at or before the bar and change its change in percent, as
its line reads. Past the other symbol's last bar (bars you fetched once, the chart streaming
on) it gives its last close, with stale: true. chart.setCompareVisible(id, false) hides a line and leaves it out of the auto scale.
Renko, Kagi, Line Break, P&F and Range Bars draw no compare lines: their bars only count on from
the first, with no time of their own, so a line there would read the other symbol at the wrong
bars. On those types the lines stay out of the auto scale, and getCompareValues() gives each one's close at the latest data bar, whatever bar is asked for, with change: null.
The indicators that read another symbol by time (a symbol on its own scale or in its own pane, a spread,
a ratio, a correlation) are not drawn there either, nor fit a scale: getActiveIndicators() gives
them shown: false and offChartType: true, and ChartWidget dims their rows as it dims a
compare's. Back on candles they come back.
A pane with nothing else in it is taken away there, its room going to the plot, and comes back with them.
chart.setScaleMode('percentage') // each line reads its change on the axis
chart.getCompareValues() // [{ id: 'eth', label: 'ETHUSDT', color, visible, close: 2650.4, change: -1.82, stale: false }]
chart.getCompareValues(barIndex) // at a bar: the one under the cursor
chart.setCompareVisible('eth', false) // hidden, and out of the auto scale In ChartWidget, Compare on the toolbar (and the + in the object tree) opens the compare dialog: search for a symbol, pick how under Add as (percent change, own scale, own pane, spread, ratio, or the correlation of prices or of returns) and add as many as you like. What is compared already is listed first, each with its way and a button to take it off. The dialog opens next time on the way used last.
ChartWidget puts the price scale in percent while a symbol is compared in percent, and back to
the scale you had once the last one goes. A logarithmic, percentage or indexed-to-100 scale is
left as it is, and a scale you pick while comparing (the status bar's % or log, the chart's
menu, the settings) stays, also after the last compare goes. The percent scale is never saved:
a layout and a shared link keep your own. The legend lists each symbol compared in percent
above the indicators, marked in its line's colour, with its price and its change at the bar under the
cursor (the last bar otherwise), an eye to hide it and a button to take it off. Its bars are fetched as deep as the
chart's and, when the chart loads older bars, the stretch those add (from a feed without fetchHistoryBefore,
each again, as deep as the chart's, while the feed has older bars to give), so its line starts where the chart does.
On a chart type that draws no compare lines it leaves your scale as it is and dims each compare's
row, saying why in its tooltip and to a screen reader; back on one that draws them, the percent scale comes back.
Exporting data
The bars as CSV or JSON, each indicator line in a column of its own named as the legend names it. ChartWidget has Export data (CSV) in the chart's right-click menu. Numbers with a fraction are written to 15 significant digits, so a volume summed from smaller bars reads 40.37 rather than 40.370000000000005.
chart.exportAllData('csv', 'btc-1h.csv') // every bar loaded
chart.exportVisibleData('json', undefined, { indicators: false })
const text = chart.getExportText('csv', { range: 'visible' })
const { bars, columns } = chart.getExportData() // columns: { name, values }[] Pictures, print and PDF
The chart as a picture: saved to a file, copied, or read as a data URL, as bytes or as a canvas. With
nothing more asked, it is read off the chart's canvases as they are on the screen. Ask for more pixels
(pixelRatio) or another theme (theme) and the frame is drawn again for the
picture, in Canvas 2D whatever the chart itself draws with: the chart on the page is neither resized nor
told. A width or a height lays the chart out again at that size, the bars it has
on view on view there, and puts the page's layout back: a picture for a slide or a sheet of paper from a
chart in a sidebar. The bars are as wide as the size makes them, within what a bar can be: past that, more
or fewer of them are on view, about the same middle. At a size of its own the picture has nothing that
follows the pointer (the crosshair, a measure), nor a canvas a host laid over the chart, and a size with no
room for a plot gives no picture. type is 'png' (default), 'jpeg' or 'webp', with quality for the last two.
chart.screenshot('btc-1h') // btc-1h.png, as on the screen
chart.screenshot('btc-1h', { pixelRatio: 3, type: 'webp' }) // drawn again at three times the pixels
await chart.copyScreenshot() // a PNG on the clipboard; false where the browser refuses
const url = chart.screenshotDataURL({ theme: 'light' }) // in the light theme; the chart stays as it is
const blob = await chart.screenshotBlob({ type: 'jpeg', quality: 0.9 })
const canvas = chart.toCanvas({ pixelRatio: 2 }) // to draw on, or to read yourself
const slide = await chart.screenshotBlob({ width: 1920, height: 1080 }) // laid out again at that size print() opens the browser's print dialog for the chart alone: a page that holds its picture
and nothing of the page it is on; it gives false when there was no picture to print. toPdf() gives a PDF of one page, the picture kept without loss and as large as fits within the
margins. Both draw the chart again for paper, in the light theme and
at twice the pixels unless you say otherwise. chartsToPdf makes one PDF of several charts, a
page each: the price chart, the finance charts, or a canvas of your own.
import { chartsToPdf } from '@tradecanvas/chart'
chart.print({ title: 'BTCUSDT, 1h' })
const pdf = await chart.toPdf({ pageSize: 'letter', margin: 12, title: 'BTCUSDT' }) // a Blob
const full = await chart.toPdf({ width: 1123, height: 794 }) // laid out in the page's own shape: as large as its margins allow
const report = await chartsToPdf([chart, equityChart, allocationChart], { title: 'March', theme: 'dark' }) pageSize is 'a4' (default), 'a3', 'letter', 'legal' or the paper's two sides in millimetres; orientation is 'landscape' (default) or 'portrait'; margin is in millimetres. The
PDF holds no text of its own, so it needs no font: the chart's words are in its picture, in any language.
A picture is held to what a browser can draw (no side past 16,384 pixels, some 16 million in all), so a
very large chart gets fewer pixels than asked. The pixels are packed without loss by the browser's CompressionStream, which every current browser has; one without it gets a JPEG that keeps
nearly all of the picture. Printing puts the picture in a frame as a data: URL, so a page with
a content security policy has to allow those for images.
What the picture has is what the chart draws on its canvases: the plot, the axes, the legend, the
crosshair if it is showing, and a canvas a host laid over the chart (unless it is hidden, or holds a
picture from another site, which no page may read back). What is built of page elements is not on it: the tooltips, and the widget's bars and its rows of indicator names. With features.screenshot off there is no picture, print or PDF. ChartWidget has Print chart and Save chart as PDF in the command palette, and widget.printChart() and widget.saveChartPdf(), both under the chart's symbol and
interval, with a toast when there was nothing to print or to save; they go with the screenshot switch.
The chart drawn with no page
renderPriceChart draws the price chart on a 2D context of your own, where there is no page:
a canvas made in Node, for a picture in an email, a report or a message from a bot, or an OffscreenCanvas in a worker. It is one frame, put together as Chart puts its
own together: at the same size it is the picture a chart on a page gives of the same bars once chart.fitContent() has every bar on view (or chart.setVisibleRange(), with visibleRange).
import { createCanvas, Path2D } from '@napi-rs/canvas' // or another canvas for Node that has Path2D
import { renderPriceChart } from '@tradecanvas/chart'
const canvas = createCanvas(1920, 1080)
const ctx = canvas.getContext('2d')
ctx.scale(2, 2) // a 960 × 540 chart at twice the pixels
renderPriceChart(ctx, {
data: bars, // every bar is on view when they fit
symbol: 'BTCUSDT',
timeframe: '1d',
theme: 'light',
timeZone: 'Asia/Ho_Chi_Minh',
indicators: [
{ id: 'ema', params: { period: 21 } },
{ id: 'rsi', instanceId: 'momentum' }, // a pane of its own under the prices
{ id: 'stochastic', pane: 'momentum' }, // in that pane, on its scale
],
drawings: [
{ type: 'horizontalLine', anchors: [{ time: bars[0].time, price: 64000 }], style: { color: '#2266ff' } },
{ type: 'horizontalLine', anchors: [{ time: bars[0].time, price: 70 }], paneId: 'momentum' }, // on that pane
],
markers: [{ time: bars[40].time, price: bars[40].low, direction: 'long', confidence: 0.8, source: 'strategy', label: 'Buy' }],
path2D: Path2D, // Node has no Path2D of its own
}, { width: 960, height: 540 })
const png = canvas.toBuffer('image/png') The options are Chart's where they say how the chart looks: chartType and chartTypeOptions, theme, font, overrides, density, logScale, numberLocale, priceFormat, watermark, and features to leave out the volume, the grid, an axis or the
legend. What a chart on a page is given by calls, this one takes as options: data, symbol and timeframe for the legend, indicators, drawings (as addDrawing takes one), markers (as addSignalMarker takes one), visibleRange (the times of the first and the last
bar on view), pricePrecision, timeZone (the machine's own with none: name the
zone your readers are in) and symbolSeries (other symbols' bars, for 'compareSymbol', 'spread' and the correlations). An indicator reads as a saved
layout's does, so chart.getIndicatorSetup() and chart.getDrawings() go in as
they are, a drawing on an indicator's pane with them: a chart someone set up in the browser is drawn again
on the server. plugins takes an indicator, a chart type, a drawing tool or an overlay of your
own.
It draws the size you give in the context's own units, over the theme's ground: scale the context first
for more pixels. The bars are drawn with Path2D, which Node does not have: @napi-rs/canvas and skia-canvas each export theirs, to give as path2D; a worker has its own. The text is in the theme's font, so name one your canvas has
with font. Nothing follows a pointer: there is no crosshair, countdown or tooltip. Orders
and positions, alerts, compare lines, the volume and market profiles, session shading and a market's
price limits are not drawn this way yet. A finance chart is drawn the same way by renderFinanceChart, and imagesToPdf puts pictures made this way in a PDF.
What is wrong with the options is said before anything is drawn, by the option's name: a RangeError for an indicator, a theme or a time zone it does not know, two indicators of one instanceId, and a number outside what it can be; a TypeError for an option that
is the wrong kind of thing. A bar that is no bar is left out, as a chart leaves it out. The context is
left as it was found; should a plugin of yours throw while it draws, draw the next chart on another.
Volume Profile
Horizontal histogram of traded volume bucketed by price over the visible range. Off by default — toggle programmatically or via the widget settings sheet:
chart.setVolumeProfileVisible(true)
chart.setVolumeProfileConfig({
buckets: 48, // resolution of the histogram
widthRatio: 0.18, // % of chart width
opacity: 0.32,
highlightPoC: true, // mark the highest-volume bucket
}) Swing markers (pivots)
Mark fractal swing highs/lows with small triangles (▼ above a confirmed pivot high, ▲ below a pivot low). The strength controls how many bars must be lower on each side. Toggle from the settings sheet, or:
chart.setPivotMarkersVisible(true)
chart.setPivotMarkersConfig({ left: 5, right: 5, showLabels: true })
// market-structure labels (HH / HL / LH / LL) instead of price
chart.setPivotMarkersConfig({ structureLabels: true })
// pure detection + classification are exported
import { findPivots, classifyPivots } from '@tradecanvas/core'
const pivots = findPivots(bars, 5, 5) // [{ index, price, type }]
const structure = classifyPivots(pivots) // adds label: 'HH'|'LH'|'HL'|'LL' Session shading (regular trading hours)
Dim bars outside the regular session (pre/post-market or the overnight break) so the cash session stands out. Defaults to US equity RTH (09:30–16:00 New York time, daylight saving included); configure the window in minutes-of-day plus the market's time zone. A symbol whose feed reports its sessions sets them by itself.
chart.setSessionShadingVisible(true)
chart.setSessionShadingConfig({
startMinute: 9 * 60 + 30, // 09:30
endMinute: 16 * 60, // 16:00 (end-exclusive; end < start wraps midnight)
timeZone: 'America/New_York', // or tzOffsetMinutes: -300 for a fixed offset
}) Extended hours. Turn them off and the bars outside the symbol's
regular hours (SymbolInfo.sessions in its timeZone) leave the
chart; they are kept aside, live bars and history pages too, and come back when
turned on. Bars a day or longer are left as they are.
chart.setSymbolInfo({ symbol: 'AAPL', timeZone: 'America/New_York', sessions: [{ start: '09:30', end: '16:00' }] })
chart.setExtendedHours(false) // or new Chart(host, { extendedHours: false })
chart.isExtendedHoursVisible() The trading day. A session that runs past midnight (CME's 17:00 to 16:00 in Chicago) starts the trading day at its open. The indicators that start again each day, week or month (Session VWAP, VWAP's and the cumulative delta's anchor, the session volume profile, the MTF average's days), the prior-day lines and the market profile's days then run from 17:00 to 17:00, each named by the date it ends on. Sessions inside a day keep midnight. Daily bars and the days built from trades keep the zone's midnight. The chart's day lines start there too while it shows the exchange's time (setTimeZone('exchange'), or the exchange's zone by name); on another clock a day there runs midnight to midnight.
chart.setSymbolInfo({ symbol: 'ES', timeZone: 'America/Chicago', sessions: [{ start: '17:00', end: '16:00' }] })
// Session VWAP, svp, the prior-day lines: from 17:00 to 17:00
import { tradingDayStart } from '@tradecanvas/chart'
tradingDayStart([{ start: '17:00', end: '16:00' }]) // 1020: minutes after midnight
tradingDayStart([{ start: '09:30', end: '16:00' }]) // null: midnight Prior-period levels (PDH / PDL / PDC)
Draw the prior day's (or week's) high, low, and close plus the current period's open as labelled horizontal lines — the support/resistance levels intraday traders watch. Toggle from the settings sheet, or directly:
chart.setPeriodLevelsVisible(true)
chart.setPeriodLevelsPeriod('week') // 'day' (PDH/PDL/PDC) | 'week' (PWH/PWL/PWC)
// pure computation is exported; the chart passes the exchange's zone (left out, the days are UTC's)
import { computePeriodLevels } from '@tradecanvas/core'
const levels = computePeriodLevels(bars, 'day', 'Australia/Sydney') // [{ id, label, price }] Market Profile (TPO)
A time-at-price histogram: each bar contributes one TPO to every price bucket its range touched, surfacing the Point of Control (busiest price) and the value area (≈70% of TPOs, grown from the POC two buckets at a time toward the heavier pair, as Market Profile counts it). Distinct from Volume Profile — it weights by time, not volume — and is left-pinned so both can show together. Off by default; toggle from the settings sheet or directly:
chart.setMarketProfileVisible(true)
chart.setMarketProfileConfig({
buckets: 48,
widthRatio: 0.18,
opacity: 0.32,
valueAreaPct: 0.7, // fraction of TPOs in the value area
highlightPoC: true, // dashed line at the point of control
valueAreaColor: '#7e57c2', color: '#90a4ae', // colours of its own; null: the theme's (the rising candle's, the secondary text's)
})
// split into one mini-profile per trading day, in the exchange's zone
chart.setMarketProfileConfig({ splitBySession: true })
// classic TPO letters per session (when zoomed in enough to be legible)
chart.setMarketProfileConfig({ splitBySession: true, letters: true })
// pure computation is exported too; give the sessions the exchange's zone, as the chart does (left out, UTC's days)
import { computeMarketProfile, computeSessionProfiles } from '@tradecanvas/core'
const profile = computeMarketProfile(bars, priceMin, priceMax, { buckets: 48 })
const sessions = computeSessionProfiles(bars, priceMin, priceMax, {}, 'Australia/Sydney') // per-day TPO Touch & mobile
| Gesture | Action |
|---|---|
| 1-finger drag (chart area) | Pan + move crosshair |
| 2-finger pinch | Zoom around the midpoint |
| Long-press (~500 ms) | Pin OHLC tooltip at the bar (mobile equivalent of Alt-click) |
| 1-finger drag inside price / time axis strip | Scale the corresponding axis |
| Tap | Click: click, barClick, a signal marker; on a drawing, select it |
| Double tap | Double-click: on an axis, reset it; on a drawing, open its settings |
| 1-finger drag on a drawing | Move it, or reshape it by a handle of the selected one |
| With a drawing tool: tap, tap — or press, drag, lift | Place its points; press, drag and lift draws a two-point line in one go |
| Long-press on a drawing | Its menu (as a right-click) |
| 1-finger drag on an alert, order or bracket line, or a pane divider | Drag it |
A finger reaches further than a mouse: about 16 px to a line and 22 px to a handle, against 8. On a page that scrolls, pageScroll: true leaves vertical swipes and the plain mouse wheel to the page: the chart pans with a sideways swipe and zooms with two fingers or Ctrl + wheel (a trackpad pinch), while presses on drawings, lines and axes stay the chart's. chart.setPageScroll(on) switches it while running.
Modals (settings, hotkey sheet, command palette, symbol search) automatically switch to a bottom-sheet pattern with a grab handle and safe-area-aware padding under 640 px viewports.
Measure tool
Hold Shift and drag on the chart to measure bars × price between two points — the overlay shows price Δ (absolute + %), bar count, and time span. The overlay clears as soon as the mouse is released; it does not persist into saved state.
Events
All events are typed via ChartEventMap:
chart.on('orderPlace', e => /* OrderPlacePayload */)
chart.on('orderModify', e => /* OrderModifyPayload */)
chart.on('signalMarkerAdd', e => /* { marker } */)
chart.on('tradeZoneAdd', e => /* { zone } */)
chart.on('dataUpdate', e => /* { kind: 'bars', length } on setData and new bars; { kind: 'correction', time, index } on a corrected bar; or kind 'alert' | 'bracket' | 'connection' | 'error' */)
chart.on('ordersChange', e => /* { orders } */)
chart.on('positionsChange', e => /* { positions } */)
chart.on('executionFill', e => /* { side, price, quantity, reason, pnl } */)
chart.on('marginCall', e => /* { marginLevel, level, equity, marginUsed }: the account was warned of its margin */)
chart.on('trades', e => /* { trades, recent }: trades of the symbol, while they are followed (followTrades, a footprint) or given (addTrades) */)
chart.on('chartContextMenu', e => /* { area, x, y, price, time } */)
chart.on('stateChange', () => /* drawings, indicators, alerts, chart type or theme may have changed */)
chart.on('paneChange', e => /* { instanceId, change: 'collapsed' | 'maximized' | 'order' } */)
chart.on('crosshairMove', e => /* { point, bar, barIndex, time, prevClose }: time is when the bar stands as the axis dates it (on Renko, the bar a brick was finished on); prevClose the close of the bar drawn before */)
chart.on('crosshairSync', e => /* { barIndex, bar, time, prevClose }: a linked chart's crosshair (setCrosshairTime, a grid) is on this bar here; barIndex null when it goes. Never fires as crosshairMove */)
chart.on('legendResize', e => /* { bottom }: the legend drawn taller or shorter, hidden or shown; content stacked under it moves to getLegendBottom() */)
chart.on('chartTypeChange', e => /* { type, previous } */)
chart.on('symbolChange', e => /* { symbol, previous } */)
chart.on('marketChange', e => /* { market }: setMarket */)
chart.on('compareChange', e => /* { id, change: 'add' | 'remove' | 'data' | 'visible' }: addCompareSymbol and the rest */)
chart.on('timeframeChange', e => /* { timeframe, previous } */)
chart.on('historyChange', e => /* { canUndo, canRedo } */)
chart.on('drawingSelect', e => /* { ids, primary } */)
chart.on('rendererChange', e => /* { renderer: 'canvas' | 'webgl', reason?: 'unsupported' | 'contextLost' | 'contextRestored' | 'limit' } */) Labels of your own under the legend start at getLegendBottom() and move
with legendResize. Tell the chart their size with setLegendStack({ width, height }), measured from the plot's left edge and
that bottom (null when there are none): drawing labels, such as a horizontal
line's price or a position's target, keep clear of them as they keep clear of the legend.
ChartWidget does this for its indicator rows.
A label they cover slides beside them on its own row, goes under them when that is
near its line, or else sits on its line by the price axis where that is clear; labels moved keep clear of one
another, and a position's tags keep the order of their prices.
Undo for your own changes
recordUndo puts a change of yours in the chart's undo history, with its drawings and
indicators: Ctrl/Cmd+Z calls undo, redo calls redo. Changes about the same subject close together are one step. ChartWidget records its settings and chart type this way.
const before = panel.color
panel.color = 'red'
chart.recordUndo({ subject: 'panel-color', undo: () => (panel.color = before), redo: () => (panel.color = 'red') }) Keyboard and screen readers
A focused chart scrolls with the arrow keys (Shift for ten bars), zooms with ↑/↓ or +/−, and goes to
the start and end with Home and End. For screen readers it is an application with a summary
(symbol, type, timeframe, last price); after the keys move the view it says what is on screen, and
comma and period read the bars one at a time. a11y.labels puts it in your language; a11y: false leaves it out. scrollBars(n) and selectDrawing(id) do from code what the keys and a click do.
new Chart(host, { a11y: { labels: { role: 'gráfico', summary: '{what}. Último precio {close}.' } } }) Prices from the pointer can be put on the market's grid with chart.roundPrice(price): a multiple of the symbol's minTick, else
its precision. ChartWidget's menus, order ticket and the drawing settings' Coordinates tab do this. chart.getPriceStep() is that step itself.
ChartWidget
Wraps Chart in a complete UI. widget.getChart() gives you the same instance.
import { ChartWidget } from '@tradecanvas/chart/widget'
const widget = new ChartWidget(host, {
symbol: 'BTCUSDT',
timeframe: '5m',
theme: 'dark',
adapter: new BinanceAdapter(), // or feed: a DataFeed it pulls from (see Realtime)
historyLimit: 500,
trading: true,
features: { 'toolbar.replay': false }, // the widget's switches: see Customization
onReady: (chart, widget) => { /* once built, just after new ChartWidget() returns */ },
})
widget.getChart().setData(...)
widget.destroy() The bars
| Bar | What it holds |
|---|---|
| Toolbar | The symbol and its info; the intervals (the pinned ones as buttons, and a menu of them all by unit, minutes to
months, a star on each to pin it); the chart type as its icon; Indicators (a dialog: see Indicators), and Compare when there is a data adapter; undo and redo. On the
right: layouts, bar replay, a Trade menu (a new order, long and short brackets, the depth ladder and the
account panel), then screenshot, settings, the theme and fullscreen; alerts and the object tree too where
there is no rail (a phone, or features: { dock: false }). What doesn't fit folds under “more”. |
| Drawing tools | Each group's menu names its tools' shortcuts (Alt+T a trend line) and has a star on each row to pin it to the top. At the bottom: the drawing style, the magnet, the eraser, the zoom area, staying in drawing mode, lock, hide, and the trash button: its menu removes the drawings, the indicators or both, each with how many, in one undo step. The magnet, lock and hide buttons each have a menu in their corner (or a right click, or an arrow key): the magnet's picks weak or strong, and the button turns the magnet on at it and off; the lock's locks the drawings, the positions and orders, or all; the hide's hides the drawings, the indicators, the positions and orders, or all, ticking what is hidden. What a menu picks is what its button does from then on. Hiding the indicators hides the ones that showed, and showing them again brings back those only. |
| Status bar | Range presets and go to date; the market's status, the connection, a clock in the display time zone (it
opens the zones to pick from) and the price scale's % · log · auto switches. |
| For a selected drawing | Its colour, width and line style, settings, an alert, lock, more and delete. It waits near the top of the price pane, clear of what you drew (at its foot on a narrow chart), whichever pane the drawing is on. Drag it by its grip and it stays there for the next drawing; double-click the grip to send it back. |
| Dock | A rail at the outer edge with a button for each panel: the watchlist, alerts, the object tree, the data window and the symbol info. See The dock. |
The dock
The widget's panels sit beside the chart, one at a time, opened from the rail at the outer edge (on the left in
a right-to-left widget). A rail button opens its panel, or shuts it when it is the one open; so does each
panel's close button. No panel opens by itself: the chart has the room until one is asked for
(widget.openPanel('watchlist') opens one from your code). Drag the panel's edge, or use the arrow keys on it, for a width from 233 to 377 px (262 to start),
kept in this browser; it never takes more than 38.2% of the row, the chart keeping the rest.
On a phone, or in a widget narrower than 641 px, there is no rail: a panel rises from the bottom over the chart,
starts shut and shuts on Escape; a panel open as the widget turns narrow (a tablet turned) shuts. Alerts and the object tree open from the toolbar there, the symbol info from the ⓘ by the symbol, and any panel from your own code. The charts of a ChartWidgetGrid have no rail each, unless its widget.features turn dock on.
A page of your own goes in the same dock with addDockPage: its button on the rail after the
built-in ones, and your element under the dock's header (its label and a close button), in the widget's --tcw-* tokens. openPanel(id) opens it, getOpenPanel() reports it, and onShow is called each time it opens, once it has its size. remove() takes it away,
shutting it first if it is open. On a phone there is no rail, as for the built-in panels: open it from a control
of yours. An id a built-in panel or another page has gives null. The onPanelChange option is told the open panel's id, or null, however it changed: the rail, a close button, your code,
a widget turning narrow.
widget.openPanel('watchlist') // 'watchlist' | 'alerts' | 'objectTree' | 'dataWindow' | 'symbolInfo' | 'depthLadder' | 'tape', or a page's id; false if not there
widget.getOpenPanel() // the panel open, or null
widget.closePanel()
const figures = document.createElement('div')
const page = widget.addDockPage({
id: 'figures', label: 'Key figures', icon: 'info', element: figures, // icon: a built-in name or an <svg> of yours
onShow: () => drawFigures(figures, widget.getSymbol()),
onHide: () => {},
})
widget.openPanel('figures')
page.remove()
new ChartWidget(host, { onPanelChange: (panel) => keepOpenPanel(panel) }) // 'figures', 'watchlist'… or null
new ChartWidget(host, { features: { dock: false } }) // no rail: the toolbar opens the panels
new ChartWidget(host, { features: { 'dock.dataWindow': false } }) // no button for the data window Symbol search, Compare and Go to
Symbol search opens from the symbol on the toolbar, Ctrl/⌘+P,
or a letter typed on the chart, which it starts with. It lists your symbols until something is
typed, then asks your feed's search (searchSymbols, or the adapter's) once typing pauses. A row starts
with a badge (the symbol's logo, else the first letter of its ticker in its kind's colour), then the symbol, its
name, its kind and its exchange in columns, the chart's own marked. On a phone the exchange goes under the
ticker, so a long one (SIMULATED, ALL VENUES) reads whole and tells two venues' rows apart. Tabs keep the list to one kind (stocks, crypto)
and stay put as you type; when the rows come from two or more exchanges, a list beside them keeps it to one. Both
narrow the rows on hand and do not search again: a search returns a page of results (the adapter's is asked for
50), so HNX picked after typing V shows the HNX ones among them, not every HNX symbol with a V. The
list shows the best 200 rows, and a line under it says how many more typing would narrow. With no search, typing finds your symbols by ticker and by
name, with or without Vietnamese marks (ngan hang finds “Ngân hàng”). features: { symbolTyping: false } leaves letters typed on the chart alone.
Give symbols as SymbolInfo and the list opens with names, kinds, exchanges and logos;
the toolbar's symbol and the symbol info panel take a name and an exchange from them where the chart knows none.
A feed's search results win over these words and keep your logo; what the chart knows of its own symbol gives the search only a name or a logo it lacks, as it may name the kind and the exchange in other words than your list (stock for Cổ phiếu, a broker for the exchange). Price steps and hours given here are not applied to the chart: those come from the adapter's resolveSymbol or chart.setSymbolInfo.
new ChartWidget(el, {
symbols: [
{ symbol: 'VNM', description: 'Vinamilk', type: 'stock', exchange: 'HOSE', logo: '/logos/vnm.svg' },
'FPT', // a ticker alone, as before
],
}) A last price and a day's changePercent on a symbol, given with your symbols or in a search's results, show in two columns of their own at the end of its row (on a phone,
the change under the price), the change in the up or down colour; when no row listed has either, the columns are
left out. A number is written in the symbol's pricePrecision decimals, else by its size, in the
widget's number locale; text is written as it is. The widget fetches none of them: your app gives what it has. A
search's figures show while its results do and are not kept for the next time the search opens.
widget.setSymbols([
{ symbol: 'BTCUSDT', exchange: 'Binance', last: 61668.46, changePercent: 0.37 },
{ symbol: 'VCB', exchange: 'HOSE', last: 61.2, pricePrecision: 2, changePercent: -0.65 },
]) A logo is an https: or http: address, a path on your site, a blob: URL or an image written in data: (PNG, JPEG, GIF, WebP, AVIF or SVG); anything
else is ignored. It is only ever loaded as an image, with no referrer, so your page's img-src policy
must allow its host; one that fails to load shows the letter. The letters take their colours from --tcw-kind-1 … --tcw-kind-5 (stock, futures, index, crypto and perpetuals, forex, in English, Vietnamese, Japanese, Chinese or Korean words; a warrant takes the futures' colour, a fund or an ETF the index's, a bond the forex's; another kind gets one by its words), set for the dark and the light theme.
Once a search has told of a symbol, the feed's words name it on the list the search opens with too, not only
among the results. A name, kind, exchange or logo that isn't text (a JSON feed's null, a numeric
exchange code), in a feed's results or in what the chart knows, counts as not given: it neither shows nor erases yours. A symbol shows as its ticker,
without the venue before a colon (BINANCE:BTCUSDT reads BTCUSDT; HYPERLIQUID:xyz:NVDA, NVDA) on the toolbar, in the legend, the rows and the info panel: the venue goes in the exchange column when the feed names none, and the whole symbol shows on hover; on a phone the kind tabs
scroll in one line and fade at an end with more past it. What the chart knows of its symbol names it on the
toolbar and in the info panel when it is of the same symbol (in any case, with or without a venue before a colon)
or was set since the symbol changed, so a feed's own spelling (BTC-USD for BTCUSD)
still counts.
Compare is the same dialog with Add as under the search and what is compared listed first (see Comparing symbols).
Go to (the calendar on the status bar, Alt+G, or the chart's menu) has two tabs. Date centres the bar of a day and a time; Custom range shows the bars between two of them edge to edge, starting from those on screen. The month under the fields fills the date field in hand, and after a range's start it moves on to its end. On daily bars and longer there is no time to give, and days after today can't be picked. Dates and times read in the display time zone.
Widget keyboard shortcuts
| Shortcut | Action |
|---|---|
| Ctrl / ⌘ + K | Command palette: the widget's own commands with their keys (go to, reset the view, save the layout, the panels…), the drawing tools, chart types, intervals and indicators; the ones used last come first |
| Ctrl / ⌘ + P | Symbol search: your symbols, or your feed's search as you type |
| A–Z | Search for a symbol, starting with the letter typed (features: { symbolTyping: false } turns it off) |
| Ctrl / ⌘ + S | Save the layout (asks for a name the first time) |
| 0–9 | Type an interval (5, 15m, 1h, 1D) and press Enter (intervalTyping: false turns it off) |
| Alt + T / H / J / V / C / F | Trend line, horizontal line, horizontal ray, vertical line, cross line, Fibonacci retracement |
| Alt + R | Reset the view: every bar in sight, the price scale fitted to them |
| Alt + I | Invert the price scale |
| Alt + G | Go to a date |
| ? | The shortcut sheet, searchable by what a key does or by the keys |
| Alt + click chart | Pin OHLC tooltip at the hovered bar (delta to live crosshair shown) |
| Press and hold on the chart | The floating OHLCV tooltip for the bar under the pointer, while the button is held: it follows the pointer, and the chart does not pan (chartOptions: { features: { crosshairTooltip: true } } has it follow a pointer that only hovers, false never shows it) |
| Esc | Unpin tooltip / cancel drawing |
| Shift + ← / → | Step the replay back / forward |
| Space | Play or pause the replay (on the chart or its track; outside a replay it fits the chart) |
| Esc | Stop picking the replay's start bar |
| Click symbol in toolbar | Opens the symbol search modal |
| Click play in toolbar | Opens the bar replay scrubber (play/step/seek/speed) |
Change the symbols on offer at runtime with widget.setSymbols(['BTCUSDT', 'ETHUSDT', …]), tickers or SymbolInfo as in symbols. A watchlist made from symbols (no lists,
nothing kept) is replaced with them, and asks quotes for every one: for a long list from your server, give the
watchlist lists of its own.
const widget = new ChartWidget(el, {
adapter: feed,
watchlist: { lists: [{ id: 'main', name: 'Main', symbols: ['VNM', 'FPT'] }] },
})
widget.setSymbols(await loadMarkets()) // your server's SymbolInfo[]: the search opens with them, the watchlist stays Data Window
A floating readout of the exact O/H/L/C/V, bar change, and every active indicator's value at the hovered bar — updates live as you move the crosshair. Toggle it from the command palette (Ctrl/⌘ K → "Toggle Data Window"). On a touch screen, touch the chart to put the crosshair on a bar. Prices, the change and the values of indicators on the price pane read as the chart writes prices; those of indicators in a pane of their own as their legend row does; all in the chart's number locale. A compare, a spread or a ratio, and a line on a scale of its own, read in the decimals their size calls for, not the chart's prices'. On Renko, Kagi and the like the data window shows the brick under the pointer and its change from the brick before.
Shareable view (deep links)
Encode the whole view — symbol, timeframe, chart type, price scale,
indicators (with params), drawings, and the Chart Settings changed from the
defaults (not the time zone or number format) — into a compact, URL-safe
string for deep-linking. With shareUrl: true the widget restores a #tcw=… hash on load and the "Share View" command palette action
copies a link to the clipboard.
const widget = new ChartWidget(host, { shareUrl: true })
const token = widget.exportState() // portable string
await widget.importState(token) // restore a view
await widget.copyShareLink() // copy "<url>#tcw=<token>" Named layouts
The layout button on the toolbar saves the chart under a name: symbol,
interval, price scale, chart type, indicators, drawings, alerts and the Chart Settings (not the theme, the time zone or
the number format, which stay the viewer's). Open, rename and delete layouts from its
menu; the layout open auto-saves as it changes, and Ctrl/⌘ S saves
it. Layouts live in this browser's localStorage unless you give a storage: four calls, each may return a promise.
import { ChartWidget, type LayoutStorage } from '@tradecanvas/chart/widget'
const server: LayoutStorage = {
list: () => api.get('/layouts'), // [{ id, name, symbol, timeframe, updatedAt }]
load: (id) => api.get(`/layouts/${id}`), // { ...summary, content } or null
save: (layout) => api.put(`/layouts/${layout.id}`, layout),
remove: (id) => api.delete(`/layouts/${id}`),
}
const widget = new ChartWidget(host, {
layouts: { storage: server, autoSave: true, openLast: true }, // or false for none
})
const layouts = widget.getLayoutSession()!
await layouts.saveAs('Swing BTC')
await layouts.open(id)
layouts.current() // { id, name, … } or null
layouts.setAutoSave(false)
// The content alone, to keep wherever you like
const json = widget.getLayoutContent()
await widget.applyLayoutContent(json) localStorageLayouts(prefix) and memoryLayouts() are the
two storages that ship. Stored content is read defensively: a layout that does
not parse is refused, not half applied. Each layout records its kind ('chart' or 'grid'), so a widget and a
grid can share one storage and each lists only its own. Saving, opening and
auto-saving run one at a time, so a save never lands in a layout opened after it.
Chart settings
The settings dialog's switches and choices (the volume and market profiles,
swing markers, session shading, prior-period levels, grid, legend, crosshair,
scales, time zone, number format) are the widget's Chart Settings. Read them
with getSettings(), a copy; change some with setSettings(patch), which drops what it can't read, keeps numbers
in the dialog's ranges and records no undo step; and hear of each change with onSettingsChange(listener), which returns the function that stops
it. It is called once when the dialog closes with OK, never for Cancel or for
a change that changes nothing. Until the chart has bars, setSettings leaves auto-scale on, since off holds the price range on screen and there is none
yet: the settings onSettingsChange gave, auto-scale off after a drag
on the price axis, are safe to give back right after the constructor. With persistSettings: true the
widget keeps them in this browser and puts them back on the next visit.
const widget = new ChartWidget(host, {
chartOptions: { timeZone: 'UTC' },
persistSettings: true, // or { key: 'myapp:settings' }
})
widget.setSettings({ volumeProfileVisible: true, timezone: 'exchange' })
widget.getSettings().timezone // 'exchange'
const stop = widget.onSettingsChange((settings) => {
api.put('/me/chart-settings', settings) // your server, say
})
stop() getSettings() reads back what was set on getChart() too,
so a layout or a link saves it as it is. The chart gives these settings with isVolumeVisible(), isLegendVisible(), isBarCountdownVisible(), isIndicatorValueLabelsVisible(), isLeftPriceScaleVisible(), getMarketProfileConfig(), getDepthHeatmapConfig(), getPivotMarkersConfig() and getPeriodLevelsPeriod(), beside each overlay's is…Visible().
- persistSettings keeps, per browser, what the user changed
from your values. A kept value wins over
chartOptions, and Reset goes back to yours. It leaves out the log and auto-scale flags and a chart type's own settings (the Renko box and the like), which are the chart's state. Give each widget on a page akeyof its own; a grid gives each of its charts one. It can't tell who made a change: what you set withsetSettings(inonReady, say), and what an opened layout brings, are kept as the user's too, and win overchartOptionson the next visit even once your code stops setting them. Setting one back to yourchartOptionsvalue takes it out of what is kept. What an opened share link brings is someone else's choice: it shows for that visit only, is not kept, and calls noonSettingsChangelistener (the next change tells them all). - Named layouts keep all of them but the time zone and the
number format, which stay the viewer's, and auto-scale, which a drag on the
price axis turns off. In the layout's JSON they are under
settings, except the scale and its flip, which have fields of their own, and a chart type's own settings, which are in the chart's state. A layout saved before they were kept has none, and opening it leaves the settings as they are. An older version of the library opens a newer layout without them, and its auto-save writes it back without them. - Share links carry the ones the sender changed from the
defaults, but the time zone, the number format and auto-scale. A chart
type's own settings in a link set only the types the sender set and the
type shown (at its defaults when the sender left it there); the viewer's
settings of the other types stay. For the
switches your
featuresset (the legend, the volume, the bar countdown, the indicators' value labels) the defaults are where they set them, so a switch the sender's app turned off isn't sent as a change. - Switched-off features: where your
featuresturn off the legend, the volume, the bar countdown or the log scale, nothing kept, shared, opened, set or applied from a chart template turns them on, and the settings dialog doesn't offer the legend's or the volume's switch and colours. - Per-symbol layouts (
persistLayouts) andchart.saveState()hold a chart type's own settings, which are part of the chart's state, and none of the others.
Per-symbol layouts
Separately, persist per-symbol indicator stacks, drawings, alerts, and chart type
to localStorage automatically:
new ChartWidget(host, {
symbol: 'BTCUSDT',
symbols: ['BTCUSDT', 'ETHUSDT', 'SOLUSDT'],
adapter: new BinanceAdapter(),
persistLayouts: true, // or { keyPrefix: 'myapp:', debounceMs: 2000 }
})
// Reset a single symbol's layout
widget.clearSavedLayout('BTCUSDT') Layouts flush on symbol switch and on widget destroy so nothing is lost
when the user navigates away. Of the Chart Settings they hold
only a chart type's own; persistSettings keeps the others.
Drag-and-drop data import
Drop a CSV or JSON file onto the chart to load it instantly. Enabled by
default — disable with dragDropImport: false. The parser
handles common column layouts (time, open, high, low, close, volume),
ISO 8601 timestamps, and unix seconds/ms.
// Programmatic use
import { parseOHLCV } from '@tradecanvas/chart'
const { data, rowCount, skipped } = parseOHLCV(csvText)
chart.setData(data) Timeframe resampling
Feed the widget your finest-resolution series with widget.setData() and the toolbar timeframe buttons aggregate it on the client — one dataset
drives every resolution, no refetch. Active whenever no live adapter is
attached; opt out with resampleTimeframes: false. Weekly buckets
anchor to Monday by default (weekStartsOn: 0 for Sunday).
const widget = new ChartWidget(host, {
symbol: 'BTCUSDT',
timeframe: '1h',
timeframes: ['5m', '15m', '1h', '4h', '1d', '1w'],
})
widget.setData(oneMinuteBars) // base series; clicking 4h/1d/1w resamples it
// Or build bars yourself
import { resampleBars, timeframeBucketStart } from '@tradecanvas/chart'
const hourly = resampleBars(oneMinuteBars, '1h') // OHLC merged, volume summed
const days = resampleBars(oneMinuteBars, '1d', { timeZone: 'Asia/Ho_Chi_Minh' }) // from 00:00 there
const dayStart = timeframeBucketStart(trade.time, '1d', { timeZone: 'Asia/Ho_Chi_Minh' }) Calendar-aware bucketing: minutes and hours (1h and shorter) floor to multiples of the
frame since the Unix epoch. Days, weeks (from the configured week start), months,
quarters and years start at the exchange's midnight, and so do the hour frames that
divide a day (2h, 3h, 4h, 6h, 8h, 12h). For the bars given to widget.setData,
that is the midnight of the symbol's timeZone (setSymbolInfo), else
the market's (setMarket), else UTC's. The timeframes a feed lacks start at the
midnight of the zone its resolveSymbol names, else UTC's: the market's zone
doesn't move them. A day the clocks change is 23 or 25 hours
long. Daily bars stamped at 00:00 UTC are read as the dates they name, so a Monday stays
in its own week west of UTC and the weeks keep 00:00 UTC stamps. Input bars are never
mutated.
A daily bar shows the date it stands for, whatever zone the chart shows: one stamped at
00:00 UTC its UTC date, one built at the exchange's midnight the exchange's date (on the
time axis, the crosshair and its card, the tooltip Alt-click pins, and the bar times a screen reader reads). For bars you build yourself, timeframeBucketStart(time, timeframe, { timeZone }) gives the
start of the bar a time falls in.
Watchlists
A panel of the dock: lists of symbols, a line each of last price, move and % change under the columns' names (a sparkline in place of the move with sparkline: true; the venue before a ticker, as in HYPERLIQUID:xyz:NVDA, shows on hover). Lists
are switched, created, renamed and deleted from its menu; symbols are added from the symbol search
(+), removed, and reordered by dragging or Alt+↑/↓. Rows take quotes from the adapter's subscribeQuotes, a quote source of yours, or what you push.
const widget = new ChartWidget(host, {
symbol: 'BTCUSDT',
adapter: new BinanceAdapter(), // its quotes fill the rows
watchlist: {
lists: [
{ id: 'majors', name: 'Majors', symbols: ['BTCUSDT', 'ETHUSDT'] },
{ id: 'alts', name: 'Alts', symbols: ['SOLUSDT', 'ADAUSDT'] },
],
persist: true, // kept in this browser; a list added here later joins them
onChange: (lists, active) => save(lists), // or keep them yourself
},
})
widget.addToWatchlist('BNBUSDT', 'alts')
widget.setActiveWatchlist('alts')
widget.setQuotes([{ symbol: 'AAPL', last: 190.2, prevClose: 188.1 }]) // from your own feed
widget.getQuote('AAPL') watchlist: true shows one list of symbols, as before; setWatchlistEntry still pushes a row's price, move and sparkline.
Symbol info
A panel of the dock, from the ⓘ by the symbol, the rail, or the command palette: the symbol's names, last price and move, the market's status counting down to the next open or close, the day's open, range, volume, prior close, bid and ask, tick size, currency, zone and trading hours, and news. The status bar shows when the market is closed.
new ChartWidget(host, {
symbol: 'AAPL',
news: (symbol, limit) => api.headlines(symbol, limit), // or the adapter's fetchNews
})
widget.toggleSymbolInfo(true) The headlines also stand on the chart as marks, on the bars they were published in
(newsMarks: false leaves them out); see Marks under Trading.
Navigation, undo and direction
Buttons over the chart — zoom out and in, scroll earlier and later (held, they keep going), go to the latest bar, reset —
show while the mouse is near the plot's bottom edge, out of the way of the data, or while one has focus
(navigation: false leaves them out). Settings changes and
chart type changes are undone with Ctrl/Cmd+Z, with drawings and indicators. In Arabic, Hebrew,
Persian or Urdu the widget mirrors (dir: 'auto'; or 'rtl' / 'ltr');
the chart keeps time running left to right.
Drawing favorites
Pin frequently-used drawing tools to a strip at the top of the sidebar.
Right-click any tool (in a group flyout or the strip itself) to pin or unpin
it; the set persists to localStorage. Seed the initial pins with drawingFavorites:
new ChartWidget(host, {
drawingFavorites: ['trendLine', 'horizontalLine', 'fibRetracement', 'rectangle'],
}) The star button on the sidebar shows the pinned tools as a favorites toolbar floating over the
chart instead: drag its grip to put it anywhere on the chart, press a tool to pick it, right-click one to
unpin it. Whether it shows and where it was left are kept in this browser, one setting for the widgets of a page, and
the sidebar's strip steps aside while it shows; with its switch off the pins stay on the strip. It first appears centred at the chart's top. features: { favoritesBar: false } leaves out the bar and its button.
Drawing style & templates
The palette button on the drawing sidebar opens a style popover — pick colour, line width, and line style for the next drawing (and the selected one), and save named templates persisted to localStorage for one-click reuse. Programmatic equivalents:
chart.setDrawingStyle({ color: '#e8505b', lineWidth: 2, lineStyle: 'dashed' })
chart.getDrawingStyle()
chart.setSelectedDrawingStyle({ color: '#1fa874' }) // restyle the selected drawing Object tree
The rail's layers button (the toolbar's, where there is no rail) opens the
object tree in the dock, listing every active indicator, named as its chip names it (EMA 20, Compare ETHUSDT),
and every drawing. Indicators can be removed; drawings get per-item
show / hide, lock / unlock, settings and delete, and groups are listed with
their drawings under them. Enabled by default — disable with objectTree: false. The drawing controls map to:
chart.getDrawings() // DrawingState[] (id, type, visible, locked, intervals)
chart.setDrawingVisible(id, false) // hide a single drawing
chart.isDrawingShown(id) // not hidden, and on this interval
chart.setDrawingLocked(id, true) // lock it from edits
chart.removeDrawing(id)
chart.groupDrawings(ids, 'Weekly levels') // hidden, locked and selected together
chart.renameDrawingGroup(groupId, 'Old highs')
chart.getActiveIndicators() // active indicator instances
chart.updateIndicator(instanceId, { period: 50 }) // re-tune params live
chart.removeIndicator(instanceId) Drawing settings and menu
Double-click a drawing, or use its gear in the object tree, to open its settings in tabs: Style (the line, its ends, the fill, the tool's own settings such as Fibonacci levels, extensions and labels), Text for the tools that write, Coordinates (its points in the chart's time zone) and Visibility (the intervals it shows on), with a Template menu, Cancel and OK at the foot. Right-click a drawing for its menu: settings, an alert on its line, order, group, lock, hide, duplicate and delete. The sidebar also has an eraser, a zoom tool and a magnet, weak or strong from its menu. See Drawing tools for the API underneath.
The gear button on each indicator row opens a settings dialog that introspects the indicator's parameters (numbers, toggles, colors) and
applies edits live via updateIndicator — no need to remove and
re-add to change a period or colour.
The object tree's Compare section lists every compare, as the compare
dialog does: each symbol with its way (percent change, own scale, own pane, spread, ratio
or correlation) and a button to take it off. With a live adapter, its + button opens the
compare dialog. Whatever the way, the widget fetches the other symbol's bars through adapter.fetchHistory before it adds the compare, and adds nothing when they
don't come (the fetch fails, or there are no bars at this interval); a toast says why.
A compare a saved state brings back stays on the chart when its bars fail to load, and
fills on an interval that has them. Comparisons refetch automatically on timeframe
change. Programmatic equivalents:
widget.addCompareSymbol('ETHUSDT') // fetches + overlays (needs an adapter)
await widget.addCompareSymbol('ETHUSDT', 'scale') // its bars first; nothing added if they don't come
// or drive the chart directly with your own data
chart.addCompareSymbol('ETHUSDT', 'ETH', ethBars, '#627eea')
chart.setCompareMode('percent') // 'percent' | 'absolute'
chart.setScaleMode('percentage') // each line's change, read on the axis
chart.removeCompareSymbol('ETHUSDT') Alerts on prices, indicators and drawings
chart.createAlert(request) sets an alert. on is what it watches: the price (unless
told), a line of an indicator, or a moment an indicator says (alertConditions). It is compared with a value, or with another line or a drawing (a trend line, a ray, any line of a channel), or it
measures a move. trigger is how often it fires: 'once' (unless told), 'oncePerBar', 'oncePerBarClose' or 'everyTime' its condition comes to hold. expiresAt ends it, onBarClose has it look only at bars that closed. A request that does not
fit together throws a RangeError that says why.
const ema = chart.addIndicator('ema', { period: 9 })
const macd = chart.addIndicator('macd')
const line = chart.addDrawing({ type: 'trendLine', anchors, options: { extendRight: true } })
// an indicator's line at a value, as each bar closes, until the end of the year
chart.createAlert({
on: { indicator: ema }, condition: 'crossing', value: 30,
trigger: 'oncePerBarClose', expiresAt: new Date('2026-12-31T16:28'), message: 'EMA 9 crossed 30',
})
// the price, or an indicator, crossing a drawing
chart.createAlert({ with: { drawing: line }, condition: 'crossingUp', message: 'Broke the trend line' })
chart.createAlert({ on: { indicator: ema }, with: { drawing: line } })
// one line crossing another; the price crossing one
chart.createAlert({ on: { indicator: macd, line: 'macd' }, with: { indicator: macd, line: 'signal' }, condition: 'crossingUp' })
chart.createAlert({ with: { indicator: ema }, condition: 'crossingDown' })
// a move, and a moment a script or an indicator of yours says
chart.createAlert({ condition: 'movesUp', percent: 5, bars: 12 })
chart.createAlert({ on: { indicator: script, condition: 'a0' }, trigger: 'oncePerBar' })
chart.updateAlert(id, { value: 35, trigger: 'everyTime' }) // the rest as it was, armed anew; null takes its end or its message away
chart.removeAlert(id)
chart.on('alertTriggered', (e) => {
// { id, message, condition, channel, drawingId?, value, time, symbol, timeframe, … }
fetch('/api/alerts', { method: 'POST', body: JSON.stringify(e.payload) })
})
chart.on('alertExpired', (e) => e.payload) // it reached its time without firing Alerts check on every price, from setCurrentPrice or a connected feed, together with the lines they
watch. They run in the page: they fire while the chart is open. An alert on a drawing goes with it, and moves as it
is moved. A drawing in an indicator's pane is crossed by an indicator of that pane. A trend line has a price only
between its two points unless it is extended: once the bars pass its end, an alert on it waits, with no error, and
checks again if the line is extended or moved over the latest bar. Extend the line (its extendRight option, or
a ray) for an alert that is to follow it on. Alerts are saved with a layout. An alert that has fired and does not
repeat, or that reached its expiresAt, is done: a layout or loadAlerts does not bring it back. addAlert, with the same by place, is the older way:
chart.addAlert(NaN, 'crossingUp', 'above the 50 EMA', 'price', undefined, { target: `${ema}:value` })
chart.addAlert(70, 'greaterThan', 'RSI closed above 70', `${rsi}:value`, 'RSI', { onBarClose: true }) In the widget, Add alert in an indicator's menu or a drawing's opens the alerts panel on its form, filled
for it; widget.openAlertForm(request) does the same from your own button, with the same on, with, value, condition, trigger and message.
The toolbar bell opens a floating panel to add, list, and delete price
alerts; a toast fires when one triggers. Alert lines are also draggable — grab one on the chart and slide it to re-price
(moving an alert re-arms it). Enabled by default — disable with alerts: false. Drive it programmatically via the Chart API and the typed alert events:
// Add from code (condition: 'crossing' | 'crossingUp' | 'crossingDown'
// | 'greaterThan' | 'lessThan')
const id = chart.addAlert(64200, 'crossingUp', 'breakout')
chart.removeAlert(id)
chart.getAlerts() // PriceAlert[]
chart.saveAlerts('tcw:alerts:BTCUSDT') // localStorage persistence
chart.loadAlerts('tcw:alerts:BTCUSDT')
// React to triggers
chart.on('alertTriggered', (e) => {
console.log('hit', e.payload.price, e.payload.message)
})
// also: 'alertAdd' / 'alertRemove' / 'alertUpdate' (fired on drag)
// Indicator alerts: bind to an indicator line via channel '<instanceId>:<key>'.
// In the widget, the alerts panel's source dropdown lists every active line.
const ema = chart.addIndicator('rsi')
chart.addAlert(70, 'crossingUp', 'RSI overbought', `${ema}:rsi`, 'RSI') Opt into a sound and/or desktop notification when an alert fires (both off by
default). sound: true plays a built-in beep; pass a URL for a
custom one. desktop: true uses the Notification API and asks
permission on first use.
new ChartWidget(host, {
alertNotifications: { sound: true, desktop: true },
}) Feature switches
132 switches, every one on until turned off: a name without a dot is a whole capability, off wherever it shows; a dotted name is one place. They change while the widget runs. All of them, and the older options they stand for, are in Customization.
new ChartWidget(host, { features: { 'toolbar.replay': false, 'sidebar.patterns': false, hotkeys: false } }) // one button, a section of drawing tools, every key
widget.setFeatures({ sidebar: false, statusBar: false })
widget.isFeatureOn('sidebar') // false
widget.getFeatures() // every switch, on or off Your own buttons and menu entries
Add buttons to the toolbar (a built-in icon or an element of yours, text, a switch) and entries to the chart's right-click menus, after the widget's own.
const news = widget.addToolbarButton({
id: 'news',
label: 'News',
icon: 'bell', // or an <svg> element; or text: 'News'
side: 'right', // 'left' sits with the chart controls
toggle: true,
onClick: () => news?.setActive(togglePanel()),
})
news?.setText('3')
news?.remove()
new ChartWidget(host, {
chartMenuItems: ({ area, price, time }) => area === 'plot' && price !== undefined
? [{ label: `Copy ${price.toFixed(2)}`, icon: 'check', onSelect: () => copy(price) }]
: [],
}) Also a menu button on the toolbar, buttons on the drawing sidebar, items on the status bar, places of your own in each bar and over the chart, and entries at the end of a drawing's or an indicator's menu (see Customization):
widget.addToolbarDropdown({ id: 'scans', label: 'Scans', icon: 'layers', items: () => [...] }) // asked for each time it opens
widget.addSidebarButton({ id: 'ruler', label: 'Ruler', icon: 'ruler', toggle: true, onClick })
widget.addStatusBarItem({ id: 'latency', text: '12 ms', label: 'Latency' })
widget.getSlot('chart') // a layer over the chart
widget.addHotkey({ keys: 'Alt+N', label: 'New note', onPress }) // a shortcut of yours; it replaces a widget shortcut on the same keys
new ChartWidget(host, {
drawingMenuItems: ({ id, type }) => [{ label: 'Share', onSelect: () => share(id) }],
indicatorMenuItems: ({ instanceId, indicatorId }) => [{ label: 'Explain', onSelect: () => explain(indicatorId) }],
}) ChartWidgetGrid
Several chart widgets side by side, each with its own symbol, interval, indicators and drawings. A bar above them picks the arrangement, links the charts and saves the whole grid as a named layout. The chart pressed last is the active one (outlined).
import { ChartWidgetGrid } from '@tradecanvas/chart/widget'
const grid = new ChartWidgetGrid(host, {
layout: '2x2', // '1x2', '2x2', '3x3', '1+2', '1/3'… (all under ChartGrid)
widget: { timeframe: '1h' }, // every chart
adapter: () => new BinanceAdapter(), // one per chart: an adapter keeps one stream
// or widget: { timeframe: '1h', feed }: one DataFeed serves every chart
cells: [{ symbol: 'BTCUSDT' }, { symbol: 'ETHUSDT' }, { symbol: 'SOLUSDT' }, { symbol: 'BNBUSDT' }],
sync: { crosshair: true, time: false, symbol: false, interval: false, drawings: false, replay: false },
})
grid.setLayout('1x2')
grid.setSync({ interval: true }) // lines the others up with the active chart
grid.applyOverrides({ 'grid.vertical.visible': false }) // every chart's look, and the charts it adds
grid.setFeatures({ 'toolbar.replay': false }) // every chart's switches, and the charts it adds
grid.getActiveWidget().getChart()
grid.getLayoutSession()?.saveAs('Majors')
// The charts as one picture, each in its cell: a file, the print dialog, a PDF
grid.screenshot('majors', { pixelRatio: 2 })
await grid.copyScreenshot() // onto the clipboard, as a PNG
const sheet = await grid.toPdf({ title: 'Majors' }) // light and at twice the pixels, as a chart's
// Each chart as it is made (at the start, and when the grid grows)
new ChartWidgetGrid(host, {
onChartAdd: (widget, index) => widget.getChart().addIndicator('ema', { period: 21 }),
}) The bar's camera button does the same from a menu: it saves the charts' picture as an image,
copies it, prints it or saves it as a PDF, named after the symbols shown (charts for more than three). picture: false leaves the button out; it is hidden as well
while the charts' screenshot switch is off, and has no copy entry while copyImage is.
Crosshair sync shows the time under the pointer on every chart; time sync scrolls and zooms the others with the chart being used; drawings are copied to the charts showing the same symbol (switching it on puts their drawings together, none lost); replay sync replays the others to the same time as the chart being replayed (a chart whose bars are longer than the replay's steps shows the whole bar that holds that time). Charts the grid shrinks from are put away, kept in the saved layout, and come back as they were when it grows again; a brand-new chart opens on the active chart's symbol and interval when those are synced.
ChartGrid
Synchronized multi-chart layouts of headless charts (no toolbar); see ChartWidgetGrid for the full UI.
import { ChartGrid } from '@tradecanvas/chart'
const grid = new ChartGrid(host, { layout: '2x2', theme: 'dark' })
// One adapter per chart: an adapter keeps one stream
await grid.connectAll(() => new BinanceAdapter(), ['BTCUSDT','ETHUSDT','SOLUSDT','BNBUSDT'], '5m')
grid.setLayout('1x2') Layouts, the same for ChartGrid and ChartWidgetGrid.
Plain grids are named rows × columns ('1x2' is one row of two): '1x1', '1x2', '2x1', '1x3', '3x1', '2x2', '1x4', '4x1', '2x3', '3x2', '2x4', '3x3'.
The others have one large chart: '1+2' and '1+3' (large on the left, two or three
stacked on the right), '2+1' (two stacked on the left, large on the right), '1/2' and '1/3' (large on top, two or three below), '2/1' (two on top, wide below).
The large chart is the first, except in '2+1' and '2/1', where it is the last. GRID_SHAPES gives each layout's cols, rows and, for the
others, the areas its charts take ([col, row, colSpan, rowSpan], in chart order).
The bar of a ChartWidgetGrid shows the layout in use as one button that opens a picker
of them, a row for each chart count; layoutChoices narrows what it offers.