@jean/kerzwerk (0.5.3)
Installation
@jean:registry=https://code.jeanavril.com/api/packages/jean/npm/npm install @jean/kerzwerk@0.5.3"@jean/kerzwerk": "0.5.3"About this package
kerzwerk
Price charts on canvas for Svelte 5 apps — and for any page, since the core knows no framework. Candles, OHLC bars, lines, areas, histograms, bands and dots on one time axis; marks, levels, spans and custom primitives; a legend, linear, log, percent and indexed scales, linked charts, and ten drawing tools. Labels in German or English, bars fed live or replayed one by one, older history paged in front, order lines the user drags, and series that reach past the last bar (a cloud). No runtime dependencies: the core is about 29 kB gzip, the drawing tools 5.3 kB more.
| Entry | What |
|---|---|
kerzwerk |
the core: createChart, aggregation, sync groups, all types |
kerzwerk/svelte |
ChartView, the Svelte 5 binding |
kerzwerk/tools |
drawing tools: createDrawingEditor and helpers |
kerzwerk/theme.css |
default colours, light and dark |
An app carries only what it imports.
Install
npm install kerzwerk
Svelte 5 is an optional peer dependency: only kerzwerk/svelte needs it.
A first chart (Svelte)
<script lang="ts">
import 'kerzwerk/theme.css';
import { ChartView } from 'kerzwerk/svelte';
import type { ChartSpec } from 'kerzwerk';
// Columns as typed arrays: painters run over them without Svelte's proxies.
let { times, open, high, low, close, volume }: Record<
'times' | 'open' | 'high' | 'low' | 'close' | 'volume',
Float64Array
> = $props();
const spec: ChartSpec = $derived({
timeline: { kind: 'time', times, zone: 'America/New_York' },
panes: [{ id: 'main', scales: [
{ id: 'right', margins: { top: 0.08, bottom: 0.2 } },
{ id: 'vol', side: 'none', margins: { top: 0.82, bottom: 0 } }
] }],
series: [
{ id: 'price', kind: 'candles', open, high, low, close, title: 'ACME' },
{ id: 'volume', kind: 'histogram', scale: 'vol', values: volume, color: '@neutral/40' }
]
});
</script>
<div style="height: 400px">
<ChartView {spec} interactive legend crosshair="magnet" />
</div>
Without a class, ChartView fills its parent; give the parent a height.
With a class, the class sets the size (class="h-96 w-full" in
Tailwind). Later changes to
spec go through update and leave the user's zoom alone; only a new
timeline or a new view.key resets the visible range. bind:api gives the
imperative handle (fit, showLast, setScaleMode, toImage, …).
Without Svelte
import { createChart } from 'kerzwerk';
const chart = createChart(document.getElementById('chart')!, { interactive: true, legend: true });
chart.update(spec);
// …
chart.destroy();
The spec
A chart is a description, ChartSpec:
- timeline —
{ kind: 'time', times, zone }with Unix seconds; daily bars carry 00:00 UTC of their day and keep the default zoneUTC, so they show their own date; intraday bars use the exchange's zone. Or{ kind: 'ordinal', length, label }for bars without dates.aheadadds slots after the last bar that series may fill, such as the cloud of Ichimoku: a count, or their times when the app knows the exchange's calendar. Series are then as long as the bars or as the bars plus the slots. Slots without a given time follow the rhythm of the data: daily bars continue on weekdays (every day if the data has weekend bars), intraday bars repeat the times of the last sessions on the next weekdays. Weekly and monthly bars keep their interval. The crosshair shows a slot's time;hoverandclickname no bar there. - panes — stacked areas, each with price scales (
right,left, orside: 'none'for an overlay such as volume) and margins. A linear scale can have fixed bounds,range: { min: 0, max: 100 }for an oscillator: a bound replaces the data's extreme on its side, the other side follows the data, and the margins still apply. - series —
candles,ohlc,line(alsostep),area,histogram(colour per bar withcolors),band(upper and lower edge; withfillCrosseda second fill where the lower edge lies above the upper, as in a cloud),points(one dot per bar,sizein CSS px, colour per bar withcolors; a parabolic SAR). Values are columns of the timeline's length,NaNfor a gap.rebase: truedraws a series relative to the first series of its scale (comparison). - marks (arrows, dots, text at a bar), levels (horizontal lines with axis labels), spans (shaded time ranges) and primitives (your own painter, above or below the series).
Every bar has the same width whatever its time; nights, weekends and
holidays take no room. After the last bar this holds as well, with or
without ahead: a drawing anchored on a future date sits on the trading
day it names, which the projection guesses unless the app passes the
times. Where bars are denser than pixels, the bars of one
pixel column are folded into one — never skipped, so every spike stays.
Colours
Colours are roles: @up, @down, @series-1, @up/45 (45 % opacity), or
any CSS colour. A role @x reads the custom property --chart-x on the
chart's element, so an app adds its own (--chart-ema21: #6246ea; and then
color: '@ema21'). theme.css defines the roles the library uses, light
under :root and dark under .dark or [data-theme='dark']; charts follow
a switch by themselves. Without the stylesheet the same light colours come
from a built-in fallback. Font: --chart-font, --chart-font-size.
Language
Numbers, dates and the few words the library writes follow the chart's
locale: locale: 'en-GB' in the options (or the locale prop of
ChartView). German (de-DE) is the default and writes 1.234,56,
12,3 Tsd., +1,7 %, Mär and Mi 11.11.2026. English writes
1,234.56, 12.3K, +1.7%, Mar, and Wed 11 Nov 2026 (en-GB) or
Wed Nov 11, 2026 (en-US); both use a 24-hour clock. Other tags take
numbers and names from Intl; they work but are not tuned.
import { createLocale } from 'kerzwerk';
chart.setOptions({ locale: 'en-US' }); // relabels in the next frame; the view stays
const mine = createLocale('en-GB', { volume: (v) => `${v} sh`, words: { 'tools.stop': 'SL' } });
chart.setOptions({ locale: mine });
createLocale(tag, overrides) replaces single parts: a formatter, the
month or weekday names (dates use them too), or words by key. Words
missing in a locale fall back to English. Each chart has its own locale,
so two charts on a page can differ; api.locale() returns the one in use,
and a primitive's painter finds it as p.locale.
Live and replay
update compares the new times with the chart's by content, so the cheap
way to feed live data is the obvious one:
- The forming bar changes in place: write the new close (and high,
low, volume) into the same arrays and call
updatewith them. The timeline is kept, and the next frame paints the visible bars. - New bars come in new, longer arrays. The timeline is extended by the
new bars only (an appended bar costs about 5 % of a fresh build at
20,000 minute bars), and when the right edge of the view was at the last
bar, the view moves with them.
followLast: false(option or prop) keeps it where it is. - Older history (paging back) comes in arrays with bars in front. The view shifts by their number, so the bars on screen keep their pixels, and a linked chart keeps showing the same days.
- Anything else, such as a correction in the middle of the history, builds
the timeline afresh and applies the spec's
view.
A replay is the same as live data: hand over one more bar per step.
Draggable levels
A level with drag (and an id) is an order line the user can move on an
interactive chart. The chart moves the line; the app decides:
const levels = orders.map((o) => ({
id: o.id,
price: o.limit,
color: o.side === 'buy' ? '@up' : '@down',
title: `${o.side} ${o.quantity}`,
drag: {
step: 0.01, // the tick size
onMove: (price) => (ticket.limit = price),
// false: back to the old price at once; a promise: dashed until the
// server answers, back on false or an error.
onDrop: (price) => (price <= 0 ? false : api.modifyOrder(o.id, price).then(() => true)),
onCancel: () => (ticket.limit = o.limit)
}
}));
chart.update({ ...spec, levels });
An accepted line stays at its new price until the next update, whose
price then wins; a refused one returns without waiting for an update.
Escape cancels a drag. Presses go to the input handler (the drawing
editor) first, then to the lines, then to panning, so a drawing over an
order line stays movable. Hovering a line shows ns-resize; autoscale: true keeps a dragged line in view.
Layout
The layout event (onlayout on ChartView) reports the plot area and
every pane's rectangle in CSS px after a frame whose layout changed: a
resize, a separator drag, panes added or removed, an axis that grew. A
legend or toolbar made of page elements sits on it:
<script lang="ts">
import type { LayoutInfo } from 'kerzwerk';
import { ChartView } from 'kerzwerk/svelte';
let layout = $state<LayoutInfo | null>(null);
</script>
<div class="relative h-96">
<ChartView {spec} onlayout={(info) => (layout = info)} />
{#each layout?.panes ?? [] as pane (pane.id)}
<div class="absolute text-xs" style="left: {pane.rect.x + 6}px; top: {pane.rect.y + 4}px">
{titles[pane.id]}
</div>
{/each}
</div>
Heights the user dragged are in layout.resized and api.paneHeights();
store them and hand them back with api.setPaneHeights(stored) before the
first update. They survive updates and give way when the spec's own
height of a pane changes. api.barSpacing() and api.setBarSpacing(px)
read and restore the zoom; the setter keeps the right edge.
Indicators
An indicator arrives as a description and its columns. indicatorParts
turns them into panes, series and levels to merge into the spec; the chart
does not know how the values were computed, so columns from a catalog in
the browser and from a job on a server draw the same way.
import { indicatorParts, type IndicatorDrawing } from 'kerzwerk';
const rsi: IndicatorDrawing = {
id: 'rsi-1',
label: 'RSI 14',
pane: { range: { min: 0, max: 100 } },
plots: [{ key: 'value', kind: 'line', color: '@ind-violet', width: 2 }],
levels: [{ value: 70, style: 'dashed' }, { value: 30, style: 'dashed' }]
};
// values[drawing.id][plot.key]: one column per plot, bars.length long, NaN for a gap.
const parts = indicatorParts([rsi], { 'rsi-1': { value: rsiColumn } }, { length: n, open, close });
const spec: ChartSpec = {
timeline: { kind: 'time', times, ahead: Math.max(myAhead, parts.ahead) },
panes: [{ id: 'main' }, ...parts.panes],
series: [candles, ...parts.series],
levels: [...myLevels, ...parts.levels]
};
- Ids: the pane is the drawing's id, a series
<id>:<key>, a fill<id>:<upper>:fill, a level<id>:level:<i>. Two drawings with one id throw. - Panes:
pane: 'price'draws on the app's price pane ('main', or the fourth argument); otherwise the drawing gets its own pane, 120 px unless it says otherwise, with its range and number format. - Plots: lines in whole pixels, histograms coloured per bar by the
value's sign or the bar's direction (
colorBy, the latter needs the bars'openandclose), points (3 px unlesswidth). Fills come first as bands, so the lines paint over them;crossedcolours where the edges have crossed, as Ichimoku's bearish cloud. - Shifts: a plot with
shift: 26reads its column 26 bars back; the slots after the last bar it needs come back asahead, and every series isbars.length + aheadlong. A negative shift drops what moves before the first bar. - Hidden:
visible: falsekeeps the pane (a dragged height survives hiding) with its series hidden and no levels. - Colours:
theme.csshas the roles an indicator catalog uses,@ind-blue,@ind-amber,@ind-violet,@ind-emerald,@ind-rose,@ind-cyan,@ind-fuchsia,@ind-slate,@ind-green,@ind-red, and@indicator-levelfor the levels.withAlpha('@ind-blue', 12)thins a colour;cssColorwrites one for a page element (a swatch).
Legend groups. Every series of a drawing carries legendGroup (its
id) and groupTitle (its label). The legend shows a group as one item on
its own line, the label and then each value in its colour after its title
("MACD 12 26 9 Histogram 0,2500 MACD 1,75 Signal 1,50"). The layout event
reports where each label sits (layout.legend, chart coordinates), so an
app can put its buttons there (hide, settings, remove); the boxes move
when labels, panes or sizes change, never with the values. legendGap
keeps that many CSS px free after each label, so the buttons cover no
value.
<ChartView {spec} legend legendGap={28} onlayout={(info) => (layout = info)} />
{#each layout?.legend ?? [] as box (box.id)}
<button class="absolute" style="left: {box.rect.x + box.rect.width + 4}px; top: {box.rect.y}px"
onclick={() => toggle(box.id)}>👁</button>
{/each}
The catalog that writes these descriptions for 29 indicators is
zeigerwerk (drawing(resolve(setting), 'de')); kerzwerk does not
depend on it.
Linked charts, aggregation, images
createSyncGroup()passed assyncto several charts shares crosshair, visible range and price-axis width — stacked charts line up.aggregateDays(weeks, months) andaggregateMinutes(5–60 minutes, aligned to the session open) build larger bars from daily and minute bars.api.toImage()gives a PNG of the chart;saveImage(api, 'chart.png')downloads it.
Drawing tools
import { createDrawingEditor, type Drawing } from 'kerzwerk/tools';
const editor = createDrawingEditor(api, {
onchange: ({ kind, drawing }) => save(kind, drawing), // 'add' | 'update' | 'remove'
onselect: (drawing) => (selected = drawing)
});
spec.primitives = [editor.primitive]; // paints the drawings and the draft
editor.set(savedDrawings);
editor.setTool('trend');
Tools (ToolKind): hline, hray, vline, trend, ray, rect,
fib, measure, long (a position with stop and target), text.
Anchors are (time, price), so a drawing survives a change of timeframe.
Escape cancels, Delete removes the selected drawings. Storing drawings is
the app's business: store locked and z with the rest.
- Several at once: Shift or Ctrl/Cmd and a click adds or removes a
drawing; with the modifier on the empty plot a box selects every drawing
inside it. Dragging one of them moves all.
selection(),setSelection(ids),onselection(drawings);onselectnames the one drawing, or null for none or several. - Lock (
locked: true): no gesture, key or action on several moves, reshapes or deletes it; a press on it pans. A padlock shows it. The app's ownchangeandremovestill work. - Stacking order (
z, absent 0): higher paints above and is hit first.toFront(),toBack(); a new drawing gets azonly once some drawing has one. - Actions:
duplicate(),align('top' | 'middle' | 'bottom' | 'left' | 'right'),lock(on),removeSelection(),copy(),cut(),paste(). Each reports its changes once more together inonchanges(changes), after theonchangeper drawing. - Clipboard: copied drawings paste into any chart of the page, also
after client-side navigation (
clipboardreplaces that slot); Ctrl/Cmd+C, X and V on the focused chart go through the system clipboard as text, so they reach another tab or app with kerzwerk. - Keys (
keys):deleteDelete/Backspace,duplicateCtrl/Cmd+D,deselectEscape,copy/cut/pasteCtrl/Cmd+C/X/V; an empty list switches one off:keys: { duplicate: [], copy: [], cut: [], paste: [] }.
Context menu
A right-click, a finger held still for half a second, the menu key or
Shift+F10 asks the app's menu for the entries of what is under the
pointer. The chart owns the trigger and describes the menu as data; the
app shows it with its own components. Without setMenu the browser keeps
its own menu and nothing changes.
With shadcn-svelte (or bits-ui's ContextMenu):
<script lang="ts">
import * as ContextMenu from '$lib/components/ui/context-menu';
import { ChartMenu, ChartView } from 'kerzwerk/svelte';
import type { ChartApi, MenuEntry, MenuTarget } from 'kerzwerk';
let api = $state<ChartApi>();
const alert = (entries: MenuEntry[], target: MenuTarget): MenuEntry[] =>
target.kind === 'plot' ? [...entries, { id: 'app.alert', label: 'Alert here', run: () => addAlert(target.price) }] : entries;
</script>
<ChartView {spec} interactive bind:api />
<ChartMenu chart={api} ui={ContextMenu} items={alert} />
Without Svelte, any menu: open gets the target and the entries.
// menu: <div popover style="position: fixed; margin: 0">
chart.setMenu({
open({ target, items }) {
menu.replaceChildren(
...items.flatMap(function row(e): HTMLElement[] {
if (e.kind === 'separator') return [document.createElement('hr')];
if (e.kind === 'group' || e.items) return e.items!.flatMap(row);
const b = document.createElement('button');
b.textContent = (e.checked ? '✓ ' : '') + e.label;
b.disabled = e.disabled ?? false;
b.onclick = () => (e.run?.(), menu.hidePopover());
return [b];
})
);
menu.style.left = `${target.clientX}px`;
menu.style.top = `${target.clientY}px`;
if (items.length) menu.showPopover();
},
items: (items, target) => items // add, drop or reorder entries here
});
target.kind is what was hit, in this order: drawing or selection
(the editor's), level, mark, series, span (those with an id),
plot, priceAxis, timeAxis. It carries the ids, the pane, the bar
index, its time, the price at the pointer and the point in chart,
client and page coordinates. Entries are items (label, shortcut,
icon, disabled, checked, a submenu in items, run), separators
and groups (choice for radio entries). Each entry runs at most once per
opening. The chart's own: the price axis switches the scale mode and fits
it, the time axis goes to the latest bar or fits all; the editor's: lock,
duplicate, copy, cut, delete, front, back, align (several), paste (plot),
and Properties when onproperties is given. Words follow the locale;
createLocale(tag, { words: { 'menu.lock': '…' } }) renames one.
Undo and redo
Every action of the drawing editor is a step in a history: drawing,
moving, reshaping, change, deleting, and every action of the menu.
Ctrl/Cmd+Z takes the latest back, Ctrl/Cmd+Shift+Z and Ctrl+Y bring it
again, and the plot menu shows "Undo Move" and "Redo …" above Paste.
Undo and redo report through onchange and onchanges like any action,
with origin: 'undo' or 'redo', so a store that saves on every change
follows without code of its own. set is never recorded.
One history for the whole workspace, shared by its charts and the app:
import { createDrawingEditor, createHistory } from 'kerzwerk/tools';
const history = createHistory(); // limit 100, merge 1000 ms
const daily = createDrawingEditor(dailyApi, { history, onchange: save });
const hourly = createDrawingEditor(hourlyApi, { history, onchange: save });
daily.set(drawingsOf('AAPL'), { document: 'AAPL' });
// A step of the app, undone and redone in order with the drawings:
history.run({ label: 'Add RSI', redo: () => indicators.add(rsi), undo: () => indicators.remove(rsi.id) });
// Several changes as one step, and changes that are not steps:
history.group('Add RSI with levels', () => { /* history.run(…), editor.change(…) */ });
history.quiet(() => hourly.change(id, patch)); // copying a change into a second chart
// Buttons:
history.on('change', ({ undo, redo, busy }) => toolbar.update(undo, redo, busy));
A step only runs on the state it left: when a drawing was changed
elsewhere since (another tab, a server push, a quiet change), or no
chart shows its drawings any more, the step is skipped and reported
(history.on('skip', …)). set(drawings, { document }) names what an
editor shows, so a reload of the same symbol keeps its steps and another
chart showing it can take them; without a name, every set with other
drawings starts afresh. An app step may return false or a promise; a
refused one stays in place (on('fail'), drop() gives it up).
historyEntries(history, locale) gives Undo and Redo as menu entries
for the app's own menus; keys: { undo: [], redo: [] } switches the keys
off.
Working on the library and an app together
# in kerzwerk
npm run dev # svelte-package --watch, writes dist/
# in the app
npm install ../kerzwerk # a link to the working copy
An app that installs the package under another name links it under that
name: npm install @jean/kerzwerk@file:../kerzwerk.
If Vite refuses to serve files from the linked folder, allow it in the
app's vite.config.ts: server: { fs: { allow: ['../kerzwerk'] } }.
The first start after installing or updating the package can show an
empty chart and an error in the console ("504 Outdated Optimize Dep", or
Cannot read properties of undefined (reading 'call')): Vite has just
pre-bundled the new dependency while the page loaded. Reload once.
The link brings kerzwerk's own copy of Svelte along. If the app's
svelte-check then reports errors about Snippet ("Two different types
with this name exist") in pages that have nothing to do with charts,
install a tarball instead, which resolves like the registry:
npm pack here, then npm install <path>/kerzwerk-<version>.tgz in
the app.
Back to the release: npm install kerzwerk@latest. Never commit the
app with the link.
Releases
Every version goes to two registries with the same files: to npm as
kerzwerk, and to the registry on Jean's Gitea as @jean/kerzwerk, for
the apps that install it from there.
npm version patch # or minor; writes the version and a tag
npm publish # to npm; runs check, tests and build first
npm run publish:gitea # the same files as @jean/kerzwerk
git push --follow-tags
Each registry needs a token with write access in the npm config of the
machine that publishes, never in a repository. Note user-visible changes
in CHANGELOG.md.
Adding a series kind
A new kind (say a baseline) is a type in the contract and one case at each
place that branches on s.kind: the type in core/types.ts (interface,
entry in SeriesSpec), the accessors in core/series.ts (seriesLength,
seriesRange, seriesHigh/Low, seriesValue, seriesValues,
firstValue — autoscale, magnet, legend and percent base read only through
them), the painter in core/paint/series.ts (paintSeries; visible bars
only, positions through bx/by), the legend in core/legend.ts and the
colour of the last value (seriesColor at the end of core/chart.ts).
Several of these handle every series with values in their default; a
kind with other columns needs its own case there — grep -n "case 'band'"
lists them all. Add a painter test against the recorder
(src/test/recorder.ts).
Development
npm install
npm test # vitest, in Node, no browser (684 tests)
npm run check # svelte-check
npm run build # dist/
The pictures in this README are drawn by the library from made-up prices;
docs/showcase/ holds the page that makes them and how to run it.
Design and history: feature 003 (the library) and feature 005 (this
package) in the strategies repository, docu/feat/.
Dependencies
Development Dependencies
| ID | Version |
|---|---|
| @sveltejs/package | ^3.0.2 |
| @sveltejs/vite-plugin-svelte | ^7.2.0 |
| @types/jsdom | ^30.0.0 |
| @types/node | ^26.6.5 |
| bits-ui | ^2.21.0 |
| jsdom | ^26.1.0 |
| rolldown | ^1.2.19 |
| svelte | ^5.57.1 |
| svelte-check | ^4.6.0 |
| typescript | ^6.0.3 |
| vite | ^8.3.0 |
| vitest | ^5.0.4 |
Peer Dependencies
| ID | Version |
|---|---|
| svelte | ^5.0.0 |



