Эта страница пока не переведена на язык «Русский», поэтому показана на английском.

Finance charts

Charts for dashboards and reports, beside the candle chart. Each one is a class that takes an element and its options, sizes itself to the element and draws in the chart's dark or light theme; most follow the pointer with a tooltip.

The charts

ClassFor
BarChartValues by category: net flows, volume by session, returns by month. Grouped or stacked, upright or sideways, up and down from zero.
DonutChartParts of a whole: allocation, exposure by sector. A pie with innerRadius: 0.
ScatterChartTwo values per item: risk against return, valuation against growth; bubbles when a point has a size.
HistogramChartHow values spread: daily returns, trade results, with lines at the mean or a VaR.
CalendarChartA value a day on a calendar: daily returns, P&L, a trading journal.
MatrixChartA value for each pair of rows and columns: correlations, volume by hour and weekday.
CounterClockChartAverage price against average volume, bar by bar: the counter-clock cycle of a stock.
SparklineChartA small line in a watchlist row or a KPI tile.
GaugeChartOne value against bands: sentiment, risk, margin use.
HeatmapChartCells coloured by change, in a grid or a treemap sized by weight (market cap). With grouped, a sector map.
WaterfallChartSteps from a start to an end: P&L attribution, cash flows.
DepthChartCumulative bids and asks of an order book.
EquityCurveChartAn account's value over time, with drawdowns and a benchmark.
PayoffChartWhat an options position makes or loses at expiry, over the underlying's price: a spread, a straddle, a condor.
CurveChartValues against a strike or a tenor, a line for each series: a volatility smile, a term structure, a yield curve.
BoxPlotChartHow each group's values spread: returns by weekday, by month, by strategy.
RadarChartSeveral measures at once, a spoke each: a strategy's scorecard beside a benchmark's.
SunburstChartParts of a whole and the parts inside them: an allocation by asset class, then sector, then holding.
StackedAreaChartSeveral series one on another over time: what a total is made of, or how its mix changes.
SurfaceChartValues over two axes as a sheet in a 3D box you turn by dragging: implied volatility by strike and expiry, a profit by price and day, or as slices, an order book's depth over time.
Bar3DChartA column for each value in rows a series deep, in the same box: returns by quarter and asset class, volume by hour and weekday.
PerformanceDashboardA strategy report from a backtest: stats, equity, drawdown and monthly returns.

What they share

const chart = new BarChart(element, { categories, series, theme: 'dark' })

chart.setOptions({ mode: 'stacked' })   // any option, merged
chart.setTheme('light')                 // 'dark' | 'light' | a Theme
chart.screenshot('flows', { pixelRatio: 2 })   // a picture: see below
chart.destroy()                         // removes the canvas and its listeners

On a touch screen a tap shows the tooltip, and it stays until a tap elsewhere; a drag still scrolls the page. The charts draw on the screen's own pixels, so lines stay sharp at any zoom or display scaling. The depth, equity and waterfall charts size their margins to their labels, as the newer charts do.

Text is in the system's sans face, as the widget's figures are; font sets another ({ family: MONO_FONT_FAMILY } for the monospaced one), and a theme with a face of its own keeps it. locale (a BCP 47 tag such as 'vi') sets the language numbers and dates are written in; the browser's own otherwise. Every chart describes itself to screen readers in English unless ariaLabel says it in your words. A depth chart's spreadLabel and an equity curve's benchmarkLabel take the words drawn on them, and a dashboard's labels its titles and the names of its stats.

Each chart fills its element and redraws when the element resizes. Where a chart has a hover tooltip, crosshair: false turns it off. Bar, donut, scatter, histogram, calendar and matrix charts tell screen readers what they show (the canvas has an image role and a label); ariaLabel puts it in your words, for instance in your page's language. Numbers read with valueFormat (or xFormat / yFormat), else as 1,234.5 and, past ten thousand, 12.3K.

Pictures, paper, and drawing with no page

