import { describe, expect, test } from 'bun:test'; import { atr, AtrIndicator, ema, EmaIndicator, rsi, RsiIndicator, trailingSimpleRsi, type HlcBar, type IndicatorSeries, } from '@stock-bot/calculations/indicators'; import golden from './fixtures/indicators.json'; function close(actual: readonly number[], expected: readonly number[]) { expect(actual).toHaveLength(expected.length); actual.forEach((value, i) => expect(value).toBeCloseTo(expected[i]!, 11)); } interface Stream { update(input: T): number | null; current(): number | null; reset(): void; snapshot(): unknown; restore(input: unknown): void; } function restarts( inputs: readonly T[], make: () => Stream, recover: (input: unknown) => Stream, batch: (inputs: readonly T[]) => IndicatorSeries ) { const source = structuredClone(inputs); const uninterrupted = make(); const values = inputs.map(input => uninterrupted.update(input)); expect(values.filter(value => value !== null)).toEqual(batch(inputs).values); for (let cut = 0; cut <= inputs.length; cut++) { const before = make(); inputs.slice(0, cut).forEach(input => before.update(input)); const serialized = JSON.stringify(before.snapshot()); const recovered = recover(JSON.parse(serialized)); expect(recovered.current()).toBe(before.current()); expect(JSON.stringify(recovered.snapshot())).toBe(serialized); expect(inputs.slice(cut).map(input => recovered.update(input))).toEqual(values.slice(cut)); const prefix = batch(inputs.slice(0, cut)); expect(batch(inputs).values.slice(0, prefix.values.length)).toEqual(prefix.values); before.reset(); expect(before.current()).toBeNull(); expect(JSON.stringify(before.snapshot())).toBe(JSON.stringify(make().snapshot())); } expect(inputs).toEqual(source); const isolated = make(); const view = isolated.snapshot() as Record; view.count = 123; expect(isolated.snapshot()).toEqual(make().snapshot()); } describe('versioned, aligned indicator formulas', () => { test('EMA seeds and offsets are explicit, without rounded intermediates', () => { const g = golden.ema; const sma = ema(g.prices, g.period); expect(sma.contract).toBe('ema/v1'); expect(sma.startIndex).toBe(2); close(sma.values, g.smaSeed); const first = ema(g.prices, g.period, { seed: 'first' }); expect(first.startIndex).toBe(0); close(first.values, g.firstSeed); expect(ema([1, 2], 3)).toMatchObject({ startIndex: 2, values: [] }); expect(ema([], 3, { seed: 'first' })).toMatchObject({ startIndex: 0, values: [] }); expect(ema([1, 2, 3], 1).values).toEqual([1, 2, 3]); expect(ema([1, 2, 3], 1, { seed: 'first' }).values).toEqual([1, 2, 3]); expect(ema([0.011, 0.019, 0.021], 2).values[0]).toBe(0.015); }); test('Wilder RSI consumes the initialization delta once and handles zero losses/flat data', () => { const g = golden.rsi; const result = rsi(g.prices, g.period); expect(result.contract).toBe('rsi-wilder/v1'); expect(result.startIndex).toBe(g.period); close(result.values, g.values); expect(rsi(g.prices.slice(0, 3), 3).values).toEqual([]); expect(rsi([1, 2, 3, 4, 5], 3).values).toEqual([100, 100]); expect(rsi([5, 4, 3, 2, 1], 3).values).toEqual([0, 0]); for (const flatValue of [0, 50, 100] as const) { expect(rsi([2, 2, 2, 2, 2], 3, { flatValue }).values).toEqual([flatValue, flatValue]); } expect(rsi([2, 2, 2, 2], 3).values).toEqual([50]); expect(rsi([1, 2, 1, 1], 1).values).toEqual([100, 0, 50]); }); test('ATR includes gap ranges and distinguishes both first-bar policies', () => { const g = golden.atr; const previous = atr(g.bars, g.period); expect(previous.contract).toBe('atr-wilder/v1'); expect(previous.startIndex).toBe(3); close(previous.values, g.previousCloseSeed); const included = atr(g.bars, g.period, { firstRange: 'high-low' }); expect(included.startIndex).toBe(2); close(included.values, g.highLowSeed); expect(atr(g.bars.slice(0, 3), 3).values).toEqual([]); expect(atr(g.bars.slice(0, 2), 3, { firstRange: 'high-low' }).values).toEqual([]); expect(atr(g.bars, 1, { firstRange: 'high-low' }).values).toEqual(g.trueRanges); expect(atr(g.bars, 1).values).toEqual(g.trueRanges.slice(1)); expect(atr(Array(5).fill({ high: 0, low: 0, close: 0 }), 2).values).toEqual([0, 0, 0]); }); test('rolling simple RSI preserves the v2 strategy variant, not an alias to Wilder RSI', () => { const g = golden.rsi; expect(trailingSimpleRsi(g.prices, 3)).toBeCloseTo(80); expect(rsi(g.prices, 3).values.at(-1)).toBeCloseTo(79.6875); expect(trailingSimpleRsi([1, 2], 3, 100)).toBeUndefined(); expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100); expect(trailingSimpleRsi([1, 1, 1, 1], 3)).toBe(50); expect(() => trailingSimpleRsi([1, NaN, 3, 4], 3)).toThrow(); }); }); describe('batch/stream/restart and no-lookahead equivalence', () => { const values = Array.from({ length: 38 }, (_, i) => 100 + Math.sin(i / 2) * 8 + i / 10); const bars = values.map(close => ({ high: close + 1, low: close - 2, close })); test('EMA supports every restart boundary for both seeds', () => { for (const seed of ['first', 'sma'] as const) { restarts( values, () => new EmaIndicator(5, { seed }), EmaIndicator.fromSnapshot, values => ema(values, 5, { seed }) ); } }); test('RSI supports every restart boundary and flat policy', () => { for (const flatValue of [0, 50, 100] as const) { restarts( values, () => new RsiIndicator(5, { flatValue }), RsiIndicator.fromSnapshot, values => rsi(values, 5, { flatValue }) ); } }); test('ATR supports every restart boundary and first-range policy', () => { for (const firstRange of ['previous-close', 'high-low'] as const) { restarts( bars, () => new AtrIndicator(5, { firstRange }), AtrIndicator.fromSnapshot, bars => atr(bars, 5, { firstRange }) ); } }); }); describe('indicator state/input rejection is atomic', () => { test('bad periods, options, sparse arrays and non-finite observations fail before producing data', () => { for (const size of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER]) { expect(() => new EmaIndicator(size)).toThrow(); expect(() => new RsiIndicator(size)).toThrow(); expect(() => new AtrIndicator(size)).toThrow(); } expect(() => ema([1], 2, { seed: 'other' } as never)).toThrow(); expect(() => rsi([1], 2, { flatValue: 12 } as never)).toThrow(); expect(() => rsi([1], 2, { smoothing: 'simple' } as never)).toThrow(); expect(() => atr([], 2, { firstRange: 'other' } as never)).toThrow(); expect(() => ema(Array(5), 2)).toThrow(); expect(() => rsi(Array(5), 2)).toThrow(); expect(() => atr(Array(5), 2)).toThrow(); for (const stream of [new EmaIndicator(2), new RsiIndicator(2)]) { stream.update(1); const before = stream.snapshot(); for (const invalid of [NaN, Infinity, -Infinity, '2', undefined, null]) { expect(() => stream.update(invalid as number)).toThrow(); expect(stream.snapshot()).toEqual(before); } } const range = new AtrIndicator(2); range.update({ high: 2, low: 0, close: 1 }); for (const bad of [ { high: 0, low: 2, close: 1 }, { high: 2, low: 0, close: 3 }, { high: Infinity, low: 0, close: 1 }, ]) { const before = range.snapshot(); expect(() => range.update(bad)).toThrow(); expect(range.snapshot()).toEqual(before); } }); test('arithmetic failures cannot poison an otherwise resumable stream', () => { const emaStream = new EmaIndicator(3); emaStream.update(Number.MAX_VALUE); const beforeEma = emaStream.snapshot(); expect(() => emaStream.update(Number.MAX_VALUE)).toThrow(); expect(emaStream.snapshot()).toEqual(beforeEma); const rsiStream = new RsiIndicator(3); rsiStream.update(-Number.MAX_VALUE); const beforeRsi = rsiStream.snapshot(); expect(() => rsiStream.update(Number.MAX_VALUE)).toThrow(); expect(rsiStream.snapshot()).toEqual(beforeRsi); const atrStream = new AtrIndicator(3); const beforeAtr = atrStream.snapshot(); expect(() => atrStream.update({ high: Number.MAX_VALUE, low: -Number.MAX_VALUE, close: 0 }) ).toThrow(); expect(atrStream.snapshot()).toEqual(beforeAtr); }); test('snapshot schemas reject incompatible versions, mismatched configurations and inconsistent phases', () => { const streams: Array | Stream> = [ new EmaIndicator(3), new RsiIndicator(3), new AtrIndicator(3), ]; for (const stream of streams) { const original = stream.snapshot() as Record; for (const bad of [ null, [], {}, { ...original, contract: 'future/v99' }, { ...original, count: -1 }, { ...original, count: 0.5 }, { ...original, count: Infinity }, { ...original, period: 4 }, { ...original, unexpected: 1 }, ]) { expect(() => stream.restore(bad)).toThrow(); expect(stream.snapshot()).toEqual(original); } } const e = new EmaIndicator(3); expect(() => e.restore({ ...e.snapshot(), count: 1, value: 1 })).toThrow(); expect(() => e.restore({ ...e.snapshot(), seedSum: 1 })).toThrow(); expect(() => e.restore({ ...e.snapshot(), count: 3 })).toThrow(); expect(() => e.restore({ ...e.snapshot(), seed: 'first' })).toThrow(); const r = new RsiIndicator(3); expect(() => r.restore({ ...r.snapshot(), count: 1 })).toThrow(); expect(() => r.restore({ ...r.snapshot(), previous: 1 })).toThrow(); expect(() => r.restore({ ...r.snapshot(), gain: -1 })).toThrow(); expect(() => r.restore({ ...r.snapshot(), count: 1, previous: 1, gain: 1 })).toThrow(); expect(() => r.restore({ ...r.snapshot(), flatValue: 100 })).toThrow(); const a = new AtrIndicator(3); expect(() => a.restore({ ...a.snapshot(), seedSum: -1 })).toThrow(); expect(() => a.restore({ ...a.snapshot(), count: 1, value: 1 })).toThrow(); expect(() => a.restore({ ...a.snapshot(), previousClose: 1 })).toThrow(); expect(() => a.restore({ ...a.snapshot(), firstRange: 'high-low' })).toThrow(); }); test('long histories keep bounded JSON state and count overflow is rejected atomically', () => { const streams = [new EmaIndicator(5), new RsiIndicator(5)]; const range = new AtrIndicator(5); for (let i = 0; i < 10000; i++) { streams.forEach(stream => stream.update(10 + Math.sin(i))); range.update({ high: 12, low: 8, close: 10 }); } const cases = [ ...streams.map(stream => ({ stream, next: () => stream.update(10) })), { stream: range, next: () => range.update({ high: 12, low: 8, close: 10 }) }, ]; for (const { stream, next } of cases) { expect(JSON.stringify(stream.snapshot()).length).toBeLessThan(300); const state = { ...stream.snapshot(), count: Number.MAX_SAFE_INTEGER }; stream.restore(state); expect(next).toThrow(); expect(stream.snapshot()).toEqual(state); } }); });