# Architecture & Determinism

> Pure functional studies, Zig/WASM SIMD acceleration, Web Worker isolation, closed-bar guarantees, and drawing validation.

Canonical page: [https://docs.kami.trade/engine/architecture/](https://docs.kami.trade/engine/architecture/)

Every study in Kami's TA engine is a pure deterministic function of closed candles, validated numeric parameters, and optional closed higher-timeframe candles. Given the same inputs, it produces identical drawings and facts across every browser, device, and runtime.

## Execution Pipeline

1. **Closed-bar slicing (`closedCount`)**: The engine checks `candles[n - 1].timestamp + intervalMs <= now`. If false, the forming candle is excluded before any study reads the series. Every result records `basis.forming = 'excluded'`.
2. **Struct-of-Arrays unpacking (`Series`)**: Closed candles are unpacked once into contiguous `Float64Array` columns (`t`, `o`, `h`, `l`, `c`, `v`, `atr`) with Wilder's `ATR(14)` precomputed once per series.
3. **Web Worker offload (`ta.worker.ts`)**: Charts transfer packed `Float64Array` buffers (`6` doubles per candle) zero-copy to a dedicated worker running its own `engine.wasm` instance. At idle, the worker pre-warms all 15 studies into a `128`-entry LRU cache so clicking a study is an instant cache hit on the main thread.
4. **Dual-level memoization**: `seriesMemo` (LRU `8`) caches unpacked series; `resultMemo` (LRU `64`) caches computed results keyed by series fingerprint, window basis, study name, resolved parameters, and HTF fingerprint.
5. **Collision-free layout (`taNotation`)**: Overlay mutations batch in a single microtask. All edge labels and point marks resolve collisions together in one pass before painting.

## Zig/WASM SIMD Backend

Hot inner loops compile from Zig (`wasm32-freestanding` with `simd128`, `@Vector(8, f64)`) to a zero-import, zero-allocator `engine.wasm` binary. At runtime, Kami validates `simd128` support with a 31-byte probe and loads WASM asynchronously; until ready (or if SIMD is unsupported or memory allocation throws), TypeScript kernels execute with identical IEEE-754 double results.

To prevent platform `Math.pow` drift between V8 and Zig/WASM, exponential decay (`halfWeight(age, halfLife)`) uses IEEE `+, -, *, /` only (repeated squaring of `0.5` plus a 17-term Horner polynomial for `e^(-f * ln 2)`).

| Backend | Kernels |
| --- | --- |
| **Zig/WASM SIMD (10)** | `atrWilder`, `median`, `fractalPivots`, `zigzag`, `srScan`, `trendScan`, `lineTouches`, `channelFit`, `zoneScan`, `zoneTests` |
| **TypeScript (6 + study logic)** | `alternate`, `rangeScan`, `breakScan`, `fvgScan`, `vpvrScan`, `sortAsc`, `liquidity`, `divergence`, `sessions`, `htf`, `avwap`, `auto`, all 12 indicators |

WASM linear memory reserves an `8 MiB` resident ring buffer (up to `32` pinned `Series` blocks via `WeakMap`/`WeakRef`) plus a 16-byte-aligned per-call staging bump allocator (`4 MiB` initial, capped at `1 GiB`).

## Zero-Lookahead & Causal Rules

| Guard | Mechanism |
| --- | --- |
| **Forming bar exclusion** | `closedCount()` drops the live candle whenever `timestamp + intervalMs > now`. |
| **Causal pivot breaks** | `breakScan` only allows a fractal pivot at `idx` to be broken at bar `k >= idx + span`. |
| **Causal SFP sweeps** | `liquidity` only scans for sweeps of a swing at `j` starting at `k = j + pivotSpan + 1`. |
| **HTF lookahead clamp** | `closedHtf()` trims any HTF candle with `timestamp + htfIntervalMs > Math.min(now, windowEnd)` so panning back in history never leaks future HTF levels. |
| **Incomplete bucket exclusion** | Local HTF aggregation drops trailing buckets where `bucketStart + targetMs > lastClosedEnd`. |
| **Warm-up isolation** | View-mode slices prepend up to `50` bars before `from` to seed `ATR(14)`, then cut them off via `.subarray(warmUp)` so no pivot, line, or zone can anchor in warm-up bars. |

## Drawing Primitives & Label Priority

Studies emit typed `Drawing` objects rendered by custom KLineChart overlays.

| Kind | Visual representation | Used by |
| --- | --- | --- |
| `level` | Horizontal price line with right-edge label and axis tag | `structure` (EQ), `sessions`, `htf` (EQ / fallback), `auto` (POC) |
| `band` | Shaded `[low, high]` price band with solid or dashed center line | `sr`, `htf` (S/R) |
| `trendline` | Segment (`extend: false`) or right-projected ray (`extend: true`) | `trend`, `structure` (BOS/CHoCH), `liquidity` (EQH/EQL), `divergence` |
| `zone` | Shaded rectangle from `from` to `to` with optional dashed `mid` line | `zones`, `range`, `fvg`, `sessions` (Asia/London/NY), `htf` (FVG) |
| `fib` | Retracement leg, shaded `0.618–0.65` Golden Pocket, ratio and extension lines | `fib` |
| `channel` | Filled parallel channel with solid base rail, faint 50% median, dashed upper/lower rail | `channel` |
| `profile` | Right-aligned buy/sell volume histogram (`48–180 px` wide), Value Area shading, POC/VAH/VAL | `vpvr` |
| `curve` | Viewport-culled polyline with edge tag at the final point | `avwap` |
| `mark` | Point label anchored above or below a candle (`taNotation` only) | `structure`, `range` (deviations), `liquidity` (sweeps), `divergence` |
| `note` | Annotation bubble at `(time, price)` | Manual / AI agent drawing tool |

### Edge Label Priority

When right-edge price tags collide, `taNotation` preserves vertical price order, avoids fixed last-price and indicator axis rows, shifts labels by at most `45 px` (`3 * 15 px`), and drops lower-priority labels using this hierarchy:

| Priority | Source |
| --- | --- |
| `5000` | `level` |
| `4000 + score` | `band` |
| `3000` | `range` edges |
| `2500` | `trend` ray |
| `2200` | `curve` (`avwap`) |
| `2000` | `fib` endpoints (`0`, `1`) |
| `1500` | `fib` key ratios (`0.382`, `0.5`, `0.618`) |
| `1000` | Other `fib` ratios |
| `500` | `zone` |
| `450` | `channel` |
| `400` | `trendline` segment |
| `300` | `mark` |

## Validation Guards

Every call to `chartApi.draw()` runs `checkDrawing(drawing, candles, intervalMs)`:

- **Price range**: All prices must fall inside `[lo - span * 2, hi + span * 2]` where `span = (hi - lo) || hi * 0.01`.
- **Time range**: Timestamps must fall inside `[first, last + (last - first)]`.
- **Geometry**: Bands require `low <= price <= high` and `low < high`; zones require `low < high`; profiles require non-empty bins and `val <= poc <= vah`; curves require at least `2` points with strictly increasing timestamps.

Manual AI agent drawings additionally pass `validateAnchors()`, requiring every anchor timestamp to match an exact loaded candle start and every price to sit within `1 ATR` (`2 ATR` for curves) of the spanned candle range.