Every chart gives a picture of itself, as the price chart does: screenshot(filename, options) saves one, copyScreenshot() puts a PNG on the clipboard, and screenshotDataURL(), screenshotBlob() and toCanvas() hand it over. The chart is drawn again for the picture, with nothing that follows the pointer on it: at its own size by the screen's pixel ratio, or with the pixelRatio, the theme and the width and height the options give (it is laid out again for another size). print() opens the print dialog for the chart alone and toPdf() gives a PDF of one page, both in the light theme and at twice the pixels unless told otherwise; chartsToPdf makes one PDF of several charts (Pictures, print and PDF has the options).

import { chartsToPdf } from '@tradecanvas/chart'

equity.screenshot('equity', { pixelRatio: 3 })                 // equity.png
const wide = flows.screenshotDataURL({ width: 1200, height: 400, type: 'jpeg' })
allocation.print({ title: 'Allocation' })
const report = await chartsToPdf([equity, flows, allocation], { title: 'March' })

renderFinanceChart draws a chart on a 2D context of your own, with 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. Its second argument names the chart, by its class name without Chart and with a small first letter ('bar', 'equityCurve', 'boxPlot', 'surface', 'bar3d'; FINANCE_CHART_KINDS lists them), and the third is that chart's own options. It draws the size you give in the context's own units, over the theme's ground: scale the context first for more pixels.

import { createCanvas } from '@napi-rs/canvas'        // or another canvas for Node
import { renderFinanceChart } from '@tradecanvas/chart'

const canvas = createCanvas(1600, 800)
const ctx = canvas.getContext('2d')
ctx.scale(2, 2)                                        // an 800 × 400 chart at twice the pixels
renderFinanceChart(ctx, 'equityCurve', { data: equity, theme: 'light', font: { family: 'Inter' } }, { width: 800, height: 400 })
const png = canvas.toBuffer('image/png')

The context has to have what a browser's has: paths, text and its measuring, and getTransform. The text is drawn in the theme's font, so name one your canvas has with font. Nothing follows a pointer and nothing moves: a gauge is at its value. The performance dashboard is built of page elements and is not drawn this way; its charts are. The price chart has its own: renderPriceChart, on the API page.

Bar chart

import { BarChart } from '@tradecanvas/chart'

// Foreign net buying over ten sessions: green above zero, red below.
const flows = new BarChart(el, {
  categories: ['6/10', '7/10', '8/10', '9/10'],
  series: [{ name: 'Net', values: [-660, 860, -280, 230] }],
  colorBySign: true,                    // or { positive, negative }
  valueFormat: (v) => v + ' bn',
  onBarClick: ({ category, series, value, index }) => openDay(index),
})

// Several series side by side, or stacked: positives up and negatives down from zero.
new BarChart(el, {
  categories: ['Foreign', 'Proprietary', 'Retail'],
  series: [{ name: 'Buy', values: [820, 310, 4200] }, { name: 'Sell', values: [-760, -280, -4290] }],
  mode: 'stacked',
  orientation: 'horizontal',            // bars to the right, labels on the left
  showValues: true,
})

flows.update(categories, series)

Zero is always on the value axis. Hovering a category shows every series' value for it; the legend shows when there is more than one series (legend to choose). Labels that don't fit along the bottom show every few categories.

Donut chart

import { DonutChart } from '@tradecanvas/chart'

new DonutChart(el, {
  data: [
    { label: 'Stocks', value: 52 },
    { label: 'Bonds', value: 23 },
    { label: 'Cash', value: 15 },
    { label: 'Gold', value: 10, color: '#d4a017' },
  ],
  innerRadius: 0.6,                     // 0 for a pie
  centerLabel: 'Total',
  centerValue: '1.2B ₫',
  onSliceClick: (slice) => filterBy(slice.label),
})

Slices go clockwise from twelve o'clock; values of 0 or less are left out. Each slice shows its share where it has room, and the legend lists names and shares, beside the ring when the chart is wide and under it when not.

Scatter and bubble chart

import { ScatterChart } from '@tradecanvas/chart'

new ScatterChart(el, {
  series: [{
    name: 'Banks',
    points: [
      { x: 21, y: 9, size: 480, label: 'VCB' },   // size: market value; the bubble's area follows it
      { x: 34, y: 24, size: 170, label: 'TCB' },
    ],
  }],
  xLabel: 'Volatility',
  yLabel: 'Return, a year',
  xFormat: (v) => v + '%',
  yFormat: (v) => v + '%',
  showLabels: true,
  onPointClick: (point, series) => openSymbol(point.label),
})

