feat(strategies): add canonical regime-aware mean reversion

This commit is contained in:
Boki 2026-10-23 17:10:08 -04:00
parent 75abae2cfc
commit 6a67ae8683
24 changed files with 1910 additions and 88 deletions

View file

@ -0,0 +1,107 @@
import {
meanReversionStrategySelectionSchema,
type BuiltinStrategySelection,
type MeanReversionSignalParameters,
type MeanReversionStrategySelection,
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { nativeReplayFixture } from './native-replay';
export function canonicalRegimeSelection(
ownerId = 'A',
options: {
ownerBudget?: string;
parameters?: Partial<MeanReversionSignalParameters>;
} = {}
): MeanReversionStrategySelection {
return meanReversionStrategySelectionSchema.parse({
ownerId,
strategyId: 'mean_reversion',
strategyVersion: 'mean-reversion-regime-long-only/v1',
seed: 42,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: options.ownerBudget ?? '80',
parameters: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.9,
minMomentumReturn: -0.9,
maxVolatility: 1,
minNotionalVolume: '0',
regimeFilter: 'volatility',
...options.parameters,
},
});
}
/** Small economic oracle, not a profitable-strategy claim: with the default
* selection, the third completed close8 requests ten shares, filled at next
* open7. The fifth close10 requests flat, filled at next open11. Gross40,
* fees1.80 at1%, final equity10038.20. No unobserved close is executable. */
export function canonicalRegimeResearchFixture(
options: {
selections?: readonly BuiltinStrategySelection[];
closes?: readonly number[];
opens?: readonly number[];
volumes?: readonly number[];
availabilitySteps?: readonly number[];
tradeStartStep?: number;
feeRate?: string;
slippageRate?: string;
} = {}
) {
const closes = options.closes ?? [10, 10, 8, 7, 10, 10];
const opens = options.opens ?? [10, 10, 10, 7, 9, 11];
if (
opens.length !== closes.length ||
(options.volumes && options.volumes.length !== closes.length) ||
(options.availabilitySteps && options.availabilitySteps.length !== closes.length)
) {
throw new Error('Research fixture columns must have equal lengths');
}
const selections = options.selections ?? [canonicalRegimeSelection()];
const fixture = nativeReplayFixture(
closes.length,
1,
selections.map(item => item.ownerId)
);
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
fixture.dataset.manifest;
const dataset = createDatasetV2({
metadata: {
calendars,
series,
executionSeries,
bounds: {
...bounds,
tradeStart: fixture.start + (options.tradeStartStep ?? 1) * fixture.minute,
},
universe,
corporateActions,
},
bars: fixture.dataset.bars.map((bar, index) => {
const open = opens[index]!,
close = closes[index]!;
return {
seriesId: bar.seriesId,
timestamp: bar.intervalStart,
availableAt:
fixture.start + (options.availabilitySteps?.[index] ?? index + 1) * fixture.minute,
sourceSequence: bar.sourceSequence,
open,
high: Math.max(open, close),
low: Math.min(open, close),
close,
volume: options.volumes?.[index] ?? 1000,
};
}),
});
fixture.config.matching.risk.feeRate = options.feeRate ?? '0.01';
fixture.config.matching.slippageRate = options.slippageRate ?? '0';
return { ...fixture, dataset, selections: [...selections] };
}

View file

