50 lines
2 KiB
TypeScript
50 lines
2 KiB
TypeScript
import { expect, test } from 'bun:test';
|
|
import { BacktestEngine } from '@stock-bot/engine';
|
|
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
|
|
|
test('native terminal liquidation reports both commissions in final equity', () => {
|
|
const start = Date.parse('2024-01-01T00:00:00Z');
|
|
const end = start + 3 * 86_400_000;
|
|
const engine = new BacktestEngine({
|
|
name: 'Terminal fee regression',
|
|
symbols: ['A.US'],
|
|
startDate: new Date(start).toISOString(),
|
|
endDate: new Date(end).toISOString(),
|
|
initialCapital: 10,
|
|
commission: 0.01,
|
|
slippage: 0,
|
|
dataFrequency: '1d',
|
|
});
|
|
engine.addNativeStrategy('sma_crossover', 'fixed-share SMA', 'terminal-fixture', {
|
|
fastPeriod: 1,
|
|
slowPeriod: 2,
|
|
quantity: 1,
|
|
});
|
|
// The crossover buys exactly one share at 4 on day 3. Day 4 leaves it open
|
|
// for terminal liquidation, also at 4; no production sizing is inferred.
|
|
engine.loadMarketData(
|
|
[4, 3, 4, 4].map((price, index) => ({
|
|
symbol: 'A.US',
|
|
timestamp: start + index * 86_400_000,
|
|
type: 'bar',
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 1_000,
|
|
vwap: price,
|
|
}))
|
|
);
|
|
|
|
const result = nativeResultSchema.parse(JSON.parse(engine.run()));
|
|
expect(result.trades).toHaveLength(2);
|
|
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 1, price: 4 });
|
|
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 1, price: 4 });
|
|
expect(Date.parse(result.trades[1]!.timestamp)).toBe(end);
|
|
expect(result.trades.reduce((sum, fill) => sum + fill.commission, 0)).toBeCloseTo(0.08, 10);
|
|
expect(result.metrics.finalValue).toBeCloseTo(9.92, 10);
|
|
expect(result.equity.at(-1)!.value).toBeCloseTo(9.92, 10);
|
|
expect(result.positions.every(position => position.quantity === 0)).toBe(true);
|
|
expect(result.equity.filter(point => Date.parse(point.date) === end)).toHaveLength(1);
|
|
expect(new Set(result.equity.map(point => point.date)).size).toBe(result.equity.length);
|
|
});
|