The axes leave room for the largest bubble (maxRadius, 24 px by default), and lines mark x = 0 and y = 0 when the axes cross them (zeroLines: false to hide them).

Histogram

import { HistogramChart, histogramBins } from '@tradecanvas/chart'

new HistogramChart(el, {
  values: dailyReturns,                 // in percent
  binWidth: 0.5,                        // or bins: 20, or 'auto' (Sturges' rule)
  colorBySign: true,
  valueFormat: (v) => v.toFixed(1) + '%',
  markers: [{ value: mean, label: 'Mean' }, { value: var95, label: 'VaR 95%', color: '#e85a67' }],
})

histogramBins([1, 2, 2, 3, 10], { bins: 3 })
// [{ from: 1, to: 4, count: 4 }, { from: 4, to: 7, count: 0 }, { from: 7, to: 10, count: 1 }]

Calendar

import { CalendarChart } from '@tradecanvas/chart'

// A year of sessions, Monday to Friday, coloured by the day's change.
new CalendarChart(el, {
  data: [{ date: '2025-01-02', value: 1.2 }, { date: '2025-01-03', value: -0.8 }],   // YYYY-MM-DD
  weekdays: 5,                          // 7 (default) every day; weekStart: 0 starts weeks on Sunday
  locale: 'vi-VN',                      // month and day names
  colorScale: { min: -2, max: 2 },      // the theme's red and green, full at ±2
  valueFormat: (v) => v.toFixed(2) + '%',
  onDayClick: (day) => openSession(day.date),
})

Weeks run left to right and weekdays top to bottom, one band a calendar year and ten years at most; when the chart is too short for all of them, the oldest give way. Days without a value are drawn empty, and the colour bar underneath shows the scale (legend: false hides it).

Correlation matrix

import { MatrixChart, correlationMatrix } from '@tradecanvas/chart'

// Daily returns, not prices: one array per stock, the same days in each.
const names = ['VCB', 'BID', 'CTG', 'TCB']
const values = correlationMatrix(returnsByStock)

new MatrixChart(el, {
  rows: names,                          // columns: [...] for a matrix that isn't square
  values,                               // values[row][column]
  triangle: 'lower',                    // half is enough for correlations
  colorScale: { min: -1, max: 1 },
  onCellClick: ({ row, column, value }) => compare(row, column),
})

Cells stay square and print their value where it fits (two decimals unless valueFormat); column names that don't fit across their cells are turned. correlationMatrix pairs the days both series have and gives NaN for fewer than three, which leaves the cell empty. A matrix suits other tables of values too, such as volume by hour and weekday.

A table of a few columns, such as a statement's lines by period, takes cellWidth: 'fill': the columns share the width beside the row names and the rows keep their height, so the matrix uses the chart instead of sitting small in its middle. A number sets each column's width in pixels, no wider than the room.

Sector map

import { HeatmapChart } from '@tradecanvas/chart'

new HeatmapChart(el, {
  data: [
    { id: 'vcb', label: 'VCB', value: 0.8, weight: 480, group: 'Banks', logo: '/logos/vcb.png' },
    { id: 'hpg', label: 'HPG', value: 1.9, weight: 160, group: 'Steel' },
    { id: 'vhm', label: 'VHM', value: -2.4, weight: 170, group: 'Real estate' },
  ],
  grouped: true,                        // tiles by group, then by stock
  valueFormat: (v) => v.toFixed(1) + '%',
})

Each group takes the room of its stocks' weights, and its name and weighted change head its tile where they fit. The heatmap's colours run from -5 to 5 unless colorScale gives a min and max.

A cell with a logo draws it over its name, on a white plate, where the cell has room: as cells get small the logo goes before the name and the value do. It takes the addresses a symbol's logo does (an https: address, a path on your site, a blob: or a data:image/… URL), is loaded once, and a cell whose logo fails is drawn as one with none. A logo from another site has to be served with CORS headers, so that the chart can still be saved as a picture; one that is not is left out. showLogos: false draws none. Drawn with no page (renderFinanceChart), a heatmap has no logos.

