stock-bot/scripts/test/native-bindings.test.ts

123 lines
4.8 KiB
TypeScript

import { createRequire } from 'node:module';
import { describe, expect, it } from 'bun:test';
import {
BacktestEngine,
FinancialReplaySession,
IncrementalSMA,
TechnicalIndicators,
TradingEngine,
} from '@stock-bot/engine';
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(typeof FinancialReplaySession.prototype.project).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.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}')
).toThrow('TypeScript strategy callbacks are not supported');
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');
});
});