# Versioned indicator contracts These are pure observation-based calculations. They do not read the clock, generate randomness, obtain prices, submit orders or persist state. Use one stream instance per instrument/series, and supply admitted observations in order. The caller owns instrument identity, timestamp ordering, gap policies and timeframe selection; periods count input observations, not elapsed minutes. Missing bars are never invented here. ## Alignment, initialization and variants Batch output is `{ contract, startIndex, values }`: value `i` belongs to input position `startIndex + i`. No leading zero/NaN padding is generated. An incomplete batch has an empty values array but still reports its intended start index. Existing `sma()` retains its earlier array return type; its first output belongs to input `period - 1`. | Calculation | Initialization and recurrence | First source index | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------ | | `ema`, `seed: 'sma'` (default), `ema/v1` | Seed from the first period's mean, then weight each new observation by `2/(period+1)` | `period - 1` | | `ema`, `seed: 'first'`, `ema/v1` | Seed immediately from the first observation; same subsequent weights | `0` | | `rsi`, `rsi-wilder/v1` | Seed gain/loss averages from the first `period` changes, then apply Wilder smoothing, consuming each change once | `period` | | `atr`, `firstRange: 'previous-close'` (default), `atr-wilder/v1` | Skip the first bar's range; seed from the next `period` true ranges, then apply Wilder smoothing | `period` | | `atr`, `firstRange: 'high-low'`, `atr-wilder/v1` | Include the first bar's high-low range in the seed; same subsequent smoothing | `period - 1` | RSI with gains but no losses is 100; losses but no gains is 0. If **both** averages are zero, `flatValue` explicitly chooses 0, 50 or 100; the new core defaults to neutral 50. That flat policy is an application convention, not a claim that all RSI libraries agree. HLC bars must be finite and satisfy `low <= close <= high`. ATR is in input price units. Periods must be positive safe integers below `Number.MAX_SAFE_INTEGER`. Non-finite inputs, invalid options and unrepresentable accumulators/results throw. Sparse arrays are not skipped. No missing-price substitution or intermediate decimal rounding occurs. The initializer distinction is corroborated by the pinned [TA-Lib EMA implementation](https://github.com/TA-Lib/ta-lib/blob/v0.6.4/src/ta_func/ta_EMA.c). Wilder's seed/recurrence and directional zero handling are described by [StockCharts RSI](https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/relative-strength-index-rsi). The true-range definition and high-low first-bar variant are described by [StockCharts ATR](https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/average-true-range-atr). Our previous-close variant also matches this repository's native ATR. These are formula references, not copied implementations or claims of identical defaults across libraries. ## Streaming and restart state ```ts import { AtrIndicator, EmaIndicator, RsiIndicator } from '@stock-bot/calculations/indicators'; const stream = new RsiIndicator(14, { flatValue: 50 }); stream.update(100); // null until the first 14 changes are available const persisted = JSON.parse(JSON.stringify(stream.snapshot())); const resumed = new RsiIndicator(14, { flatValue: 50 }); resumed.restore(persisted); // validates contract, phase, counters and configuration const value = resumed.update(101); ``` `update()` and `current()` return `number | null`; only warm-up returns null. A legitimate zero is never treated as missing. All three streams use constant-size, finite JSON state and O(1) work/memory per observation. They do not retain the input history. Each snapshot includes its versioned contract string, period, variant settings and observation count: - EMA: seed accumulator before readiness, current value afterward. - RSI: previous observation and gain/loss accumulators (sums during seed, averages after). - ATR: previous close, seed accumulator and current smoothed range. Snapshots are detached copies. Invalid updates, arithmetic failures and failed restores leave prior state intact. Reset retains configuration and clears all observed history. Unknown fields/contracts, invalid numbers/counters, incompatible configuration and inconsistent warm-up phases are rejected. Counters cannot exceed safe integer precision. `fromSnapshot()` constructs a new stream using the snapshot's settings. Use an existing configured instance's `restore()` when settings must match an independently loaded strategy configuration. Structural validation does not establish provenance or prove that the snapshot belongs to a particular instrument. Persist a strategy's cursor, indicator snapshot and financial intents atomically through the existing execution recovery port; do not use this library as a second persistence/accounting authority. ## Derived chart math `bollingerBands` uses population deviation around an unrounded SMA. `macd` composes the explicit EMA seed variant for fast, slow and signal series, returning separate aligned series for MACD, signal and histogram. No timestamp searches are needed. `stochastic` uses SMA smoothing for K/D and defines a flat high/low window as neutral 50, not NaN. These are batch compositions, not new streaming/checkpoint APIs. EMA/RSI/ATR and MACD batch work are linear; population bands and stochastic still scan their trailing windows. Chart adapters now only map source timestamps, select variants and round display values. The display contract is `chart-indicators/v2`: chart RSI no longer reuses the seed's final change, uses exact 100 for gain-only data and neutral 50 for flat data; MACD/Bollinger/ stochastic no longer feed rounded intermediate chart values back into their calculations. Zero/absent cumulative volume emits no VWAP chart point. Invalid inputs fail explicitly. Those chart numbers can change; no saved trading/strategy contract is implicitly changed. ## Existing strategies and native compatibility `mean-reversion/v2` deliberately retains rolling **simple-average** RSI, reverse summation order, flat=100 and its existing incomplete-warm-up fallback. Its arithmetic is extracted to `trailingSimpleRsi`, not replaced with Wilder RSI. Checkpoint versions and serialized strategy state remain unchanged. Experimental ML and the native `TechnicalAnalysis` adapter also retain their previous contracts; neither is silently switched to this core. Native first-seeded EMA, previous-close ATR, first-seeded MACD and compatible mixed-move Wilder RSI paths are checked against the real bindings. Historical native **batch** RSI uses a ratio of 100 for zero losses and then transforms it again, yielding roughly 99.01, while its incremental path uses 100. That difference is pinned/documented, not erased by relabelling a migration. Adopting corrected Wilder RSI in an existing saved/native/ML strategy needs an explicit new strategy/feature contract and deliberate migration. ## Verification - Hand-checked rational EMA/RSI/ATR fixtures are in `test/fixtures/indicators.json`; expected constants are independent of the implementation under test. - Tests cover every JSON restart boundary through warm-up and steady state, reset and detachment, batch/stream equality, prefix invariance (no lookahead), malformed snapshots, invalid inputs, overflow atomicity and bounded state after long histories. - Integration tests cover real native variants, exact mean-reversion-v2 arithmetic, chart offsets/gaps, corrected RSI initialization and display-only rounding. - The browser-bundle check prevents native/server dependency leaks into chart adapters. Calculation lint rules forbid global I/O, wall-clock input and unseeded randomness. Run `bun run test:calculations`, `bun run test:integration`, and `bun run check`.