Counter-clock chart

import { CounterClockChart } from '@tradecanvas/chart'

const clock = new CounterClockChart(el, {
  data: bars,                           // OHLCV bars, oldest first
  period: 25,                           // bars in each average
  points: 120,                          // the newest points drawn
  xLabel: 'Volume, average', yLabel: 'Price, average',
  onPointClick: (p) => goTo(p.time),
})

clock.getPhase()                        // 1–8: the direction of the last move

Each point is the 25-bar average of volume (across) and of the close (up), joined in time order and fading with age. A healthy cycle turns counter-clockwise. getPhase() (and counterClockPhase(points)) name the last move: 1 volume rising, 2 both rising, 3 price rising, 4 price rising on falling volume, 5 volume falling, 6 both falling, 7 price falling, 8 price falling on rising volume.

Sparkline, gauge, heatmap, waterfall, depth and equity curve

import { SparklineChart, GaugeChart, HeatmapChart, WaterfallChart, DepthChart, EquityCurveChart } from '@tradecanvas/chart'

new SparklineChart(el, { data: closes, mode: 'area', showLastPoint: true })

const gauge = new GaugeChart(el, {
  value: 72, min: 0, max: 100, label: 'Fear & Greed',
  zones: [{ from: 0, to: 45, color: '#e8505b' }, { from: 45, to: 55, color: '#8a93a3' }, { from: 55, to: 100, color: '#1fa874' }],
})
gauge.setValue(64)

// A treemap sized by market value, coloured by the day's change.
new HeatmapChart(el, {
  data: [{ id: 'vcb', label: 'VCB', value: 1.2, weight: 480 }, { id: 'fpt', label: 'FPT', value: -0.8, weight: 170 }],
  weighted: true, showLabels: true, showValues: true,
  onCellClick: (cell) => openSymbol(cell.label),
})

new WaterfallChart(el, { data: [{ label: 'Start', value: 10000, type: 'total' }, { label: 'Fees', value: -85 }, { label: 'End', value: 9915, type: 'total' }] })
new DepthChart(el, { data: { bids, asks }, midPriceLine: true, spreadLabel: true })
new EquityCurveChart(el, { data: equity, benchmark, drawdown: true })

An equity curve also takes levels, lines across the plot at fixed values with each value in a tag at the axis, and bands, tinted stretches of values under the curve. A level has a label written at its right end (labelAt: 'start' for its left, away from the curve's latest point), a color and a dash ([] for a solid line); a band has a label in its corner and a color used as given, so give one with transparency. Both take the theme's colours when none is given. A level's value is written in full, or by valueFormat when given. Tags of levels too close for both move apart (when there is no room for them all, the lowest levels' are left out), and the names in the plot keep clear of each other. The value scale widens to show them all; fitLevels: false keeps it to the curve, leaving out a level outside it and drawing a band only where it overlaps it. setOptions changes them on the chart as it is.

const chart = new EquityCurveChart(el, {
  data: closes,
  levels: [{ value: 41_250, label: 'BOS', color: '#e0a030' }, { value: 38_900, label: 'Equilibrium' }],
  bands: [
    { from: 38_900, to: 44_100, label: 'Premium', color: 'rgba(232, 80, 91, 0.10)' },
    { from: 33_700, to: 38_900, label: 'Discount', color: 'rgba(31, 168, 116, 0.10)' },
  ],
})
chart.setOptions({ levels: [{ value: 42_000, label: 'CHoCH' }] })

Option payoff

PayoffChart draws what an options position makes or loses at expiry, over the underlying's price: the profit tinted above zero and the loss below it, a dashed line at each breakeven and at spot, the price now. A leg is a 'call' or a 'put', bought ('long') or sold ('short'), with its strike and the premium of one unit; an 'underlying' leg is the underlying held beside them, at its entry. multiplier is the units a contract is for. The prices drawn are around the strikes, or the range given. The pointer reads the profit or loss at its price.

import { PayoffChart, payoffStats, optionPayoff } from '@tradecanvas/chart'

