41 lines
2.3 KiB
TypeScript
41 lines
2.3 KiB
TypeScript
import { createRequire } from 'node:module';
|
|
import { describe, expect, it } from 'bun:test';
|
|
import { BacktestEngine, IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine';
|
|
|
|
describe('generated native bindings', () => {
|
|
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);
|
|
});
|
|
|
|
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');
|
|
});
|
|
});
|