@jean/kerzwerk (0.2.0)
Installation
@jean:registry=https://code.jeanavril.com/api/packages/jean/npm/npm install @jean/kerzwerk@0.2.0"@jean/kerzwerk": "0.2.0"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 |
|---|---|
@jean/kerzwerk |
the core: createChart, aggregation, sync groups, all types |
@jean/kerzwerk/svelte |
ChartView, the Svelte 5 binding |
@jean/kerzwerk/tools |
drawing tools: createDrawingEditor and helpers |
@jean/kerzwerk/theme.css |
default colours, light and dark |
An app carries only what it imports.
Install
The package lives in the npm registry of Jean's Gitea and can be read
without a token. In the app, an .npmrc next to package.json maps the
scope:
@jean:registry=https://gitea.public.mgmt/api/packages/jean/npm/
Then:
npm install @jean/kerzwerk
A first chart (Svelte)
<script lang="ts">
import '@jean/kerzwerk/theme.css';
import { ChartView } from '@jean/kerzwerk/svelte';
import type { ChartSpec } from '@jean/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 '@jean/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 '@jean/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 '@jean/kerzwerk';
import { ChartView } from '@jean/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.
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 '@jean/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 drawing. Storing drawings is
the app's business.
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
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>/jean-kerzwerk-<version>.tgz in
the app.
Back to the release: npm install @jean/kerzwerk@^0.2.0. Never commit the
app with the link.
Releases
npm version patch # or minor; writes the version and a tag
npm publish # runs check, tests and build first
git push --follow-tags
Publishing needs a Gitea token with package write access in your user npm config, once per machine — never in a repository:
npm config set -- //gitea.public.mgmt/api/packages/jean/npm/:_authToken "YOUR_TOKEN"
publishConfig sends the package to the Gitea registry only; it cannot end
up on the public npm registry by mistake. Packages on Gitea take the
visibility of their owner: while the user jean is public, anyone who
reaches gitea.public.mgmt can install them, though the repository is
private. 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 (351 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 |
| 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 |



