Tagged for strategies, which reads the crate from Gitea; not published to npm. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zeigerwerk
One indicator catalog for every app. The definitions and their computation are written once, in Rust, and used in three ways:
- natively, as the crate
zeigerwerk(strategies' Rust server and its research parity tests); - as WebAssembly in the browser and in Node, through the npm package
zeigerwerk(trading_book, tws-dashboard, strategies' web app); - as a drawing description for the chart library
kerzwerk, which draws it with
indicatorParts.
Every place computes the same bits for the same bars. Why and how:
kerzwerk's specs/004-shared-indicators/.
What changes against the apps' old code:
docs/migrations.md;
which variant equals which research function:
docs/research.md.
36 definitions: sma, ema, wma, vwap, psar, ichimoku,
supertrend, rsi, macd, stoch, stochrsi, cci, willr, roc,
momentum, ao, bbands, keltner, donchian, atr, stddev, adx,
volume, obv, mfi, cmf (tws-dashboard's 26), atrzone, adr,
rs (strategies'), and atrpct with six event signals, rally, gap,
breakout, macross, volclimax, drawdown (rallyscope's events): a
signal is +1 or −1 on the bar of an event and 0 elsewhere.
And 91 candle patterns after Bulkowski, in a table of their own beside the definitions (Candle patterns), bit for bit as strategies' screener finds them.
Install
npm install zeigerwerk
It has no runtime dependencies and carries the WebAssembly module inside
(about 107 kB), so no bundler or server has to find a .wasm file. It
loads with import and with require.
Settings
An indicator is stored as a portable setting: its id, its definition and only what differs from the defaults.
import { newSetting, parseSetting, resolve, writeSetting, type Setting } from 'zeigerwerk';
const rsi: Setting = { id: 'rsi-1', def: 'rsi', params: { period: 21 }, styles: { value: { color: '#7c3aed' } } };
const r = resolve(rsi); // defaults filled, numbers clamped and rounded
r.values.period; // 21
r.issues; // [] — or { code: 'clamped', path: 'params.period', message: 'issue.clamped' }
const { setting, issues } = parseSetting(JSON.parse(stored)); // never throws
const toStore = writeSetting(setting!); // defaults dropped, unknown fields kept
resolve never refuses: a value it cannot use is replaced and reported.
Issues carry a word key (issue.clamped) for the app's language.
Computing
Runs need the module once per process:
import { load, resolve, run, compute, warmup } from 'zeigerwerk';
await load();
const r = resolve({ id: 'bb', def: 'bbands' });
const x = run(r, bars, { clock: { zone: 'America/New_York' } });
x.outputs(); // { upper, middle, lower }: Float64Array each, NaN for a gap
x.append(nextBar); // one bar more: one row computed
x.replaceLast(forming); // the forming bar changed
x.free();
compute(r, bars); // the same in one call, for a job
warmup(r); // 20: bars of history after which the start no longer matters
bars holds columns: time in Unix seconds (UTC), open, high, low,
close, optionally volume (null and undefined are gaps). Inputs
beyond the bars:
clock: the exchange's time zone, for definitions that read sessions (VWAP per trading day).sessionKeys(time, clock)shows the keys.benchmark: the benchmark's closes aligned to the bars, for relative strength (alignByTime(time, { time, close })).
The values are causal: a row depends on its bar and the bars before.
Ichimoku's spans are drawn shifted; valueAt(resolved, outputs, key, i)
gives what is drawn at bar i, shift included, for a legend or an alert.
warmup is Infinity where no count exists: OBV, VWAP over all bars,
relative strength and Parabolic SAR depend on where the bars start.
Drawing with kerzwerk
import { drawing } from 'zeigerwerk';
import { indicatorParts } from 'kerzwerk';
const settings = [rsiSetting, bbSetting];
const drawings = settings.map((s) => drawing(resolve(s), 'de'));
const values = Object.fromEntries(settings.map((s) => [s.id, compute(resolve(s), bars, inputs)]));
const parts = indicatorParts(drawings, values, { length: n, open: bars.open, close: bars.close });
// parts.panes, parts.series, parts.levels and parts.ahead go into the chart's spec.
drawing() merges the definition's defaults with the setting: placement,
pane height and range, colours (roles such as @ind-violet, defined by
kerzwerk's theme.css), line styles, shifts, fills and levels, and the
legend label ("RSI 14"). zeigerwerk does not depend on kerzwerk; a type
check in js/test/kerzwerk.check.ts keeps the two descriptions equal.
Picker and form
import { categories, formFields, resetField, search, setField } from 'zeigerwerk';
search('bänder', { lang: 'de' }); // [Bollinger]; every word, any language, accents folded
categories('de'); // Trend, Momentum, Volatilität, Volumen
formFields(setting, 'de'); // parameters, shift, then colour, width, line, visible per output
const { setting: next, issue } = setField(setting, 'period', 0); // refused: issue out-of-range
resetField(setting, 'style.upper.color'); // back to the default: the key is removed
The catalog ships no components: each app renders the fields its own way.
Words: word(key, lang), name(def, lang), label(resolved, lang); the
dictionaries are words/en.json and words/de.json, also served as
zeigerwerk/words/*.
Candle patterns
The 91 patterns of Bulkowski's Encyclopedia of Candlestick Charts, as
strategies' research and screener define them (C40 is the hammer). They
are not definitions: no parameters, nothing to draw, no form. A pattern run
gives a mask per bar.
import { findPatterns, load, pattern, patternMask, patternName, patternRun, patterns } from 'zeigerwerk';
await load();
findPatterns(bars, ['C40', 'C36']); // [{ bar: 20, ids: ['C40'] }, …]: bars completing a chosen pattern
findPatterns(bars); // all 91
const r = patternRun(bars);
r.has(20, 'C40'); // true
r.ids(20); // every pattern bar 20 completes, in table order
r.hits(patternMask(['C40'])); // as findPatterns
r.masks(); // Uint32Array, four words per bar
r.append(bar); // one bar more
r.replaceLast(forming); // the forming bar changed
r.free();
pattern('C40'); // { index: 29, id: 'C40', bars: 1, side: 1, taught: 1, group: 'reversal', trend: 'down' }
patternName('C41', 'de'); // "Hammer, umgekehrt"; patternShortName gives "IH" for a chart's mark
A pattern's index is its bit in a mask, and the table only grows at its
end. A mask has 128 bits, which a JavaScript number cannot hold, so it
crosses as four 32-bit words per bar, lowest bits first: pattern i at bar
b is bit i % 32 of word 4·b + ⌊i / 32⌋. side is the direction
Bulkowski measured after the pattern, taught the one the textbooks teach;
group says whether he found a reversal or a continuation, trend which
trend the rule asks for before the pattern (any: none).
The rules compute in single precision (f32), as strategies' screener
stores its bars: each bar is rounded to f32 first. A mask is causal: bar
i reads bars 0..=i. The trend's 10-bar EMA starts at the first bar
given, so a mask near a threshold can depend on where the bars start.
Reading the apps' stored indicators
import { fromTwsDashboard, fromTwsAlert, fromTradingBook, fromTradingBookStorage, fromStrategies } from 'zeigerwerk/legacy';
const { settings, issues } = fromTradingBookStorage((key) => localStorage.getItem(key));
None of them throws. What they cannot read becomes an issue with the raw
value in its path; what they read and changed is reported as legacy.
fixtures/corpus/ holds real stored settings of the three apps and what
they read as.
Rust
use zeigerwerk::{definition, compute, Run, Columns};
let def = definition("sma").unwrap();
let rows = compute(def, &def.defaults(), &columns)?; // one Vec per output
let mut run = Run::new(def, &[50.0, 3.0])?; // period 50, close
run.reset(&columns)?;
run.append(&bar);
run.replace_last(&bar);
let warm = (def.warmup)(&def.defaults()); // zeigerwerk::NEVER if none
let masks = zeigerwerk::pattern_masks(&open, &high, &low, &close)?; // a u128 per bar
let mut patterns = zeigerwerk::PatternRun::new(); // reset, append, replace_last as Run
let hammer = 1u128 << zeigerwerk::pattern_index("C40").unwrap();
// Pivots, trend lines, levels and 30 chart formations (strategies' feature 025).
use zeigerwerk::formations::{analyze, Options};
let a = analyze(&columns, Options { reversal: 2.5, log: true })?; // daily bars in ln(price)
for f in &a.formations { let _ = (f.kind.id(), f.status(), f.upper.map(|l| l.at(100.0))); }
// Which moving average a stock respects, with rallyscope's respect score.
let lines = zeigerwerk::reactive::analyze(&columns, zeigerwerk::reactive::Side::Support, 0, n)?;
// The logarithm and exponential behind the log space: fdlibm, the same bits everywhere.
let x = zeigerwerk::math::ln(105.0);
formations and reactive are modules beside the catalog, like the
candle patterns: their results are records (a formation, a touch) whose
state later bars decide, not one value per bar. Both are frozen like the
definitions: a changed rule is a new VERSION. They are not in the
WebAssembly module or the npm package yet; strategies' server computes
them and its app draws the answers.
The crate has no dependencies. Arithmetic in kernels is restricted to
correctly rounded operations (tests/arith.rs), which is why native and
WebAssembly give the same bits.
Third-party code
src/math/ ports fdlibm's e_log.c and e_exp.c (as FreeBSD's msun
carries them) to Rust; scripts/math-reference/ holds the C originals as
the reference. Their notice:
Copyright (C) 1993 (log) and 2004 (exp) by Sun Microsystems, Inc. All rights reserved. Developed at SunSoft, a Sun Microsystems, Inc. business. Permission to use, copy, modify, and distribute this software is freely granted, provided that this notice is preserved.
Build and test
cargo test --release
cd js && npm install && npm run build && npm test && npm run check
npm run bench # SC-005: all 29 over 20,000 bars, updates, replay; the 91 patterns
npm run size # module and JavaScript against their budgets
npm run check:browser # the golden digests in a real browser (localhost:5180)
The WebAssembly build needs rustup target add wasm32-unknown-unknown.
A changed computation shows in the golden digests (fixtures/golden.json):
a released one never changes; a new variant gets a new choice value or a
new definition instead.
Releases
The version stands in Cargo.toml and js/package.json; both change
together, and the repository gets the tag v<version> (Rust users depend
on the crate by Git tag). Every version goes to two registries with the
same files: to npm as zeigerwerk, and to the registry on Jean's Gitea as
@jean/zeigerwerk, for the apps that install it from there.
git tag -a v0.1.0 -m 0.1.0
cd js && npm publish # to npm; runs build, check and tests first
npm run publish:gitea # the same files as @jean/zeigerwerk
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. User-visible changes go
into CHANGELOG.md.
