import { createRequire } from 'node:module'; import { describe, expect, it } from 'bun:test'; import { BacktestEngine, FinancialReplaySession, IncrementalSMA, stageFinancialTransaction, TechnicalIndicators, TradingEngine, } from '@stock-bot/engine'; import { parseFinancialDecimal } from '@stock-bot/types'; import { financialTransactionRequestSchema, parseFinancialTransactionResult, } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; import nativeReplayLoad from '../../test/fixtures/native-replay-load.json'; describe('generated native bindings', () => { it('fill P&L is an incremental delta and native FIFO commissions are allocated once', () => { const start = Date.parse('2024-01-01T00:00:00Z'); const engine = new TradingEngine('backtest', { startTime: start, endTime: start + 86400000, speedMultiplier: 0, initialCapital: 10000, }); for (const [side, price, quantity, commission] of [ ['buy', 100, 10, 1], ['sell', 110, 4, 0.4], ['sell', 90, 10, 1], ['buy', 80, 4, 0.4], ] as const) { engine.processFillWithMetadata('A', price, quantity, side, commission, 'order', 'strategy'); } expect(engine.getTotalPnl()[0]).toBeCloseTo(17.2, 8); expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(17.2, 8); const trades = JSON.parse(engine.getClosedTrades()) as { commission: number; pnl: number }[]; expect(trades.reduce((n, t) => n + t.commission, 0)).toBeCloseTo(2.8, 8); expect(trades.reduce((n, t) => n + t.pnl, 0)).toBeCloseTo(17.2, 8); engine.processFill('A', 100, 1, 'buy', 0.1); expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(17.1, 8); engine.advanceTime(start + 86400000); engine.processFill('A', 100, 1, 'sell', 0.1); expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(-0.1, 8); }); it('native risk checks use configured projected notionals and reject invalid fills', () => { const start = Date.parse('2024-01-01T00:00:00Z'); const engine = new TradingEngine('backtest', { startTime: start, endTime: start + 86400000, speedMultiplier: 0, initialCapital: 10000, }); engine.updateRiskLimits({ maxOrderSize: 100, maxPositionSize: 100, maxDailyLoss: 100, maxGrossExposure: 1000, maxSymbolExposure: 800, }); engine.updateQuote('A', 100, 100, 100, 100); const result = JSON.parse( engine.checkRisk({ id: 'id', symbol: 'A', side: 'buy', quantity: 9, orderType: 'market' }) ); expect(result.passed).toBe(false); expect(result.checks.symbol_exposure).toBe(false); expect(() => engine.processFill('A', NaN, 1, 'buy', 0)).toThrow('Invalid fill'); }); it('ESM loads the generated artifact and exposes the documented constructor aliases', () => { const sma = new IncrementalSMA(2); sma.update(10); expect(sma.update(12)).toBe(11); expect(new TechnicalIndicators().calculateSma([1, 2, 3], 2)).toEqual([1.5, 2.5]); }); it('CommonJS exposes the same native constructors', () => { const binding = createRequire(import.meta.url)('@stock-bot/engine'); expect(binding.TechnicalIndicators).toBe(TechnicalIndicators); expect(binding.IncrementalSMA).toBe(IncrementalSMA); expect(binding.FinancialReplaySession).toBe(FinancialReplaySession); expect(binding.stageFinancialTransaction).toBe(stageFinancialTransaction); expect(typeof FinancialReplaySession.prototype.project).toBe('function'); expect(typeof FinancialReplaySession.prototype.report).toBe('function'); }); it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => { const indicators = new TechnicalIndicators(); const prices = Array.from({ length: 80 }, (_, index) => 100 + index); const result = JSON.parse(indicators.calculateMacd(prices, 12, 26, 9)) as { macd: number[]; signal: number[]; histogram: number[]; }; const fast = indicators.calculateEma(prices, 12); const slow = indicators.calculateEma(prices, 26); expect(result.macd).toHaveLength(prices.length); expect(result.signal).toHaveLength(prices.length); for (let index = 0; index < prices.length; index++) { expect(result.macd[index]).toBeCloseTo(fast[index]! - slow[index]!, 10); expect(result.histogram[index]).toBeCloseTo(result.macd[index]! - result.signal[index]!, 10); } }); it('invalid SMA periods throw before entering the native event loop', () => { const engine = new BacktestEngine({ name: 'validation', symbols: ['TEST'], startDate: '2023-01-01T00:00:00Z', endDate: '2023-02-01T00:00:00Z', initialCapital: 100000, commission: 0, slippage: 0, dataFrequency: '1d', }); expect(engine).not.toHaveProperty('addTypescriptStrategy'); expect(engine).not.toHaveProperty('addTypescriptStrategy'); expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 0, slowPeriod: 20, }) ).toThrow('SMA periods must satisfy'); expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 20, slowPeriod: 10, }) ).toThrow('SMA periods must satisfy'); }); }); describe('stateless native financial transaction contract', () => { const config = nativeReplayLoad.config.matching; const identity = { sessionId: config.risk.ledger.sessionId, accountId: config.risk.ledger.accountId, }; function initialized() { const request = financialTransactionRequestSchema.parse({ version: 1, kind: 'initialize', identity, config, }); return parseFinancialTransactionResult( stageFinancialTransaction(JSON.stringify(request)), identity ); } function marked() { const init = initialized(); const at = config.risk.ledger.riskSession.startsAt; const command = { commandId: 'mark', key: { at, phase: 'Observation', instrumentId: 'X0.US', sourceSequence: 0 }, body: { kind: 'mark', seriesId: 'X0.US:1m', price: '10', observedAt: at }, }; const request = financialTransactionRequestSchema.parse({ version: 1, kind: 'apply', identity, checkpoint: init.checkpoint, command, }); if (request.kind !== 'apply') { throw new Error('Expected an apply request in the mark fixture'); } const raw = stageFinancialTransaction(JSON.stringify(request)); return { init, request, raw, result: parseFinancialTransactionResult(raw, identity) }; } it('initializes and applies with strict parsed views, checkpoint and exact journal effects', () => { const { init, result } = marked(); expect(init.outcome).toBeNull(); expect(init.view.equity).toBe(parseFinancialDecimal('10000.00000000')); expect(result.checkpoint.revision).toBe(1); expect(result.journal).toHaveLength(1); expect(result.journal[0]!.viewAfter.admissionRevision).toBe(0); expect(result.view.admissionRevision).toBe(1); expect(result.view.portfolio.cash).toBe(init.view.portfolio.cash); }); it('returns no journal for an old replay after a later mark', () => { const { request, result } = marked(); const later = { ...request.command, commandId: 'later', key: { ...request.command.key, at: request.command.key.at + 1 }, body: { kind: 'mark', seriesId: 'X0.US:1m', price: '11', observedAt: request.command.key.at + 1, }, }; const advanced = parseFinancialTransactionResult( stageFinancialTransaction( JSON.stringify({ ...request, checkpoint: result.checkpoint, command: later }) ), identity ); const replay = parseFinancialTransactionResult( stageFinancialTransaction(JSON.stringify({ ...request, checkpoint: advanced.checkpoint })), identity ); expect(replay.journal).toEqual([]); expect(replay.view).toEqual(advanced.view); expect(replay.outcome!.revision).toBe(1); expect(replay.checkpoint.revision).toBe(2); expect(replay.checkpoint).toEqual(advanced.checkpoint); }); it('rejects missing fields, wrong identity/revision and altered effect journals', () => { const { raw } = marked(); const mutations: Array<(value: any) => void> = [ value => { delete value.journal[0].effect.Risk.command; }, value => { delete value.journal[0].effect.Risk.outcome.financial.effects; }, value => { value.identity.accountId = 'wrong'; }, value => { value.view.admissionRevision = 0; }, value => { value.journal[0].viewAfter.admissionRevision = 1; }, value => { value.journal[0].index = 2; }, value => { value.journal[0].effect.Risk.outcome.disposition = { Rejected: 'Invented' }; }, value => { value.journal[0].effect.Risk.command.commandId = 'different'; }, ]; for (const mutate of mutations) { const bad = JSON.parse(raw); mutate(bad); expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow(); } const reordered = JSON.parse(raw); const command = reordered.journal[0].effect.Risk.command; reordered.journal[0].effect.Risk.command = Object.fromEntries( Object.entries(command).reverse() ); expect(() => parseFinancialTransactionResult(JSON.stringify(reordered), identity) ).not.toThrow(); }); it('rejects nested unknown, missing and null configuration fields through both native hosts', () => { const mutations: Array<(value: any) => void> = [ value => { value.risk.ledger.riskSession.extra = true; }, value => { delete value.risk.ledger.riskSession.calendarRevision; }, value => { value.risk.ledger.riskSession.calendarRevision = null; }, value => { value.owners[0].extra = true; }, value => { delete value.owners[0].mode; }, value => { value.owners[0].mode = null; }, ]; for (const mutate of mutations) { const bad = structuredClone(config); mutate(bad); expect(() => stageFinancialTransaction( JSON.stringify({ version: 1, kind: 'initialize', identity, config: bad, }) ) ).toThrow(); expect( () => new FinancialReplaySession( JSON.stringify({ ...nativeReplayLoad, config: { ...nativeReplayLoad.config, matching: bad }, }) ) ).toThrow(); } }); it('requires explicit null checkpoint fields and rejects nested receipt additions', () => { const { request, result } = marked(); // The untouched initialized checkpoint has a required null cursor. expect(request.checkpoint.cursor).toBeNull(); expect(() => stageFinancialTransaction(JSON.stringify(request))).not.toThrow(); const omitted = structuredClone(request) as any; delete omitted.checkpoint.cursor; expect(() => stageFinancialTransaction(JSON.stringify(omitted))).toThrow( 'missing financial transaction fields' ); const retry = { ...request, checkpoint: result.checkpoint }; expect(retry.checkpoint.receipts[0]).toMatchObject({ outcome: { effects: [{ Risk: { outcome: { remaining: null } } }] }, }); const mutations: Array<(value: any) => void> = [ value => { value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.extra = true; }, value => { delete value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.remaining; }, value => { value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.disposition = null; }, ]; for (const mutate of mutations) { const bad = structuredClone(retry); mutate(bad); expect(() => stageFinancialTransaction(JSON.stringify(bad))).toThrow(); } const replay = parseFinancialTransactionResult( stageFinancialTransaction(JSON.stringify(retry)), identity ); expect(replay.view).toEqual(result.view); expect(replay.checkpoint).toEqual(result.checkpoint); expect(replay.journal).toEqual([]); }); it('validates initialized metadata and rejects operator/legacy/malformed native requests', () => { const result = initialized(); const bad = structuredClone(result); bad.checkpoint.cursor = { at: 1, phase: 'Observation', instrumentId: 'X0.US', sourceSequence: 0, }; expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow( 'initialized' ); expect(() => stageFinancialTransaction( JSON.stringify({ version: 1, kind: 'apply', identity, checkpoint: { cash: 1000 }, command: {}, }) ) ).toThrow(); expect(() => stageFinancialTransaction(JSON.stringify({ version: 1, kind: 'reset', identity })) ).toThrow(); expect(() => stageFinancialTransaction( JSON.stringify({ version: 1, kind: 'initialize', identity: { ...identity, accountId: 'other' }, config, }) ) ).toThrow('identity'); const request = { version: 1, kind: 'initialize', identity, config: { ...config, unexpected: true }, }; expect(() => stageFinancialTransaction(JSON.stringify(request))).toThrow(); }); });