Unify simulation order execution and persist paper accounting
This commit is contained in:
parent
7dec0be3b4
commit
63c3856797
37 changed files with 3901 additions and 3043 deletions
|
|
@ -1,8 +1,64 @@
|
|||
import { createRequire } from 'node:module';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { BacktestEngine, IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine';
|
||||
import {
|
||||
BacktestEngine,
|
||||
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);
|
||||
|
|
@ -20,7 +76,9 @@ describe('generated native bindings', () => {
|
|||
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[];
|
||||
macd: number[];
|
||||
signal: number[];
|
||||
histogram: number[];
|
||||
};
|
||||
const fast = indicators.calculateEma(prices, 12);
|
||||
const slow = indicators.calculateEma(prices, 26);
|
||||
|
|
@ -33,9 +91,30 @@ describe('generated native bindings', () => {
|
|||
});
|
||||
|
||||
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');
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue