English
Candlestick
D3PCandlestickRenderer on a series with open, high, low and close. A line renderer draws a moving average over it.
ts
import * as d3 from 'd3'
import {
D3PAutoDomain, d3pAutoInteractionArea, D3PAxis, D3PAxisDomain, D3PCandlestickRenderer, D3PChart,
D3PCursorIndicator, d3pDomLegend, d3pDomTooltip, D3PLegendBundle, D3PLineRenderer, D3PSeries, D3PTooltip,
getGlobalBus,
} from 'd3pict'
// your series data: replace these generators with your own values
import { walk } from './data'
const bus = getGlobalBus()
const container = document.getElementById('app')! // any element with a size: the chart fills it
const closes = walk(14, 60, 100, 8, 60, 140)
const rows = closes.map((close, i) => {
const open = i ? closes[i - 1] : close - 1
return [new Date(Date.UTC(2026, 0, 1 + i)), open, Math.max(open, close) + 2 + (i % 4), Math.min(open, close) - 2 - (i % 3), close]
})
// five columns; the close is "the value" (tooltip marker, default domain)
const prices = new D3PSeries({ bus, name: 'AAPL', columns: ['x', 'open', 'high', 'low', 'close'], primary: 'close', data: rows })
const average = new D3PSeries({ bus, name: 'SMA 10', data: rows.map((r, i) => [r[0], d3.mean(rows.slice(Math.max(0, i - 9), i + 1), (c) => c[4] as number)]) })
const dx = new D3PAxisDomain({ bus, domain: [0, 1] })
const dy = new D3PAxisDomain({ bus, domain: [0, 1] })
const auto = new D3PAutoDomain({ bus })
auto.linkSeries(prices, [dx, dy]) // Y covers the lows and the highs
auto.linkSeries(average, [dx, dy])
const x = new D3PAxis({ bus, name: 'x', domain: dx, scaleType: 'time', props: { tickFormat: d3.timeFormat('%b %d') } })
const y = new D3PAxis({ bus, name: 'y', domain: dy, position: 'left', props: { grid: { enabled: true } } })
const candles = new D3PCandlestickRenderer({ bus, series: prices })
const sma = new D3PLineRenderer({ bus, series: average, props: { style: { color: '#f28e2b', curve: 'monotone' } } })
const cursor = new D3PCursorIndicator({ bus })
const tooltip = new D3PTooltip({ bus })
const legend = new D3PLegendBundle({ bus })
const objects = [x, y, candles, sma, cursor, tooltip, legend]
const chart = new D3PChart({ container, bus })
const stopArea = d3pAutoInteractionArea(chart) // before the objects: the cursor, the tooltip and the tools ask for an interaction area
objects.forEach((o) => o.addToChart(chart))
const stopTooltip = d3pDomTooltip(tooltip)
const stopLegend = d3pDomLegend(legend)