Bu sayfa henüz Türkçe diline çevrilmedi, bu yüzden İngilizce gösteriliyor.
Plugins
Extend the chart with custom indicators, drawing tools, chart types, and overlays — registered globally or per chart.
Registration
Three ways to register, in precedence order: global defaults, the constructor, then imperative instance calls.
import { Chart, registerPlugin } from '@tradecanvas/chart'
// 1) Global — every Chart created afterward inherits it
registerPlugin({ kind: 'indicator', plugin: new MyIndicator() })
// 2) Per-chart at construction
const chart = new Chart(el, { plugins: [{ kind: 'overlay', plugin: myHeatmap }] })
// 3) Imperative on an instance
chart.plugins.register({ kind: 'chartType', plugin: myCandles })
chart.plugins.unregister('chartType:my-candles')
chart.plugins.list() A ChartWidget takes them as plugins (typed, and with any chartOptions.plugins):
they are registered with its chart before it restores anything, so a saved layout
(persistLayouts), a template or a shared view that names one of your indicators gets it back.
For the same id, the widget's plugins win over chartOptions.plugins, and a grid cell's own plugins replace the grid's shared ones. Registered on widget.getChart() after a layout was
restored, an indicator comes too late: the layout has already left it out.
new ChartWidget(host, {
symbol: 'BTCUSDT', adapter, persistLayouts: true,
plugins: [{ kind: 'indicator', plugin: new DoubleSMA() }],
}) Plugin kinds
| Kind | Contract | Renders |
|---|---|---|
indicator | IndicatorPlugin — calculate() + render(ctx, output, viewport, style, { theme }) | overlay or panel |
drawing | DrawingPlugin — render() + hitTest() | overlay layer |
chartType | ChartTypePlugin — createRenderer() + optional transform() | main series |
overlay | OverlayPlugin — render(ctx, { viewport, data, theme }) | main / overlay / ui |
Custom indicator, the short way
defineIndicator makes an indicator from its inputs and one function of the bars: no class and no
drawing code. calculate is handed the bars as columns (bars.close[i]), the inputs'
values and ta, the sums indicators are made of, and returns its lines by key. The chart draws them,
scales their pane, lists them in the legend, and gives each input a field in the settings dialog.
import { defineIndicator } from '@tradecanvas/chart'
const emaCross = defineIndicator({
id: 'emaCross',
name: 'EMA Crossover',
placement: 'overlay', // on the prices; 'panel' (the default) is a pane of its own
inputs: {
fast: { default: 9, kind: 'int', min: 1 },
slow: { default: 21, kind: 'int', min: 2 },
},
plots: [
{ key: 'fast', title: 'Fast', color: 0 },
{ key: 'slow', title: 'Slow', color: 1 },
{ key: 'buy', title: 'Buy', color: 2, kind: 'markers', shape: 'arrowUp', position: 'belowBar' },
{ key: 'sell', title: 'Sell', color: 3, kind: 'markers', shape: 'arrowDown', position: 'aboveBar' },
],
calculate({ bars, inputs, ta }) {
const fast = ta.ema(bars.close, inputs.fast)
const slow = ta.ema(bars.close, inputs.slow)
return { fast, slow, buy: ta.crossover(fast, slow), sell: ta.crossunder(fast, slow) }
},
})
chart.registerIndicator(emaCross)
chart.addIndicator('emaCross', { fast: 12 }) chart.replaceIndicator(plugin) registers a new version and puts it in the place of the one the
chart's indicators of its id are of, as an indicator edited and run again. Each keeps its instance id, pane, size,
order, style, levels and visibility, and the inputs the new one still takes; alerts on its lines and indicators
that read them follow each line by its title. One the new version draws elsewhere (placement) moves
there, and one whose output comes later (pending) takes the place once it is in, the old one drawn
till then. indicatorChange then says 'plugin', with the lines that are gone in lostLines. It is not an undo step.
- Inputs. Each has a
default, whose type is the input's type, and what the settings dialog needs to show it:kind,min,max,step,optionsfor a choice,source: truefor a price source (the indicator then reads it asbars.close).calculategets each number within itsminandmax, whole for akind: 'int', and a choice that is one of its options. - Lines. A value a bar;
undefined,nullorNaNwhere there is none.truemarks a bar, for a plot ofkind: 'markers'on the prices: above or below the bar by itsposition, else at the bar's close. A mark in a pane of its own is a number, the value it is drawn at. With noplots, every line returned is drawn as a line in the theme's series colours; an indicator that returns no lines for too few bars declares them. - How it looks.
plots(a line,'histogram','step','dots','markers', each with its colour, width and dash),fillsfor a band between two lines,scaleandlevelsfor a pane, as in the descriptor below. tahassma,ema,wma,rma,stdev,highest,lowest,change,rsi,macd,atr,bollinger,crossoverandcrossunder. Each takes a value a bar and returns one, so one feeds the next (ta.ema(ta.rsi(bars.close, 14), 9)).rsi,macd,atrandbollingerrun the built-in indicators themselves, so their values are the chart's.ta.indicator(id, input, params)runs any built-in indicator and returns its lines by key:ta.indicator('stochastic', bars, { kPeriod: 14 }).k,ta.indicator('supertrend', bars).value. The ids, inputs and lines are the ones on the Indicators page, and they are typed.inputis the bars, or a value a bar that the indicator then reads as its prices (ta.indicator('ema', rsi, { period: 5 })). A value a bar has no volume and no clock, so an indicator of volume or of the day's sessions (OBV, MFI, VWAP…) wants the bars. The five that read another symbol's bars are not among them. It is exported on its own too:import { ta } from '@tradecanvas/chart'.
It computes over all the bars on each tick, which is quick for sums like these. An indicator slow enough for
that to show, or one that draws something other than a value a bar, is a class with an update:
the long way, below.
Custom indicator
An indicator is an IndicatorPlugin: a descriptor that says what it is and how it
looks, and a calculate() that gives a value per bar. Extend IndicatorBase and the chart
does the rest from the descriptor: it draws the plots, scales the pane, tags the values on the axis, and lists the
indicator in the legend, the settings and the Indicators dialog. Here is a whole one, a MACD that marks where its
line turns:
import { IndicatorBase, IndicatorValueMap } from '@tradecanvas/chart'
const ema = (prev, value, period) => (prev === undefined ? value : prev + (2 / (period + 1)) * (value - prev))
class TurningMacd extends IndicatorBase {
descriptor = {
id: 'turning-macd', name: 'Turning MACD', shortName: 'TMACD',
placement: 'panel', // a pane of its own; 'overlay' draws on the price pane
category: 'oscillators', // its group in the Indicators dialog
defaultConfig: { fast: 12, slow: 26, source: 'close' },
inputs: {
fast: { kind: 'int', min: 2, label: 'Fast' },
slow: { kind: 'int', min: 3, label: 'Slow' },
source: { kind: 'choice', label: 'Price', options: [{ value: 'close', label: 'Close' }, { value: 'hl2', label: 'Median' }] },
},
plots: [
{ key: 'value', title: 'MACD', color: 0 },
{ key: 'turn', title: 'Turn', color: 1, kind: 'markers', tone: { field: 'up' }, downColor: 2 },
],
scale: { zero: true },
levels: [0],
defaultStyle: (theme) => ({ colors: theme.name === 'light' ? ['#1f4e8c', '#0a7d3b', '#b3261e'] : ['#8ab4f8', '#4cc38a', '#f28b82'] }),
}
calculate(data, config) {
const { fast, slow, source } = config.params
const values = new IndicatorValueMap()
const series = new Array(data.length).fill(null)
let f, s
for (let i = 0; i < data.length; i++) {
const bar = data[i]
const price = source === 'hl2' ? (bar.high + bar.low) / 2 : bar.close
f = ema(f, price, fast)
s = ema(s, price, slow)
if (i < slow) continue
const point = { value: f - s }
const a = series[i - 2]?.value, b = series[i - 1]?.value
// The bar before this one is a turn when the line changed direction there.
if (a !== undefined && b !== undefined && (b - a) * (point.value - b) < 0) {
series[i - 1] = { ...series[i - 1], turn: b, up: point.value > b ? 1 : 0 }
values.set(data[i - 1].time, series[i - 1])
}
series[i] = point
values.set(bar.time, point)
}
return { values, series }
}
} calculate(data, config) gets the bars and the instance's inputs (config.params) and
returns its values twice: by bar index (series, null before the first value) and by bar
time (values). Use new IndicatorValueMap() for values: a Map that
is several times cheaper to fill in time order, which every symbol or interval switch does. A field no plot names
(up above) is not drawn, scaled or shown; it is there for a plot's tone.
The descriptor
- Plots draw a field each:
'line'(the default),'step','histogram','dots'(a line drawn as dots),'markers', a shape (shape:'dot','triangleUp','arrowUp','cross','labelUp'…) on the bars where the field has a value, at it, at the top or the bottom of the pane, or, on the price pane, above or below the bar (position), with itstextby it or, in a label, in it (textColor), or'background', the pane's whole height behind each bar with a value, drawn behind the bars and the levels, at the plot'sopacity(0.1 unless set),'area', a line with the space down to zero shaded under it, or'barColor', the price bars painted in its colour on the bars it has a value at, over candles and OHLC bars and under every line (another chart type, the left scale, a pane of its own, and a zoom below a pixel a bar show the bars as they are).coloris an index into the style's colours;toneanddownColordraw a plot in two colours;colorBynames a field that holds, bar by bar, the index of the colour to draw in there, andpaletteByone that indexes the output's ownpalette(colours known only as it runs). A line's stretch takes the colour of the bar it ends on.width,lineStyle,opacityandbreakOnset a line's look.fillsshade between two plots, coloured bar by bar the same way; a colour see-through of its own (#rrggbbaa) keeps its alpha, times the fill'sopacity. - Inputs say how each input in
defaultConfigis edited:kind,label,min,max,step, and a choice'soptions, plain or with a label for each ({ value, label }).{ source: true }lets it run on another price or another indicator's line. - The pane:
scalefixes its bounds or keeps zero in view,levelsdraws reference lines the viewer can edit. - Past the last bar: an output's
aheadholds its values at the bars after the last one, drawn in the empty slots there (a line drawn some bars on). - What it is told of the chart:
readsIntervalandreadsSymbolhave it computed again when the chart's interval (config.interval) or its symbol (config.symbol: its ticker, smallest step, currency…) changes. - Its look:
defaultStyle, a style or one for each theme (below). - Shapes of its own: an output's
drawingsare labels, lines, boxes and tables it draws over its plots, at a bar (by its place among the chart's bars, past the last one too) and a value on its scale:{ kind: 'label', at, text, position, color },{ kind: 'line', from, to, extend },{ kind: 'box', from, to, fill, text },{ kind: 'polyline', points, curved, closed, fill }through many points, and{ kind: 'lineFill', lines, color }for the space between two lines. A table,{ kind: 'table', position: 'top-right', columns, rows, cells }, stands in a place of the pane over the bars, clear of the legend and of other indicators' tables. On the price pane a label keeps clear of the legend too: behind it, the label goes to the point's other side, else beside it. With the point itself behind the legend, the label goes under the legend at the point's bar, with no pointer: there its height is not its value. They are not the viewer's drawings: nothing picks, moves or saves them, and they show and hide with the indicator. - Moments to be told of:
alertConditionsnames output fields that are 1 on the bars a condition holds (a cross, a signal) and 0 on the others, each with atitleand amessage. The widget's alert form lists each as name: title, asks nothing more of it, and the alert fires as the condition turns true, once. A condition that holds on the forming bar and not when it closes still fires: "Only on bar close" looks at closed bars alone. WithdefineIndicator, returntrueon those bars; an indicator of your own declaresplotsbeside them.
Live ticks: update and revisesBefore
On each tick only the newest bar changes. Without update() the chart runs calculate() over
the whole history again; with it, the chart hands back your last output (prev) and the first bar that
changed (from), and you recompute from there. Return null to have calculate() run
instead; the values must be the ones it would give. canResume and writePoint come with IndicatorBase.
Each bar of an indicator like this one is worked out from the bars around it, not from a running state like
TurningMacd's averages (which would keep its own state, or leave update out):
// A swing high: the bar is higher than the n bars either side of it.
pointAt(data, i, n) {
if (i < n || i + n >= data.length) return null
for (let k = 1; k <= n; k++) if (data[i - k].high >= data[i].high || data[i + k].high > data[i].high) return null
return { high: data[i].high }
}
update(data, config, prev, from) {
if (!this.canResume(data, prev, from)) return null
const n = config.params.strength
// A new bar decides the bar n back: rewrite from there.
for (let i = Math.max(0, from - n); i < data.length; i++) this.writePoint(prev, data, i, this.pointAt(data, i, n))
return prev
}
revisesBefore(config) { return config.params.strength } from is always the first bar that changed. When a new bar can change bars before it (a swing point,
a turn, a fractal is decided by the bars after it), update rewrites them itself, and revisesBefore(config) says how many, so the indicators that read this one's line are recomputed from
there too. Leave it out when only bars from from on change.
Outputs that come later: connect
An indicator computed somewhere else (in a worker, on a server) cannot answer calculate() at once. connect(host) is called once for each chart the plugin is registered with: return what it has from calculate() (an empty output at first), send the bars off, and when the answer is in, call host.recompute(config) with the instance's config. The chart then runs calculate() again,
which now returns the answer, recomputes the indicators that read it, and draws. A config that chart does not hold is
passed over, so calling every host is safe. A function connect returns is called when the chart lets the
plugin go, and release(config), when there is one, when an instance is removed or its chart destroyed.
connect(host) {
this.hosts.add(host)
return () => this.hosts.delete(host)
}
calculate(data, config) {
// The bars are the same array as ticks come: tell them apart by their length and last close.
const asked = data.length + ':' + data.at(-1)?.close
const entry = this.entries.get(config)
if (entry?.asked === asked) return entry.output
// Asked once for these bars; what was drawn stays till the answer comes.
const next = { asked, output: entry?.output ?? { values: new Map(), series: data.map(() => null) } }
this.entries.set(config, next)
this.ask(data, config).then((output) => {
if (this.entries.get(config) !== next) return
next.output = output
for (const host of this.hosts) host.recompute(config)
})
return next.output
}
release(config) {
this.entries.delete(config)
} A picture drawn with no page (renderPriceChart) draws what calculate() returns at once; it
does not wait for an output that comes later.
@tradecanvas/script runs a script this way in a worker (scriptWorkerIndicator).
Drawing it
IndicatorBase's render() draws the plots and fills on the pane's
scale, so most indicators have no drawing code. To draw more, override it and call it first. The fifth argument
holds the theme the chart draws with, for colours and a font the style doesn't give: theme.candleUp, theme.candleDown, theme.text, theme.font.
render(ctx, output, viewport, style, context) {
super.render(ctx, output, viewport, style, context)
ctx.fillStyle = context.theme.text
// barIndexToX(i, viewport) and priceToY(value, viewport) place it where the chart draws
} Colours that follow the theme
defaultStyle on the descriptor is the look an indicator starts with: a style, or a function of the
theme that gives one for each. An instance on it follows chart.setTheme(); a colour someone picks for
it stays. It sits under the viewer's saved default (chart.setIndicatorDefaults(), the widget's Save as default), so your app's colours never take the viewer's place. A saved layout leaves out what
the theme gives, and opened in another theme it takes that theme's colours.
Registering it before a layout is read
A saved layout names indicators by id, and one that isn't registered when the layout is read is left out. Give a ChartWidget your indicators in plugins: they are registered before it restores a layout
(persistLayouts), a template or a shared view. On a Chart, pass plugins to the
constructor, or register before loadState().
new ChartWidget(host, { symbol, adapter, persistLayouts: true, plugins: [{ kind: 'indicator', plugin: new TurningMacd() }] })
const chart = new Chart(host, { plugins: [{ kind: 'indicator', plugin: new TurningMacd() }] })
chart.addIndicator('turning-macd', { fast: 8 }) What the chart reads off it
- The legend names it by
shortNameand the inputs that differ fromdefaultConfig(a choice by its label), and shows the value of each plot but markers, in its colour. - The price axis tags the latest value of those plots.
- The CSV export has a column for each of them, named by the legend's name and, when there is
more than one, the plot's
title. - The settings dialog edits the inputs, lists each plot with its colour, whether it shows, and a dash for a line or a step, and edits the levels.
- The Indicators dialog lists it by
nameunder itscategory: a kind ('oscillators','volume'…) or a group of your own,{ id: 'my-app', label: 'My App' }, which puts your app's indicators together under its name, before the built-in kinds (several groups in the order their first indicators are registered). Search finds them by that name too. - Another indicator can read its lines (the same plots) as its source.
Coding agents get the same guide, with code type-checked against the published packages, from the MCP server's custom_indicator tool and the skill's custom indicator recipe.
Custom drawing tool
Extend DrawingBase for its helpers (anchors to pixels, line
styles, handles), describe the tool, and register it. Settings listed in descriptor.options show up in the widget's settings dialog and
are saved with the drawing.
import { DrawingBase, registerPlugin } from '@tradecanvas/chart'
class TargetLine extends DrawingBase {
descriptor = {
type: 'targetLine', name: 'Target Line', requiredAnchors: 1,
options: { label: { kind: 'text', label: 'Label', default: 'Target' } },
}
render(ctx, state, viewport, selected) { /* at this.anchorToPixel(state.anchors[0], viewport) */ }
hitTest(point, state, viewport, tolerance) { /* is the pointer on it? */ return false }
// optional: the prices of its lines, so an alert can follow them
priceAt(state) { return [state.anchors[0].price] }
}
registerPlugin({ kind: 'drawing', plugin: new TargetLine() })
chart.setDrawingTool('targetLine') The tool's name works wherever the chart takes one (setDrawingTool, addDrawing…) in TypeScript too: DrawingToolType takes any name and still completes the built-in ones, which BuiltInDrawingToolType lists.
The descriptor can also say how the tool is drawn (creation: 'clicks', 'freehand' or 'path', with maxAnchors) and whether the dialog offers a fill
(fill) or text (text). A tool can move handles that
are not anchors with moveHandle(), and receives the chart's bars
through setDataGetter(getter, revision) when it draws from them. revision() moves when a bar was corrected in the same array
(updateBar): a tool that keeps what it computed from the bars
computes it again then.
Custom chart type
A ChartTypePlugin supplies a renderer and an optional data transform; switch to it like a built-in:
registerPlugin({
kind: 'chartType',
plugin: {
descriptor: { type: 'my-bricks', name: 'My Bricks' },
createRenderer: () => new MyBrickRenderer(),
transform: (raw) => toBricks(raw), // optional
},
})
chart.setChartType('my-bricks') Custom overlay
An OverlayPlugin draws each frame on the layer you choose, receiving the live viewport, data, and theme:
import { overlayScale, registerPlugin } from '@tradecanvas/chart'
registerPlugin({
kind: 'overlay',
plugin: {
descriptor: { id: 'high-marks', name: 'High marks', layer: 'main' },
render(ctx, context) {
const s = overlayScale(context)
ctx.fillStyle = '#f2a93b'
for (let i = s.visible.from; i <= s.visible.to; i++) {
const bar = context.data[i]
ctx.fillRect(s.indexToX(i) - s.barWidth / 2, s.priceToY(bar.high) - 1, s.barWidth, 2)
}
},
},
}) overlayScale(context) places things where the chart draws them: timeToX / xToTime by bar time (between bars and past the newest, in proportion), indexToX / xToIndex, priceToY / yToPrice (on a log or inverted scale too), barWidth, and visible, the bars on screen. For rows on the price grid, chart.getPriceStep() is the
symbol's smallest step (minTick), a fraction's unit, or one unit of the decimals prices show.
Chart-type renderers get the viewport alone, and indicators the viewport and the theme: priceToY, barIndexToX, timeToX and their inverses are exported for them. The bars are those on screen: on a Renko or
Kagi chart, its bricks (chart.isTimeAligned() says when they are the feed's bars).
To write a price as the axis does, the viewport carries the chart's own price format when it has one
(formatPrice), its numberLocale, and the market's or the symbol's decimals when one sets
them (pricePrecision); indicator panes leave the format and the decimals unset.
An overlay with settings of its own (a display mode, a switch) can show a change at once, even when no
tick is coming to redraw the chart: set enabled: false on the plugin to hide it while it stays
registered, and call chart.requestRender() after changing either. Requests before the next
frame make one frame.
See the API reference for the full plugin type signatures.