const condor = [
  { type: 'put', side: 'long', strike: 90, premium: 1 },
  { type: 'put', side: 'short', strike: 95, premium: 2.5 },
  { type: 'call', side: 'short', strike: 105, premium: 2.5 },
  { type: 'call', side: 'long', strike: 110, premium: 1 },
]
const chart = new PayoffChart(el, { legs: condor, multiplier: 100, spot: 101.4, spotLabel: 'Spot' })
chart.update(otherLegs)

payoffStats(condor, 100)    // { maxProfit: 300, maxLoss: -200, breakevens: [92, 108] }
optionPayoff(condor, 100, 100)   // 300: what the legs make with the underlying at 100

// Before expiry: a second, dashed line, by a model
chart.setOptions({ model: { daysToExpiry: 30, volatility: 0.25, rate: 0.03 } })
positionValue(condor, 100, { daysToExpiry: 30, volatility: 0.25 }, 100)   // what the legs make with 30 days to go
optionPrice('call', 100, 105, { years: 30 / 365, volatility: 0.25 })      // one option's price

payoffStats gives the most the legs make and the most they lose at expiry (null where there is no limit: a call bought, a call sold alone) and the prices where they break even. A leg without its strike, or the underlying without its entry, counts for nothing.

With model the chart draws what the position makes or loses with that many days still to go, dashed, over the payoff, names the two lines over the plot, each beside a stretch of its own line (expiryLabel and model.label say them in your words) and reads both under the pointer. Each option is priced as a European one by Black-Scholes at the model's volatility (a year's, as a share: 0.25 is 25%), with rate and dividendYield where given; a leg's own volatility and daysToExpiry stand in for the model's, for a skew or a calendar spread. It is a model's answer, not a quote: an American option, or one whose volatility moves with the price, is worth something else. positionValue and optionPrice are the sums, good to about a part in a million of a price; with no days left positionValue is optionPayoff, and with the underlying at nothing a put is worth its strike, discounted.

Curves: a volatility smile, a term structure

CurveChart draws values against a strike, a tenor or a maturity, a line for each series. The lines are rounded through their points without passing a value they do not reach (smooth: false joins them straight), a series with dashed is yesterday's beside today's, and markers are labelled lines at an x. With ticks the x axis is named by you, a tenor at each number of days. The pointer snaps to the nearest x that has a quote and reads every curve there, along the line as it is drawn. curveValueAt(points, x) reads a curve in code, straight between its points, or along the rounded line with true as its third argument.

import { CurveChart } from '@tradecanvas/chart'

// A smile: implied volatility against the strike, a line an expiry.
new CurveChart(el, {
  series: [
    { name: '1M', points: [{ x: 90, y: 31 }, { x: 100, y: 24 }, { x: 110, y: 27 }] },
    { name: '3M', points: [{ x: 90, y: 28 }, { x: 100, y: 25 }, { x: 110, y: 26 }] },
  ],
  markers: [{ x: 101.4, label: 'ATM' }],
  valueFormat: (v) => v.toFixed(1) + '%',
})

// A term structure: tenors along x, in days.
new CurveChart(el, {
  series: [
    { name: 'Today', points: [{ x: 30, y: 26 }, { x: 90, y: 25 }, { x: 365, y: 27 }] },
    { name: 'A week ago', points: [{ x: 30, y: 24 }, { x: 90, y: 25 }, { x: 365, y: 26 }], dashed: true },
  ],
  ticks: [{ x: 30, label: '1M' }, { x: 90, label: '3M' }, { x: 365, label: '1Y' }],
})

Box plot

BoxPlotChart shows how each group's values spread: a box from the first quartile to the third with a line at the median, whiskers to the furthest values within whiskers box heights of the box (1.5 when left out; Infinity for the lowest and the highest), and a ring for each value further out. A group gives its raw values, or its numbers in stats when they were worked out elsewhere. boxPlotStats(values) is the same working out in code, and labels puts the readout's words in another language. onBoxClick gives the group a click falls on and its five numbers: anywhere up and down the group's place across the plot, as the readout picks it.

import { BoxPlotChart, boxPlotStats } from '@tradecanvas/chart'

new BoxPlotChart(el, {
  data: [{ label: 'Mon', values: mondayReturns }, { label: 'Tue', values: tuesdayReturns }],
  colorBySign: true,                     // by each box's median
  valueFormat: (v) => v.toFixed(1) + '%',
  onBoxClick: (group, stats) => openDay(group.label, stats.median),
})

boxPlotStats([1, 2, 3, 4, 5, 6, 7, 8, 9, 100])
// { min: 1, q1: 3.25, median: 5.5, q3: 7.75, max: 9, outliers: [100] }

Radar

RadarChart puts several measures on spokes around a centre, clockwise from twelve o'clock, and joins each series' values into a shape. A spoke runs from its min at the centre (0 when left out, or the lowest value on it when that is under zero) to its max at the rim, the highest value on it when none is given: give each spoke its own when the measures differ in size. It needs three spokes. The pointer reads every series on the nearest spoke, and onAxisClick gives that spoke for a click: its label, its place among axes, and each series' value on it.

import { RadarChart } from '@tradecanvas/chart'

new RadarChart(el, {
  axes: [{ label: 'Sharpe', max: 3 }, { label: 'Sortino', max: 3 }, { label: 'Calmar', max: 3 }, { label: 'Win rate', max: 100 }],
  series: [{ name: 'Strategy', values: [1.8, 2.4, 1.5, 58] }, { name: 'Benchmark', values: [1.0, 1.3, 0.7, 51] }],
  onAxisClick: ({ axis, index, values }) => explain(axis, values),   // 'Sortino', 1, [{ series: 'Strategy', value: 2.4 }, …]
})

Sunburst

SunburstChart draws parts of a whole and the parts inside them, a ring a level. A part with children is as large as they are together; one without takes its value. The first ring takes the palette's colours and each ring outside it its parent's, paler. Four rings are drawn at most (maxDepth for fewer or more), innerRadius: 0 closes the hole, and centerLabel and centerValue are written in it. A click gives the part and the labels down to it. Names are written along their rings where they fit.

import { SunburstChart } from '@tradecanvas/chart'

new SunburstChart(el, {
  data: [
    { label: 'Stocks', children: [{ label: 'Banks', value: 22 }, { label: 'Technology', value: 14 }] },
    { label: 'Bonds', value: 23 },
    { label: 'Cash', value: 18 },
  ],
  centerLabel: 'Total', centerValue: '1.2B',
  onNodeClick: (node, path) => openHoldings(path),   // ['Stocks', 'Banks']
})

Stacked area

StackedAreaChart stacks several series over the same points, the first at the bottom: what a total is made of over time. With normalized each point's values are shares of their total and the areas fill the height: how a mix changes. A value under zero counts as none. The pointer reads every series and their total at the nearest point.

import { StackedAreaChart } from '@tradecanvas/chart'

const chart = new StackedAreaChart(el, {
  categories: ['Jan', 'Feb', 'Mar', 'Apr'],
  series: [{ name: 'Stocks', values: [40, 44, 47, 52] }, { name: 'Bonds', values: [30, 29, 27, 25] }, { name: 'Cash', values: [30, 27, 26, 23] }],
  normalized: true,
})
chart.update(nextSeries, nextCategories)

3D surface

SurfaceChart draws values over two axes as a sheet in a box: x across, y running back, and values[yIndex][xIndex] up. Numbers along an axis are placed by their value, and drawn by rising value whatever their order; names are spaced evenly in the order given, so a list of tenors ('1W', '1M', '1Y') is not crowded at its short end. A value that is missing or no number leaves a hole, and a place along an axis that is no number is left out with its values.

import { SurfaceChart } from '@tradecanvas/chart'

const chart = new SurfaceChart(el, {
  x: [80, 90, 100, 110, 120],              // strikes
  y: ['1W', '1M', '3M', '6M', '1Y'],       // expiries
  values: impliedVolatility,               // values[expiry][strike]
  xLabel: 'Strike', yLabel: 'Expiry', valueLabel: 'IV',
  valueFormat: (v) => (v * 100).toFixed(1) + '%',
  onPointClick: (point) => openChain(point.x, point.y),
})
chart.update(nextValues)                   // or update(values, { x, y }) when the axes changed too

