400 lines
17 KiB
TypeScript
400 lines
17 KiB
TypeScript
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import {
|
|
IncrementalSMA,
|
|
BacktestEngine as NativeEngine,
|
|
TechnicalIndicators,
|
|
} from '@stock-bot/engine';
|
|
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
|
import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies';
|
|
import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan';
|
|
import {
|
|
nativeMeanReversionParameters,
|
|
nativeMomentumParameters,
|
|
nativePairsParameters,
|
|
nativeSmaParameters,
|
|
typescriptMeanReversionParameters,
|
|
typescriptSmaParameters,
|
|
} from '../../apps/stock/orchestrator/src/contracts/strategies';
|
|
import {
|
|
builtinStrategy,
|
|
normalizeStrategyName,
|
|
} from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
|
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
|
import {
|
|
movingAverageCrossover,
|
|
trailingMean,
|
|
trailingPopulationDeviation,
|
|
} from '../../apps/stock/orchestrator/src/indicators/window-statistics';
|
|
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
|
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
|
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
|
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
|
import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
|
import { config, logger, makeExecution, start } from '../fixtures/execution';
|
|
|
|
const cleanup: (() => Promise<void>)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanup.splice(0).reverse()) await close();
|
|
});
|
|
const definition: StrategyConfig = {
|
|
id: 'sma',
|
|
name: 'sma-crossover',
|
|
enabled: true,
|
|
parameters: {},
|
|
symbols: ['A.US'],
|
|
allocation: 1,
|
|
};
|
|
function nativeEngine() {
|
|
return new NativeEngine({
|
|
name: 'contracts',
|
|
symbols: ['A.US'],
|
|
startDate: config.startDate,
|
|
endDate: config.endDate,
|
|
initialCapital: 10000,
|
|
commission: 0,
|
|
slippage: 0,
|
|
dataFrequency: '1d',
|
|
});
|
|
}
|
|
const bar = (close: number, index: number, symbol = 'A.US') => ({
|
|
type: 'bar' as const,
|
|
eventId: symbol + ':' + index,
|
|
data: {
|
|
symbol,
|
|
close,
|
|
open: close,
|
|
high: close + 0.1,
|
|
low: close - 0.1,
|
|
volume: 1000,
|
|
timestamp: start + index * 86400000,
|
|
},
|
|
});
|
|
async function runtime(parameters: Record<string, unknown> = {}, name = definition.name) {
|
|
const f = makeExecution();
|
|
await f.execution.initialize({ ...config, commission: 0 }, f.engine);
|
|
cleanup.push(() => f.execution.shutdown());
|
|
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
|
const manager = new StrategyManager({
|
|
logger,
|
|
custom: { ExecutionService: f.execution, ModeManager: mode },
|
|
});
|
|
cleanup.push(() => manager.shutdown());
|
|
await manager.initializeStrategies([{ ...definition, name, parameters }]);
|
|
return { ...f, manager, mode, strategy: manager.getStrategy('sma')! };
|
|
}
|
|
|
|
describe('explicit strategy contracts and shared planning', () => {
|
|
test('aliases have one canonical identity across registries and native planning', () => {
|
|
for (const name of [
|
|
'SMA',
|
|
' sma-crossover ',
|
|
'sma_crossover',
|
|
'Simple Moving Average Crossover',
|
|
'moving-average',
|
|
]) {
|
|
expect(builtinStrategy(name)).toBe('sma_crossover');
|
|
expect(resolveNativeStrategies({ ...config, strategy: name })[0]?.strategy).toBe(
|
|
'sma_crossover'
|
|
);
|
|
}
|
|
expect(normalizeStrategyName(' Mean-Reversion ')).toBe('meanreversion');
|
|
expect(builtinStrategy('unknown')).toBeUndefined();
|
|
});
|
|
|
|
test('both backends use the same shared-default then per-strategy override rule', () => {
|
|
const request = {
|
|
...config,
|
|
config: { fastPeriod: 2, slowPeriod: 9, commission: 0, slippage: 0 },
|
|
strategies: [
|
|
{ name: 'sma', enabled: true, config: { slowPeriod: 5 } },
|
|
{ name: 'not-installed', enabled: false, config: {} },
|
|
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 3 } },
|
|
],
|
|
};
|
|
const before = structuredClone(request);
|
|
for (const backend of ['typescript', 'native'] as const) {
|
|
const plan = backtestStrategies(request, backend);
|
|
expect(plan.map(entry => [entry.parameters.fastPeriod, entry.parameters.slowPeriod])).toEqual(
|
|
[
|
|
[2, 5],
|
|
[3, 9],
|
|
]
|
|
);
|
|
expect(plan.every(entry => !('commission' in entry.parameters))).toBe(true);
|
|
}
|
|
expect(request).toEqual(before);
|
|
const custom = backtestStrategies(
|
|
{ ...config, strategy: 'custom-extension', config: { vendorOption: 42 } },
|
|
'typescript'
|
|
);
|
|
expect(custom[0]?.parameters).toMatchObject({
|
|
vendorOption: 42,
|
|
initialCapital: config.initialCapital,
|
|
});
|
|
});
|
|
|
|
test('periods and units have explicit defaults and fail rather than coerce or truncate', () => {
|
|
expect(typescriptSmaParameters.parse({})).toMatchObject({
|
|
fastPeriod: 5,
|
|
slowPeriod: 15,
|
|
positionFraction: 0.1,
|
|
minHoldingBars: 3,
|
|
});
|
|
expect(nativeSmaParameters.parse({})).toEqual({ fastPeriod: 5, slowPeriod: 15, quantity: 100 });
|
|
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
|
expect(nativeSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
|
expect(typescriptSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
|
}
|
|
expect(typescriptSmaParameters.safeParse({ fastPeriod: 20, slowPeriod: 5 }).success).toBe(
|
|
false
|
|
);
|
|
for (const bad of [0, -1, Infinity, 1e10]) {
|
|
expect(nativeSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
|
expect(typescriptSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
|
}
|
|
expect(typescriptSmaParameters.safeParse({ positionFraction: 2 }).success).toBe(false);
|
|
expect(typescriptSmaParameters.safeParse({ positionSize: 100 }).success).toBe(false);
|
|
expect(typescriptSmaParameters.safeParse({ fastPreriod: 3 }).success).toBe(false);
|
|
expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false);
|
|
});
|
|
|
|
test('mean reversion and native-only strategies validate their actual, different contracts', () => {
|
|
const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 });
|
|
expect(mean.trendPeriod).toBe(80);
|
|
expect(mean.entryThreshold).toBe(2);
|
|
expect(typescriptMeanReversionParameters.safeParse({ exitZScore: 3 }).success).toBe(false);
|
|
expect(
|
|
typescriptMeanReversionParameters.safeParse({ rsiOversold: 80, rsiOverbought: 20 }).success
|
|
).toBe(false);
|
|
expect(
|
|
typescriptMeanReversionParameters.safeParse({ lookbackPeriod: 30, trendPeriod: 20 }).success
|
|
).toBe(false);
|
|
expect(nativeMeanReversionParameters.safeParse({ exitZScore: 0.5 }).success).toBe(false);
|
|
expect(nativeMeanReversionParameters.safeParse({ lookbackPeriod: 0 }).success).toBe(false);
|
|
expect(nativeMomentumParameters.safeParse({ momentumThreshold: NaN }).success).toBe(false);
|
|
expect(nativePairsParameters.safeParse({ pairA: 'A.US', pairB: 'A.US' }).success).toBe(false);
|
|
expect(() =>
|
|
backtestStrategies(
|
|
{ ...config, strategy: 'pairs', config: { pairA: 'A.US', pairB: 'C.US' } },
|
|
'native'
|
|
)
|
|
).toThrow('included in backtest symbols');
|
|
});
|
|
|
|
test('invalid native plans fail before loading input and unsupported execution flags are explicit', () => {
|
|
expect(() => backtestStrategies({ ...config, strategies: [] }, 'native')).toThrow('No enabled');
|
|
expect(() => backtestStrategies({ ...config, strategies: [] }, 'typescript')).toThrow(
|
|
'No enabled'
|
|
);
|
|
expect(() =>
|
|
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: true } })
|
|
).toThrow('does not execute TypeScript');
|
|
expect(() =>
|
|
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: 'false' } })
|
|
).toThrow();
|
|
expect(
|
|
backtestStrategies({ ...config, config: { useTypeScriptImplementation: true } }, 'typescript')
|
|
).toHaveLength(1);
|
|
});
|
|
|
|
test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
|
|
const f = await runtime();
|
|
const storage = new StorageService({ logger }, null, null, null);
|
|
const backend = new BacktestEngine(
|
|
{ logger, custom: { ExecutionService: f.execution } },
|
|
storage,
|
|
f.manager
|
|
);
|
|
cleanup.push(() => backend.shutdown());
|
|
let reads = 0;
|
|
await expect(
|
|
backend.runBacktest({ ...config, config: { fastPeriod: 5, slowPeriod: 2 } }, async () => {
|
|
reads++;
|
|
throw new Error('Must not load data');
|
|
})
|
|
).rejects.toThrow('SMA periods must satisfy');
|
|
expect(reads).toBe(0);
|
|
});
|
|
|
|
test('definitions are detached and rejected inactive edits leave effective settings intact', async () => {
|
|
const f = await runtime();
|
|
const input = { ...definition, parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 7 } };
|
|
const strategy = new SmaCrossoverStrategy(input, f.mode, f.execution);
|
|
input.parameters.fastPeriod = 0;
|
|
const view = strategy.getConfig();
|
|
view.parameters.slowPeriod = 0;
|
|
expect(strategy.getConfig().parameters).toMatchObject({
|
|
fastPeriod: 2,
|
|
slowPeriod: 3,
|
|
quantity: 7,
|
|
});
|
|
await expect(
|
|
strategy.updateConfig({ parameters: { fastPeriod: 9, slowPeriod: 3 } })
|
|
).rejects.toThrow('SMA periods');
|
|
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 2, slowPeriod: 3 });
|
|
await strategy.updateConfig({ parameters: { fastPeriod: 3, slowPeriod: 8 } });
|
|
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 8 });
|
|
});
|
|
});
|
|
|
|
describe('shared trailing-window math and native parity', () => {
|
|
test('warm-up never manufactures zero averages or first-window crossovers', () => {
|
|
expect(trailingMean([3, 2], 3)).toBeUndefined();
|
|
expect(movingAverageCrossover([3, 2, 1], 2, 3)).toBeUndefined();
|
|
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)).toMatchObject({
|
|
goldenCross: true,
|
|
deathCross: false,
|
|
});
|
|
expect(movingAverageCrossover([1, 2, 3, 1], 2, 3)).toMatchObject({
|
|
goldenCross: false,
|
|
deathCross: false,
|
|
});
|
|
expect(movingAverageCrossover([1, 2, 3, 0.5], 2, 3)).toMatchObject({
|
|
goldenCross: false,
|
|
deathCross: true,
|
|
});
|
|
expect(trailingPopulationDeviation([10, 10, 10], 3)).toBe(0);
|
|
for (const period of [0, -1, 1.5, Infinity])
|
|
expect(() => trailingMean([1, 2, 3], period)).toThrow();
|
|
expect(() => trailingMean([1, NaN, 3], 3)).toThrow('finite');
|
|
expect(() => trailingMean([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('overflow');
|
|
});
|
|
|
|
test('scalar SMA and population deviation match native batch and incremental indicators', () => {
|
|
const native = new TechnicalIndicators();
|
|
const prices = Array.from(
|
|
{ length: 130 },
|
|
(_, index) => 100 + Math.sin(index / 3) * 8 + index / 100
|
|
);
|
|
for (const period of [2, 5, 15, 80]) {
|
|
const rolling = new IncrementalSMA(period);
|
|
const series = native.calculateSma(prices, period);
|
|
const bands = JSON.parse(native.calculateBollingerBands(prices, period, 2));
|
|
for (let index = 0; index < prices.length; index++) {
|
|
const value = rolling.update(prices[index]!);
|
|
const scalar = trailingMean(prices.slice(0, index + 1), period);
|
|
if (scalar === undefined) {
|
|
expect(value == null).toBe(true);
|
|
continue;
|
|
}
|
|
expect(value!).toBeCloseTo(scalar, 9);
|
|
expect(series[index + 1 - period]!).toBeCloseTo(scalar, 9);
|
|
const deviation = trailingPopulationDeviation(prices.slice(0, index + 1), period)!;
|
|
expect(
|
|
(bands.upper[index + 1 - period] - bands.middle[index + 1 - period]) / 2
|
|
).toBeCloseTo(deviation, 8);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('configured SMA periods and explicit shares reach real fills in both backends', async () => {
|
|
const f = await runtime({ fastPeriod: 2, slowPeriod: 3, quantity: 7, minHoldingBars: 0 });
|
|
const prices = [3, 2, 1, 4];
|
|
for (let i = 0; i < 3; i++) await f.manager.onMarketData(bar(prices[i]!, i));
|
|
expect((await f.execution.getAccount()).positions['A.US']).toBeUndefined();
|
|
await f.manager.onMarketData(bar(prices[3]!, 3));
|
|
expect((await f.execution.getAccount()).positions['A.US']?.quantity).toBe(7);
|
|
const native = nativeEngine();
|
|
native.addNativeStrategy('sma_crossover', 'sma', 'id', {
|
|
fastPeriod: 2,
|
|
slowPeriod: 3,
|
|
quantity: 7,
|
|
});
|
|
native.loadMarketData(
|
|
prices.map((price, i) => ({ ...bar(price, i).data, type: 'bar', vwap: price }))
|
|
);
|
|
const result = JSON.parse(native.run());
|
|
// Native backtests liquidate at the end; that exit is not a second strategy entry.
|
|
expect(result.trades).toHaveLength(2);
|
|
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 7, symbol: 'A.US' });
|
|
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 7, symbol: 'A.US' });
|
|
expect(() => native.addNativeStrategy('sma_crossover', 'late', 'late', {})).toThrow('consumed');
|
|
});
|
|
|
|
test('configured long windows remain checkpointable and preserve state through replacement', async () => {
|
|
const settings = { fastPeriod: 5, slowPeriod: 80, quantity: 1 };
|
|
const f = await runtime(settings);
|
|
for (let i = 0; i < 90; i++) await f.manager.onMarketData(bar(100 + Math.sin(i / 3), i));
|
|
const state = f.strategy.captureCheckpoint();
|
|
const replacement = new SmaCrossoverStrategy(f.strategy.getConfig(), f.mode, f.execution);
|
|
replacement.restoreCheckpoint(state);
|
|
expect(replacement.captureCheckpoint()).toEqual(state);
|
|
expect(replacement.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
|
const mean = await runtime({ lookbackPeriod: 80 }, 'mean-reversion');
|
|
const prices = Array.from({ length: 90 }, (_, i) => 100 + Math.sin(i / 3));
|
|
for (let i = 0; i < prices.length; i++) {
|
|
await mean.manager.onMarketData(bar(prices[i]!, i));
|
|
}
|
|
const meanState = mean.strategy.captureCheckpoint();
|
|
expect(meanState).toMatchObject({
|
|
indicators: {
|
|
priceHistory: [['A.US', prices]],
|
|
indicators: [
|
|
[
|
|
'A.US',
|
|
{
|
|
mean: trailingMean(prices, 80),
|
|
trendMean: trailingMean(prices, 80),
|
|
stdDev: trailingPopulationDeviation(prices, 80),
|
|
},
|
|
],
|
|
],
|
|
},
|
|
});
|
|
const restoredMean = new MeanReversionStrategy(
|
|
mean.strategy.getConfig(),
|
|
mean.mode,
|
|
mean.execution
|
|
);
|
|
restoredMean.restoreCheckpoint(meanState);
|
|
expect(restoredMean.captureCheckpoint()).toEqual(meanState);
|
|
expect(restoredMean.getConfig().parameters.trendPeriod).toBe(80);
|
|
});
|
|
|
|
test('v2 cannot silently reset a legacy paper definition; explicit new IDs preserve old registration', async () => {
|
|
const f = makeExecution();
|
|
await f.execution.initialize(config, f.engine);
|
|
cleanup.push(() => f.execution.shutdown());
|
|
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
|
const legacy = new SmaCrossoverStrategy(definition, mode, f.execution);
|
|
legacy.getCheckpointVersion = () => 'sma-crossover-fixed/v1';
|
|
await f.execution.registerStrategy(legacy);
|
|
const before = await f.execution.getRecoveryStatus();
|
|
const upgraded = new SmaCrossoverStrategy(definition, mode, f.execution);
|
|
await expect(f.execution.registerStrategy(upgraded)).rejects.toThrow('version changed');
|
|
expect(await f.execution.getRecoveryStatus()).toEqual(before);
|
|
await f.execution.pauseStrategy('sma');
|
|
const fresh = new SmaCrossoverStrategy({ ...definition, id: 'sma-v2' }, mode, f.execution);
|
|
await f.execution.registerStrategy(fresh);
|
|
expect((await f.execution.getRecoveryStatus()).strategies).toMatchObject([
|
|
{ strategyId: 'sma', enabled: false, version: 'sma-crossover-fixed/v1' },
|
|
{ strategyId: 'sma-v2', enabled: true, version: 'sma-crossover-fixed/v2' },
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('native parameter trust boundary', () => {
|
|
test('native bindings reject invalid numeric types, fractions, infinities and unknown keys independently', () => {
|
|
const engine = nativeEngine();
|
|
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
|
expect(() =>
|
|
engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: bad })
|
|
).toThrow('SMA periods');
|
|
}
|
|
for (const [name, parameters] of [
|
|
['sma_crossover', { fastPreriod: 3 }],
|
|
['sma_crossover', { quantity: -1 }],
|
|
['mean_reversion', { lookbackPeriod: 0 }],
|
|
['mean_reversion', { lookbackPeriod: 1.5 }],
|
|
['mean_reversion', { entryThreshold: NaN }],
|
|
['momentum', { positionSize: Infinity }],
|
|
['momentum', { momentumThreshold: '5' }],
|
|
['pairs_trading', { pairA: 'A.US', pairB: 'A.US' }],
|
|
] as const) {
|
|
expect(() => engine.addNativeStrategy(name, 'invalid', 'invalid', parameters)).toThrow();
|
|
}
|
|
expect(() =>
|
|
engine.addNativeStrategy('sma_crossover', 'defaults', 'defaults', {})
|
|
).not.toThrow();
|
|
});
|
|
});
|