@ -1,4 +1,4 @@
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { nativeReplayFixture } from './native-replay';
@ -48,7 +48,7 @@ export function canonicalSmaFixture(
}),
});
const selections = owners.map(ownerId =>
builtinStrategySelectionSchema.parse({
smaStrategySelectionSchema.parse({
ownerId,
strategyId: 'sma',
strategyVersion: 'sma-crossover-long-only/v1',

View file

@ -4,7 +4,7 @@ import { strategyReplayRequestSchema } from '../../apps/stock/orchestrator/src/c
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
function send(message: unknown): Promise<void> {
return new Promise((resolve, reject) =>

View file

@ -0,0 +1,44 @@
import { expect, test } from 'bun:test';
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
test('canonical mean-reversion selection requires its exact version and explicit compatible parameters', () => {
const selection = canonicalRegimeSelection();
for (const alias of ['mean_reversion', 'mean-reversion', ' Mean Reversion ']) {
expect(builtinStrategySelectionSchema.parse({ ...selection, strategyId: alias })).toEqual(
selection
);
}
const { maxVolatility: _ceiling, ...missing } = selection.parameters;
for (const patch of [
{ strategyId: 'sma' },
{ strategyVersion: 'mean-reversion/v2' },
{ strategyVersion: 'mean-reversion-regime-long-only/v2' },
{ ownerBudget: '0' },
{ ownerBudget: '-1' },
{ ownerBudget: 'invalid' },
{ parameters: missing },
{ parameters: {} },
{ parameters: { ...selection.parameters, lookbackPeriod: 1 } },
{ parameters: { ...selection.parameters, trendPeriod: 2 } },
{ parameters: { ...selection.parameters, momentumPeriod: 0 } },
{ parameters: { ...selection.parameters, volatilityPeriod: 1 } },
{ parameters: { ...selection.parameters, entryZScore: 0 } },
{ parameters: { ...selection.parameters, exitZScore: 1 } },
{ parameters: { ...selection.parameters, minTrendReturn: -1 } },
{ parameters: { ...selection.parameters, minMomentumReturn: -1 } },
{ parameters: { ...selection.parameters, maxVolatility: Infinity } },
{ parameters: { ...selection.parameters, maxVolatility: -0.01 } },
{ parameters: { ...selection.parameters, minNotionalVolume: '-1' } },
{ parameters: { ...selection.parameters, minNotionalVolume: 'invalid' } },
{ parameters: { ...selection.parameters, regimeFilter: 'fitted' } },
{ parameters: { ...selection.parameters, rsiOversold: 30 } },
{ parameters: { ...selection.parameters, quantity: 10 } },
{ parameters: { ...selection.parameters, maxPositionQuantity: '99999' } },
{ initialState: {} },
{ source: 'return buy()' },
{ decide: () => ({}) },
]) {
expect(() => builtinStrategySelectionSchema.parse({ ...selection, ...patch })).toThrow();
}
});

View file

@ -0,0 +1,462 @@
import { expect, test } from 'bun:test';
import { parseFinancialDecimal } from '@stock-bot/types';
import {
meanReversionStrategySelectionSchema,
type MeanReversionSignalParameters,
type MeanReversionStrategySelection,
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type {
StrategyContext,
StrategyProgram,
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import {
calculateMeanReversionSignals,
createMeanReversionStrategy,
type MeanReversionStrategyState,
} from '../../apps/stock/orchestrator/src/strategies/canonical-mean-reversion';
const d = parseFinancialDecimal;
function selection(
parameters: Partial<MeanReversionSignalParameters> = {},
patch: Partial<MeanReversionStrategySelection> = {}
) {
return meanReversionStrategySelectionSchema.parse({
ownerId: 'A',
strategyId: 'mean_reversion',
strategyVersion: 'mean-reversion-regime-long-only/v1',
seed: 7,
instrumentId: 'X',
seriesId: 'X:bar',
ownerBudget: '80',
parameters: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0.2,
minTrendReturn: -0.9,
minMomentumReturn: -0.9,
maxVolatility: 10,
minNotionalVolume: '0',
regimeFilter: 'volatility',
...parameters,
},
...patch,
});
}
function observation(
close: string,
sequence: number,
patch: Partial<PublishedObservation> = {}
): PublishedObservation {
return {
series_id: 'X:bar',
instrument_id: 'X',
interval_start: sequence,
interval_end: sequence + 1,
event_time: sequence + 1,
available_at: sequence + 1,
source_sequence: sequence,
open: d(close),
high: d(close),
low: d(close),
close: d(close),
volume: d('100'),
...patch,
};
}
function position(ownerId = 'A', quantity = '2.5', instrumentId = 'X') {
return {
ownerId,
instrumentId,
quantity: d(quantity),
remainingCost: d('0'),
realizedGrossPnl: d('0'),
};
}
function context(
state: MeanReversionStrategyState,
observations: PublishedObservation[],
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
): StrategyContext<MeanReversionStrategyState> {
const last = observations.at(-1);
const now = last?.available_at ?? state.lastObservation?.availableAt ?? 0;
const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 };
return {
ownerId: 'A',
strategyId: 'mean_reversion',
strategyVersion: 'mean-reversion-regime-long-only/v1',
decisionSequence: 0,
now,
barrier: {
barrier_id: 'test',
at: now,
revision: 0,
owner_ids: ['A'],
observation_count: observations.length,
inputs: [
{
series_id: 'X:bar',
availability: last
? { Fresh: { event_time: last.event_time, available_at: last.available_at } }
: 'Missing',
},
],
},
portfolio: {
admissionRevision: 0,
equity: d('10000'),
availableCash: d('10000'),
orders: [],
reservations: [],
portfolio: {
version: 1,
sessionId: 'test',
accountId: 'test',
revision: 0,
baseCurrency: 'USD',
reserveOwnerId: 'reserve',
cash: d('10000'),
positions: [],
fees: [],
riskSession,
},
risk: {
dailyBaseline: d('10000'),
peakEquity: d('10000'),
dailyHalted: false,
drawdownHalted: false,
riskSession,
lastEventTime: now,
},
},
positions: [],
observations,
previousAdmission: null,
state,
random: () => {
throw new Error('Mean reversion must not consume randomness');
},
...patch,
};
}
function decide(
program: StrategyProgram<MeanReversionStrategyState>,
closes: string[],
state = program.initialState,
offset = 0,
patch: Partial<StrategyContext<MeanReversionStrategyState>> = {}
) {
return program.decide(
context(
state,
closes.map((close, i) => observation(close, offset + i)),
patch
)
);
}
const target = (quantity: string) => ({
mode: 'target' as const,
targets: [{ instrumentId: 'X', quantity: d(quantity) }],
});
const none = { mode: 'target' as const, targets: [] };
test('signal_composition_units use population deviation, fractional returns and inclusive volatility regimes', () => {
const params = selection().parameters;
const signals = calculateMeanReversionSignals([100, 110, 99], params)!;
expect(signals.mean).toBe(104.5);
expect(signals.zScore).toBe(-1);
expect(signals.trendReturn).toBeCloseTo(104.5 / 103 - 1, 12);
expect(signals.momentumReturn).toBeCloseTo(-0.1, 12);
expect(signals.volatility).toBeCloseTo(0.1, 12);
expect(
calculateMeanReversionSignals([100, 110, 99], { ...params, maxVolatility: signals.volatility })!
.regime
).toBe('low');
expect(
calculateMeanReversionSignals([100, 110, 99], {
...params,
maxVolatility: signals.volatility - 1e-10,
})!.regime
).toBe('high');
expect(calculateMeanReversionSignals([10, 10, 10], params)).toEqual({
mean: 10,
zScore: 0,
trendReturn: 0,
momentumReturn: 0,
volatility: 0,
regime: 'low',
});
for (const close of [0, -1, Number.NaN, Infinity]) {
expect(() => calculateMeanReversionSignals([10, 10, close], params)).toThrow();
}
});
test('both ablation modes require identical complete warmup and flat prices create no entry', () => {
for (const regimeFilter of ['none', 'volatility'] as const) {
const selected = selection({ momentumPeriod: 4, volatilityPeriod: 6, regimeFilter });
expect(
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10], selected.parameters)
).toBeUndefined();
expect(
calculateMeanReversionSignals([10, 10, 10, 10, 10, 10, 10], selected.parameters)
).toBeDefined();
const program = createMeanReversionStrategy(selected);
expect(decide(program, ['10', '10', '10', '10', '10', '8']).intent).toEqual(none);
expect(decide(program, ['10', '10', '10', '10', '10', '10', '10']).intent).toEqual(none);
}
});
test('inclusive entry conjunction uses exact notional volume and a fixed whole-share budget', () => {
const signals = calculateMeanReversionSignals([100, 110, 99], selection().parameters)!;
const parameters = {
minTrendReturn: signals.trendReturn,
minMomentumReturn: signals.momentumReturn,
maxVolatility: signals.volatility,
minNotionalVolume: d('198'),
};
const run = (overrides: Partial<MeanReversionSignalParameters> = {}) => {
const program = createMeanReversionStrategy(
selection({ ...parameters, ...overrides }, { ownerBudget: d('990') })
);
return program.decide(
context(
program.initialState,
[100, 110, 99].map((close, i) => observation(String(close), i, { volume: d('2') }))
)
);
};
expect(run().intent).toEqual(target('10'));
for (const changed of [
{ entryZScore: 1.00001 },
{ minTrendReturn: signals.trendReturn + 1e-6 },
{ minMomentumReturn: signals.momentumReturn + 1e-6 },
{ minNotionalVolume: d('198.00000001') },
{ maxVolatility: signals.volatility - 1e-6 },
]) {
expect(run(changed).intent).toEqual(none);
}
expect(run({ maxVolatility: 0, regimeFilter: 'none' }).intent).toEqual(target('10'));
expect(
run({ maxVolatility: 0, regimeFilter: 'none', minNotionalVolume: d('199') }).intent
).toEqual(none);
const poor = createMeanReversionStrategy(selection({}, { ownerBudget: d('7.99') }));
expect(decide(poor, ['10', '10', '8']).intent).toEqual(target('0'));
const exact = createMeanReversionStrategy(
selection(
{ entryZScore: 0.5, minNotionalVolume: d('900000000.00000003') },
{ ownerBudget: d('0.0000003') }
)
);
const rows = ['0.00000005', '0.00000005', '0.00000003'].map((close, i) =>
observation(close, i, { volume: d('30000000000000001') })
);
expect(exact.decide(context(exact.initialState, rows)).intent).toEqual(target('10'));
const insufficient = structuredClone(rows);
insufficient[2]!.volume = d('30000000000000000');
expect(exact.decide(context(exact.initialState, insufficient)).intent).toEqual(none);
});
test('only the final fresh prefix can create intent; intermediate entry or exit signals have no phantom effect', () => {
const program = createMeanReversionStrategy(selection());
expect(decide(program, ['10', '10', '8', '10']).intent).toEqual(none);
const entered = decide(program, ['10', '10', '8']);
expect(entered.intent).toEqual(target('10'));
// Intermediate 12 would exit, but it was not a decision barrier.
expect(
decide(program, ['12', '7'], entered.nextState, 3, { positions: [position('A', '10')] }).intent
).toEqual(target('10'));
});
test('future suffix changes cannot alter earlier state or decisions; observed gaps do not synthesize history', () => {
const program = createMeanReversionStrategy(selection());
const prefix = ['10', '10', '8'];
const trace = (suffix: string[]) => {
let state = program.initialState;
return [...prefix, ...suffix].map((close, index) => {
const result = decide(program, [close], state, index);
state = result.nextState;
return result;
});
};
expect(trace(['7', '10']).slice(0, 3)).toEqual(trace(['700', '0.01']).slice(0, 3));
const regular = decide(program, prefix);
const gaps = program.decide(
context(
program.initialState,
prefix.map((close, i) => observation(close, i * 1000))
)
);
expect(gaps.intent).toEqual(regular.intent);
expect(gaps.nextState.closes).toEqual(regular.nextState.closes);
});
test('stale, missing or mismatched availability only advances history; delayed and duplicate physical bars cannot rewrite it', () => {
const program = createMeanReversionStrategy(selection());
const entered = decide(program, ['10', '10', '8']);
for (const availability of [
'Missing',
{ Stale: { event_time: 4, available_at: 4 } },
{ Fresh: { event_time: 400, available_at: 400 } },
] as const) {
const input = context(entered.nextState, [observation('12', 3)]);
const result = program.decide({
...input,
barrier: { ...input.barrier, inputs: [{ series_id: 'X:bar', availability }] },
});
expect(result.intent).toEqual(none);
expect(result.nextState.targetQuantity).toBe(d('10'));
expect(result.nextState.closes).toEqual([10, 8, 12]);
}
const delayed = program.decide(
context(entered.nextState, [observation('0.01', 1, { available_at: 10 })], { now: 10 })
);
expect(delayed.nextState).toEqual(entered.nextState);
expect(delayed.intent).toEqual(none);
expect(program.decide(context(entered.nextState, [observation('80', 2)])).nextState).toEqual(
entered.nextState
);
expect(program.decide(context(entered.nextState, [])).intent).toEqual(none);
for (const row of [
observation('7', 3, { available_at: 99 }),
observation('7', 3, { event_time: 99 }),
observation('7', 3, { instrument_id: 'OTHER' }),
]) {
expect(() => program.decide(context(entered.nextState, [row], { now: 4 }))).toThrow();
}
});
test('entry-only filters cannot block exit or cancel a partially filled exit target', () => {
const program = createMeanReversionStrategy(
selection({ maxVolatility: 0.15, minNotionalVolume: d('1') })
);
const entered = decide(program, ['10', '10', '8']);
const exit = program.decide(
context(entered.nextState, [observation('12', 3, { volume: d('0') })], {
positions: [position('A', '2.5')],
})
);
expect(exit.intent).toEqual(target('0'));
const partial = program.decide(
context(exit.nextState, [observation('1', 4, { volume: d('0') })], {
positions: [position('A', '1.25')],
})
);
expect(partial.intent).toEqual(target('0'));
expect(partial.nextState.targetQuantity).toBe(d('0'));
});
test('failed entry gates cancel unfilled remainder permanently; fractional owned exposure does not rebuild on recovery', () => {
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1') }));
const entered = decide(program, ['10', '10', '8']);
const rejected = decide(program, ['7'], entered.nextState, 3, {
previousAdmission: {
decision: {
ownerId: 'A',
decisionId: 'A:0',
sequence: 0,
},
revision: 1,
orders: [
{
orderId: 'denied-entry',
instrumentId: 'X',
decision: { ownerId: 'A', decisionId: 'A:0', sequence: 0 },
status: { Rejected: 'InsufficientCash' },
},
],
},
});
expect(rejected.intent).toEqual(target('10'));
for (const owned of ['0', '2.5']) {
const clipped = program.decide(
context(entered.nextState, [observation('7', 3, { volume: d('0') })], {
positions: owned === '0' ? [] : [position('A', owned)],
})
);
expect(clipped.intent).toEqual(target(owned));
const recovered = decide(program, ['6'], clipped.nextState, 4, {
positions: owned === '0' ? [] : [position('A', owned)],
});
expect(recovered.intent).toEqual(target(owned === '0' ? '13' : '2.5'));
}
});
test('trend, momentum, volatility and z-score entry failures also cap pending exposure to actual holdings', () => {
const cases: {
parameters: Partial<MeanReversionSignalParameters>;
prefix: string[];
next: string;
}[] = [
{ parameters: { minTrendReturn: -0.05 }, prefix: ['10', '10', '8'], next: '7' },
{ parameters: { minMomentumReturn: -0.3 }, prefix: ['10', '10', '8'], next: '4' },
{ parameters: { maxVolatility: 0.15 }, prefix: ['10', '10', '8'], next: '1' },
{
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
prefix: ['10', '10', '10', '8'],
next: '7.5',
},
];
for (const { parameters, prefix, next } of cases) {
const program = createMeanReversionStrategy(selection(parameters));
const entered = decide(program, prefix);
expect(entered.intent).toEqual(target('10'));
expect(
decide(program, [next], entered.nextState, prefix.length, {
positions: [position('A', '2.5')],
}).intent
).toEqual(target('2.5'));
}
});
test('owner isolation adopts only existing owned exposure and never pyramids another owner quantity', () => {
const program = createMeanReversionStrategy(selection({ minNotionalVolume: d('1000000') }));
expect(
decide(program, ['10', '10', '8'], program.initialState, 0, {
positions: [position('B', '99')],
}).intent
).toEqual(none);
expect(
decide(program, ['10', '10', '8'], program.initialState, 0, {
positions: [position('B', '99'), position('A', '3.25')],
}).intent
).toEqual(target('3.25'));
expect(
decide(program, ['10', '8', '10'], program.initialState, 0, {
positions: [position('A', '3.25')],
}).intent
).toEqual(target('0'));
});
test('checkpoint validation and detachment preserve inputs, reject incompatible state, and bound retained history', () => {
const selected = selection();
const program = createMeanReversionStrategy(selected);
selected.parameters.entryZScore = 99;
const initial = structuredClone(program.initialState);
const entered = decide(program, ['10', '10', '8']);
expect(entered.intent).toEqual(target('10'));
expect(program.initialState).toEqual(initial);
const restored = JSON.parse(JSON.stringify(entered.nextState)) as MeanReversionStrategyState;
expect(decide(createMeanReversionStrategy(selection()), ['7'], restored, 3)).toEqual(
decide(program, ['7'], entered.nextState, 3)
);
for (const state of [
{ ...restored, version: 2 },
{ ...restored, selectionKey: 'other' },
{ ...restored, closes: [] },
{ ...restored, targetQuantity: d('-1') },
{ ...restored, unknown: true },
]) {
expect(() => decide(program, ['7'], state as MeanReversionStrategyState, 3)).toThrow();
}
expect(() => program.decide(context(restored, [], { now: 1 }))).toThrow('future');
const next = decide(program, ['7', '6', '5', '4'], restored, 3);
expect(next.nextState.closes).toEqual([6, 5, 4]);
next.nextState.closes[0] = 999;
expect(restored.closes).toEqual([10, 10, 8]);
expect(() =>
decide(createMeanReversionStrategy(selection({}, { ownerId: 'B' })), ['7'], restored, 3)
).toThrow();
});

View file

@ -0,0 +1,417 @@
import { createHash } from 'node:crypto';
import { expect, test } from 'bun:test';
import { parseFinancialDecimal, type FinancialStrategyIntent } from '@stock-bot/types';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type {
StrategyContext,
StrategyProgram,
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import type {
ReplayProjectionResult,
ReplayReportResult,
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
canonicalRegimeResearchFixture,
canonicalRegimeSelection,
} from '../fixtures/canonical-regime-research';
const d = parseFinancialDecimal;
type Fixture = ReturnType<typeof canonicalRegimeResearchFixture>;
type DecisionRecord = {
ownerId: string;
at: number;
sequence: number;
observed: { eventTime: number; availableAt: number; close: string }[];
positions: StrategyContext['positions'];
portfolio: StrategyContext['portfolio'];
state: unknown;
intent: FinancialStrategyIntent;
};
function run(fixture: Fixture, eventBudget = 1) {
const load = prepareReplayLoad(fixture.dataset, fixture.config);
validateBuiltinStrategyBindings(fixture.selections, load);
const records: DecisionRecord[] = [];
const programs = fixture.selections.map(selection => {
const strategy = createBuiltinStrategy(selection);
return {
...strategy,
decide(context: StrategyContext) {
const output = strategy.decide(context);
records.push({
ownerId: context.ownerId,
at: context.now,
sequence: context.decisionSequence,
observed: context.observations.map(row => ({
eventTime: row.event_time,
availableAt: row.available_at,
close: row.close,
})),
positions: context.positions,
portfolio: context.portfolio,
state: structuredClone(output.nextState),
intent: structuredClone(output.intent),
});
return output;
},
} satisfies StrategyProgram;
});
return {
...runStrategyReplay(load, programs, { resultFormat: 'report', eventBudget }),
records,
};
}
function economicHash(result: ReplayProjectionResult | ReplayReportResult): string {
return createHash('sha256')
.update(JSON.stringify({ projection: result.projection, view: result.view }))
.digest('hex');
}
function target(record: DecisionRecord) {
return record.intent.mode === 'target' ? record.intent.targets[0]?.quantity : undefined;
}
test('MR hand oracle buys and exits at next opens with authoritative basis, commissions and terminal equity', () => {
const fixture = canonicalRegimeResearchFixture();
const result = run(fixture);
expect(
result.records.filter(row => row.at < fixture.start + 3 * fixture.minute).map(target)
).toEqual([undefined, undefined]);
expect(target(result.records.find(row => row.at === fixture.start + 3 * fixture.minute)!)).toBe(
d('10')
);
expect(
result.result.projection.fills.map(fill => ({
at: fill.eventTime,
quantity: fill.quantityDelta,
price: fill.price,
fee: fill.fee.amount,
releasedBasis: fill.releasedBasis,
realizedGrossPnl: fill.realizedGrossPnl,
}))
).toEqual([
{
at: fixture.start + 3 * fixture.minute,
quantity: d('10'),
price: d('7'),
fee: d('0.7'),
releasedBasis: d('0'),
realizedGrossPnl: d('0'),
},
{
at: fixture.start + 5 * fixture.minute,
quantity: d('-10'),
price: d('11'),
fee: d('1.1'),
releasedBasis: d('70'),
realizedGrossPnl: d('40'),
},
]);
expect(result.result.projection.valuation).toMatchObject({
cash: d('10038.2'),
equity: d('10038.2'),
markedHoldings: d('0'),
remainingCost: d('0'),
realizedGrossPnl: d('40'),
fees: d('1.8'),
});
expect(result.diagnostics.strategies[0]!.state).toMatchObject({ targetQuantity: d('0') });
});
test('two differently configured MR owners share native portfolio barriers but retain independent history, inventory, basis and fees', () => {
const fixture = canonicalRegimeResearchFixture({
selections: [
canonicalRegimeSelection('B', {
ownerBudget: '35',
parameters: { lookbackPeriod: 3, trendPeriod: 4 },
}),
canonicalRegimeSelection('A'),
],
});
const result = run(fixture);
const beforeExit = result.records.filter(row => row.at === fixture.start + 5 * fixture.minute);
expect(beforeExit).toHaveLength(2);
expect(beforeExit[0]!.portfolio).toBe(beforeExit[1]!.portfolio);
expect(
beforeExit.map(row => [
row.ownerId,
row.positions.map(position => [position.ownerId, position.quantity, position.remainingCost]),
])
).toEqual([
['B', [['B', d('5'), d('45')]]],
['A', [['A', d('10'), d('70')]]],
]);
expect(
result.result.projection.fills.map(fill => [
fill.ownerId,
fill.quantityDelta,
fill.price,
fill.releasedBasis,
])
).toEqual([
['A', d('10'), d('7'), d('0')],
['B', d('5'), d('9'), d('0')],
['A', d('-10'), d('11'), d('70')],
['B', d('-5'), d('11'), d('45')],
]);
expect(
result.result.projection.valuation.owners
.filter(owner => owner.ownerId !== 'reserve')
.map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees, owner.remainingCost])
).toEqual([
['A', d('40'), d('1.8'), d('0')],
['B', d('10'), d('1'), d('0')],
]);
expect(result.result.projection.valuation.equity).toBe(d('10047.2'));
const [a, b] = result.diagnostics.strategies;
// The terminal close marks equity; tradeEnd itself does not create another decision.
expect(a!.state).toMatchObject({ closes: [8, 7, 10], targetQuantity: d('0') });
expect(b!.state).toMatchObject({ closes: [10, 8, 7, 10], targetQuantity: d('0') });
expect(a!.state).not.toEqual(b!.state);
expect(
result.records.every(row => row.positions.every(position => position.ownerId === row.ownerId))
).toBe(true);
});
test.each(['trace', 'projection', 'report'] as const)(
'actual %s worker supports mixed MR/SMA selections with the same native decisions and finance as direct replay',
async resultFormat => {
const fixture = canonicalRegimeResearchFixture({
selections: [
canonicalRegimeSelection('A'),
smaStrategySelectionSchema.parse({
ownerId: 'B',
strategyId: 'sma',
strategyVersion: 'sma-crossover-long-only/v1',
seed: 43,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '30',
parameters: { fastPeriod: 1, slowPeriod: 2 },
}),
],
});
const input = strategyReplayRequestSchema.parse({
type: 'runStrategyReplay',
version: 1,
dataset: fixture.dataset,
config: fixture.config,
strategies: fixture.selections,
eventBudget: 2,
resultFormat,
});
const load = prepareReplayLoad(fixture.dataset, input.config);
const expected = runStrategyReplay(load, input.strategies.map(createBuiltinStrategy), {
resultFormat,
eventBudget: 1,
});
const worker = new NativeBacktestWorker();
const output = await worker.execute(input, new AbortController().signal, () => {});
const parsed = parseStrategyReplayResult(output, {
strategies: input.strategies,
identity: load.identity,
policy: input.config,
format: resultFormat,
});
expect(parsed.result).toEqual(expected.result);
expect(parsed.strategies.map(item => [item.ownerId, item.strategyId])).toEqual([
['A', 'mean_reversion'],
['B', 'sma_crossover'],
]);
expect(
parsed.result.view.portfolio.positions.find(position => position.ownerId === 'B')
).toMatchObject({ quantity: d('3'), remainingCost: d('33') });
if ('projection' in parsed.result) {
expect(parsed.result.projection.valuation).toMatchObject({
equity: d('10034.87'),
fees: d('2.13'),
remainingCost: d('33'),
unrealizedPnl: d('-3'),
});
}
if (resultFormat === 'report') {
expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(output);
}
}
);
test('fee-inclusive cash and portfolio risk rejections remain Rust authority for MR targets', () => {
for (const mode of ['fee-funding', 'position-limit'] as const) {
const fixture = canonicalRegimeResearchFixture();
if (mode === 'fee-funding') {
fixture.config.matching.risk.ledger.initialCapital = '80';
} else {
fixture.config.matching.risk.maxPositionQuantity = '5';
}
const result = run(fixture);
expect(result.records.some(row => target(row) === d('10'))).toBe(true);
expect(result.result.projection.fills).toEqual([]);
expect(result.result.projection.valuation).toMatchObject({
cash: d(mode === 'fee-funding' ? '80' : '10000'),
fees: d('0'),
remainingCost: d('0'),
});
const trace = runStrategyReplay(
prepareReplayLoad(fixture.dataset, fixture.config),
fixture.selections.map(createBuiltinStrategy),
{ resultFormat: 'trace' }
);
expect(JSON.stringify(trace.result.receipts)).toContain(
mode === 'fee-funding' ? 'InsufficientCash' : 'PositionSize'
);
}
});
test('partial entry commitments are cancelled when gates fail, never rebuilt while held, and low-volume exits still fill', () => {
const fixture = canonicalRegimeResearchFixture({
selections: [canonicalRegimeSelection('A', { parameters: { minNotionalVolume: d('200') } })],
closes: [10, 10, 8, 7, 6, 10, 10, 10],
opens: [10, 10, 10, 7, 6, 9, 11, 11],
volumes: [1000, 1000, 30, 10, 1000, 10, 1000, 1000],
});
// Native Open mode uses previously available completed volume: 30*.1 fills
// three shares, then the later low-volume exit fills one and two at11.
fixture.config.participation_rate = '0.1';
const result = run(fixture);
expect(
result.records.filter(row => row.at >= fixture.start + 3 * fixture.minute).map(target)
).toEqual([d('10'), d('3'), d('3'), d('0'), d('0')]);
expect(result.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
[d('3'), d('7')],
[d('-1'), d('11')],
[d('-2'), d('11')],
]);
expect(result.result.projection.valuation).toMatchObject({
equity: d('10011.46'),
fees: d('0.54'),
remainingCost: d('0'),
});
});
test('future suffix mutations cannot alter earlier MR decisions, observation availability or held inventory', () => {
const original = canonicalRegimeResearchFixture();
const mutated = canonicalRegimeResearchFixture({
closes: [10, 10, 8, 7, 1, 500],
opens: [10, 10, 10, 7, 80, 100],
});
expect(mutated.dataset.manifest.hash).not.toBe(original.dataset.manifest.hash);
const baseline = run(original),
changed = run(mutated);
const prefix = (records: DecisionRecord[]) =>
records
.filter(row => row.at <= original.start + 4 * original.minute)
.map(({ ownerId, at, sequence, observed, positions, state, intent }) => ({
ownerId,
at,
sequence,
observed,
positions,
state,
intent,
}));
expect(prefix(changed.records)).toEqual(prefix(baseline.records));
for (const row of [...baseline.records, ...changed.records]) {
expect(row.observed.every(observation => observation.availableAt <= row.at)).toBe(true);
}
expect(
changed.result.projection.fills.filter(
fill => fill.eventTime <= original.start + 3 * original.minute
)
).toEqual(
baseline.result.projection.fills.filter(
fill => fill.eventTime <= original.start + 3 * original.minute
)
);
});
test('fixed versioned inputs reproduce identical strategy state, economic hashes and native finance across event budgets', () => {
const fixture = canonicalRegimeResearchFixture();
const before = JSON.stringify(fixture);
const first = run(fixture, 1),
second = run(fixture, 64),
third = run(canonicalRegimeResearchFixture(), 3);
expect(JSON.stringify(fixture)).toBe(before);
expect(second.result).toEqual(first.result);
expect(third.result).toEqual(first.result);
expect(second.diagnostics).toEqual(first.diagnostics);
expect(third.diagnostics).toEqual(first.diagnostics);
expect(economicHash(second.result)).toBe(economicHash(first.result));
expect(economicHash(third.result)).toBe(economicHash(first.result));
});
test('no-regime ablation changes only the volatility entry gate and retains identical observation warmup', () => {
const filtered = canonicalRegimeSelection('A', { parameters: { maxVolatility: 0.05 } });
const unfiltered = canonicalRegimeSelection('A', {
parameters: { maxVolatility: 0.05, regimeFilter: 'none' },
});
expect(unfiltered).toEqual({
...filtered,
parameters: { ...filtered.parameters, regimeFilter: 'none' },
});
const filteredFixture = canonicalRegimeResearchFixture({ selections: [filtered] });
const unfilteredFixture = canonicalRegimeResearchFixture({ selections: [unfiltered] });
expect(filteredFixture.dataset.manifest.hash).toBe(unfilteredFixture.dataset.manifest.hash);
expect(filteredFixture.config).toEqual(unfilteredFixture.config);
const withRegime = run(filteredFixture),
withoutRegime = run(unfilteredFixture);
expect(withRegime.records.map(row => [row.at, row.observed])).toEqual(
withoutRegime.records.map(row => [row.at, row.observed])
);
expect(withRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
expect(withoutRegime.records.slice(0, 2).map(target)).toEqual([undefined, undefined]);
expect(withRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
expect(withoutRegime.records[2]!.state).toMatchObject({ closes: [10, 10, 8] });
expect(target(withRegime.records[2]!)).toBeUndefined();
expect(target(withoutRegime.records[2]!)).toBe(d('10'));
expect(withRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])).toEqual([
[d('11'), d('9')],
[d('-11'), d('11')],
]);
expect(
withoutRegime.result.projection.fills.map(fill => [fill.quantityDelta, fill.price])
).toEqual([
[d('10'), d('7')],
[d('-10'), d('11')],
]);
});
test('fixed fee and slippage alternatives retain provenance and give hand-computed native cost sensitivity', () => {
const recipes = [
{ feeRate: '0', slippageRate: '0', equity: '10040', fees: '0', prices: ['7', '11'] },
{ feeRate: '0.01', slippageRate: '0', equity: '10038.2', fees: '1.8', prices: ['7', '11'] },
{
feeRate: '0.01',
slippageRate: '0.01',
equity: '10036.404',
fees: '1.796',
prices: ['7.07', '10.89'],
},
];
const baseline = canonicalRegimeResearchFixture();
for (const recipe of recipes) {
const fixture = canonicalRegimeResearchFixture(recipe);
expect(fixture.dataset.manifest.hash).toBe(baseline.dataset.manifest.hash);
expect(fixture.selections).toEqual(baseline.selections);
const result = run(fixture);
expect(result.result.projection.valuation).toMatchObject({
equity: d(recipe.equity),
fees: d(recipe.fees),
});
expect(result.result.projection.fills.map(fill => fill.price)).toEqual(recipe.prices.map(d));
expect(economicHash(run(canonicalRegimeResearchFixture(recipe)).result)).toBe(
economicHash(result.result)
);
}
});

View file

@ -7,7 +7,8 @@ import {
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import {
builtinStrategySelectionSchema,
type BuiltinStrategySelection,
smaStrategySelectionSchema,
type SmaStrategySelection,
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type {
StrategyContext,
@ -16,16 +17,16 @@ import type {
import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names';
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
import { validateBuiltinStrategyBindings } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
createSmaStrategy as createBuiltinStrategy,
type SmaStrategyState,
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
const d = parseFinancialDecimal;
function selection(overrides: Partial<BuiltinStrategySelection> = {}) {
return builtinStrategySelectionSchema.parse({
function selection(overrides: Partial<SmaStrategySelection> = {}) {
return smaStrategySelectionSchema.parse({
...canonicalSmaFixture().selections[0],
...overrides,
});

View file

@ -17,7 +17,7 @@ import {
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
} from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { nativeReplayFixture } from '../fixtures/native-replay';
function request(resultFormat: ReplayResultFormat = 'trace', owners = ['A']) {

View file

@ -0,0 +1,110 @@
import { expect, test } from 'bun:test';
import { parseFinancialDecimal } from '@stock-bot/types';
import {
createRegimeComparisons,
runRegimeComparisons,
} from '../../apps/stock/orchestrator/examples/canonical-regime-research';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import type { StrategyReplayRequest } from '../../apps/stock/orchestrator/src/contracts/strategy-replay';
import {
canonicalRegimeResearchFixture,
canonicalRegimeSelection,
} from '../fixtures/canonical-regime-research';
function request(): StrategyReplayRequest {
const fixture = canonicalRegimeResearchFixture({
selections: [canonicalRegimeSelection('A', { parameters: { maxVolatility: 0.05 } })],
});
return {
type: 'runStrategyReplay',
version: 1,
dataset: fixture.dataset,
config: fixture.config,
strategies: fixture.selections,
eventBudget: 2,
resultFormat: 'report',
};
}
const costs = { feeRate: '0.02', slippageRate: '0.01' };
test('comparison inputs are detached, explicit and differ only by declared filter/cost changes', () => {
const input = request();
const original = structuredClone(input);
const trials = createRegimeComparisons(input, costs);
expect(trials.map(trial => trial.label)).toEqual([
'volatility',
'none',
'volatility-alternative-costs',
'none-alternative-costs',
]);
const [on, off, higherOn, higherOff] = trials.map(trial => structuredClone(trial.request));
for (const candidate of [on!, off!, higherOn!, higherOff!]) {
expect(candidate.dataset).toEqual(original.dataset);
expect(candidate.strategies[0]!.strategyVersion).toBe('mean-reversion-regime-long-only/v1');
const strategy = candidate.strategies[0]!;
if (strategy.strategyId === 'mean_reversion') {
strategy.parameters.regimeFilter = 'volatility';
}
candidate.config.matching.risk.feeRate = parseFinancialDecimal('0.01');
candidate.config.matching.slippageRate = parseFinancialDecimal('0');
}
expect(off!).toEqual(on!);
expect(higherOn!).toEqual(on!);
expect(higherOff!).toEqual(on!);
trials[0]!.request.config.matching.risk.ledger.accountId = 'changed';
expect(input).toEqual(original);
expect(trials[1]!.request.config.matching.risk.ledger.accountId).toBe(
original.config.matching.risk.ledger.accountId
);
});
test('malformed costs and cancellation cannot submit a trial', async () => {
let calls = 0;
const worker = {
execute: async () => {
calls++;
throw new Error('unexpected submit');
},
};
await expect(
runRegimeComparisons(
worker,
request(),
{ ...costs, feeRate: 'invalid' },
new AbortController().signal
)
).rejects.toThrow();
const controller = new AbortController();
controller.abort(new Error('cancelled'));
await expect(runRegimeComparisons(worker, request(), costs, controller.signal)).rejects.toThrow(
'cancelled'
);
expect(calls).toBe(0);
});
test('four actual worker reports preserve exact inputs and reproduce the small economic oracle', async () => {
const input = request();
const result = await runRegimeComparisons(
new NativeBacktestWorker(),
input,
costs,
new AbortController().signal
);
expect(result).toHaveLength(4);
expect(result.map(trial => trial.result.result.view.equity)).toEqual(
['10019.80000000', '10038.20000000', '10015.40440000', '10034.60800000'].map(
parseFinancialDecimal
)
);
expect(result.map(trial => trial.result.strategies)).toEqual(
result.map(trial => trial.request.strategies)
);
expect(
await runRegimeComparisons(
new NativeBacktestWorker(),
input,
costs,
new AbortController().signal
)
).toEqual(result);
});

View file

@ -20,7 +20,7 @@ import type {
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
canonicalConfig,
counterProgram,
@ -835,6 +835,68 @@ describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
expect(filled.some(order => order.order.side === 'buy')).toBe(true);
expect(filled.some(order => order.order.side === 'sell')).toBe(true);
});
test('canonical regime strategy retains fractional entry cancellation and exit through every durable restart', async () => {
const selection = builtinStrategySelectionSchema.parse({
ownerId: 'A',
strategyId: 'mean_reversion',
strategyVersion: 'mean-reversion-regime-long-only/v1',
seed: 7,
instrumentId: 'X',
seriesId: 'X:quote',
ownerBudget: '80',
parameters: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.5,
minMomentumReturn: -0.5,
maxVolatility: 1,
minNotionalVolume: '1',
regimeFilter: 'volatility',
},
});
const run = async (restart: boolean) => {
const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]);
let host = f.host;
await send(host, openInput());
for (const [index, close] of ['10', '10', '8', '7', '10', '10'].entries()) {
const mark = markInput(index + 1, ['A'], close);
if (index >= 3) {
mark.observations[0]!.volume = parseFinancialDecimal('0');
}
await send(host, mark);
if (restart) {
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
}
if (index === 3) {
expect((await host.snapshot()).owners[0]!.diagnostic.state).toMatchObject({
targetQuantity: parseFinancialDecimal('0.5'),
});
}
const price = ['10', '10', '7', '9', '11', '10'][index]!;
await send(host, quoteInput(index + 1, index === 2 ? '0.5' : '100', price));
if (restart) {
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
}
}
return { snapshot: await host.snapshot(), journal: await host.journal() };
};
const uninterrupted = await run(false);
expect(await run(true)).toEqual(uninterrupted);
const view = uninterrupted.snapshot.account.view;
expect(view.portfolio.cash).toBe(parseFinancialDecimal('1001.91'));
expect(view.equity).toBe(parseFinancialDecimal('1001.91'));
const position = view.portfolio.positions.find(position => position.ownerId === 'A')!;
expect(position.quantity).toBe(parseFinancialDecimal('0'));
expect(position.remainingCost).toBe(parseFinancialDecimal('0'));
expect(position.realizedGrossPnl).toBe(parseFinancialDecimal('2'));
expect(view.portfolio.fees.find(fee => fee.ownerId === 'A')!.amount).toBe(
parseFinancialDecimal('0.09')
);
});
test('a native failed admission prefix atomically makes its durable batch terminal', async () => {
const max = '792281625142643375935.43950335';
const config = ordersConfig();

View file

@ -7,7 +7,7 @@ import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/pa
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
BacktestConfigSchema,
type OrchestratorServices,