Dragging turns the chart: a mouse turns and tilts it, a finger turns it only, so that a page still scrolls under it. From the keyboard, once Tab has reached the chart, the arrows turn and tilt it by 5 degrees (15 with Shift) and Home goes back; a screen reader is told the keys, and after each where the chart is seen from (describeView says it in your words). A double click goes back to the view the options gave ({ yaw: -35, pitch: 28 } when they give none: yaw turns the chart about its upright axis, pitch is how far above the floor the eye is, 0 to 90 degrees). getView() reads where it is seen from now, setView() sets it, onViewChange follows it, and rotate: false holds it still. The chart is drawn without perspective, so lines that are parallel in the data stay parallel on the screen, and it keeps one size as it is turned.

style is 'surface' (a shaded sheet, the default), 'wireframe' (its lines only) or 'slices' (each y a filled line of its own, one behind another). Values are coloured by colorRamp: one hue from near the chart's ground up to its strongest by default, over the values' range; give colors (two or more, the lowest value's first) and min and max for your own, such as a loss colour, a neutral and a profit colour either side of zero. The pointer reads the nearest point of the cell it is on, the one in front where the sheet folds over itself. A grid past 120 points along an axis is thinned to that many, both ends kept, and to 60 for as long as it is being turned, so that a large grid turns smoothly.

depthSurface(snapshots, { levels }) turns a run of order books into a surface's x, y and values: prices across, the books' times back, and at each the volume waiting from the best price out to that price, as a depth chart has it. levels is how many prices (48 when left out, 1,000 at most), and from and to keep to a window of prices.

import { SurfaceChart, depthSurface } from '@tradecanvas/chart'

// books: { time, bids: [{ price, volume }], asks: [...] }[], oldest first
const chart = new SurfaceChart(el, {
  ...depthSurface(books, { levels: 48 }),
  style: 'slices',
  xLabel: 'Price', yLabel: 'Time', valueLabel: 'Depth',
  yFormat: (ms) => new Date(ms).toISOString().slice(11, 16),
})

3D bars

Bar3DChart stands a column on each value, in rows a series deep: categories across and a row for each of series, the first at the front of the y axis. Columns start at zero; one under zero hangs from the level of zero, which is drawn as a sheet across the box. It takes view, rotate and the rest of what a surface takes for turning, and onBarClick gives the category, the series and the value. No more than 120 categories and 120 series are drawn.

import { Bar3DChart } from '@tradecanvas/chart'

const chart = new Bar3DChart(el, {
  categories: ['Q1', 'Q2', 'Q3', 'Q4'],
  series: [{ name: 'Stocks', values: [4.2, 6.1, -2.4, 5.3] }, { name: 'Bonds', values: [1.1, 0.8, 1.6, -0.5] }],
  valueFormat: (v) => v.toFixed(1) + '%',
})
chart.update(nextSeries, nextCategories)

Performance dashboard

PerformanceDashboard puts a strategy report together from a backtest: a strip of headline stats, the equity curve, the drawdown under it and a calendar of monthly returns. Pair it with the analytics backtester.

import { Backtester } from '@tradecanvas/analytics'
import { PerformanceDashboard } from '@tradecanvas/chart'

const result = new Backtester({ initialCash: 10_000 }).run(bars, myStrategy)

const dash = new PerformanceDashboard(document.getElementById('report')!, {
  result,            // any { equityCurve, metrics }: Backtester output fits
  theme: 'dark',
  title: 'SMA Crossover',
  subtitle: 'BTC/USDT · 1h · 2023',
})

// later: dash.update(newResult) · dash.setTheme('light') · dash.destroy()

Metrics you build by hand take fractions, as @tradecanvas/analytics returns them: a totalReturnPct of 0.12 shows as +12.00%, and one given in percent (12) would show 100 times too large. maxDrawdownPct reads as a fall, whichever sign it is given with.

The calculations are exported for a layout of your own: computeMonthlyReturns, computeDrawdownCurve, toEquityPoints, selectKeyStats, and for axes of your own niceScale(min, max) (ticks in steps of 1, 2, 2.5 or 5).