- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
405 lines
15 KiB
TypeScript
405 lines
15 KiB
TypeScript
import { expect, test } from 'bun:test';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import {
|
|
runStrategyReplay,
|
|
StrategyReplayError,
|
|
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
|
import {
|
|
builtinStrategySelectionSchema,
|
|
smaStrategySelectionSchema,
|
|
type SmaStrategySelection,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
StrategyContext,
|
|
StrategyProgram,
|
|
} from '@stock-bot/research/strategy-api';
|
|
import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay';
|
|
import { strategyAliases } from '@stock-bot/stock-config/strategy-names';
|
|
import { validateBuiltinStrategyBindings } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
|
import {
|
|
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<SmaStrategySelection> = {}) {
|
|
return smaStrategySelectionSchema.parse({
|
|
...canonicalSmaFixture().selections[0],
|
|
...overrides,
|
|
});
|
|
}
|
|
function observation(
|
|
close: string,
|
|
sequence: number,
|
|
overrides: Partial<PublishedObservation> = {}
|
|
): PublishedObservation {
|
|
return {
|
|
series_id: 'X0.US:1m',
|
|
instrument_id: 'X0.US',
|
|
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('1000'),
|
|
...overrides,
|
|
};
|
|
}
|
|
function context(
|
|
state: SmaStrategyState,
|
|
observations: PublishedObservation[],
|
|
now = observations.at(-1)?.available_at ?? 0
|
|
): StrategyContext<SmaStrategyState> {
|
|
const last = observations.at(-1);
|
|
const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 };
|
|
return {
|
|
ownerId: 'A',
|
|
strategyId: 'sma_crossover',
|
|
strategyVersion: 'sma-crossover-long-only/v1',
|
|
decisionSequence: 0,
|
|
now,
|
|
barrier: {
|
|
barrier_id: 'test',
|
|
at: now,
|
|
revision: 0,
|
|
owner_ids: ['A'],
|
|
observation_count: observations.length,
|
|
inputs: [
|
|
{
|
|
series_id: 'X0.US:1m',
|
|
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('SMA must not consume random');
|
|
},
|
|
};
|
|
}
|
|
function decide(
|
|
program: StrategyProgram<SmaStrategyState>,
|
|
closes: string[],
|
|
state = program.initialState,
|
|
offset = 0
|
|
) {
|
|
return program.decide(
|
|
context(
|
|
state,
|
|
closes.map((close, i) => observation(close, offset + i))
|
|
)
|
|
);
|
|
}
|
|
|
|
test('sma_registry_alias selects only the explicit canonical version and leaves legacy factories available', () => {
|
|
for (const strategyId of [...strategyAliases.sma_crossover, 'sma_crossover', ' SMA Crossover ']) {
|
|
expect(builtinStrategySelectionSchema.parse({ ...selection(), strategyId }).strategyId).toBe(
|
|
'sma_crossover'
|
|
);
|
|
}
|
|
for (const patch of [
|
|
{ strategyId: 'momentum' },
|
|
{ strategyVersion: 'sma-crossover-fixed/v2' },
|
|
{ source: 'code' },
|
|
{ parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 10 } },
|
|
{ parameters: { fastPeriod: 3, slowPeriod: 3 } },
|
|
{ ownerBudget: '0' },
|
|
]) {
|
|
expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow();
|
|
}
|
|
});
|
|
|
|
test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => {
|
|
const fixture = canonicalSmaFixture();
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
expect(() => validateBuiltinStrategyBindings(fixture.selections, load)).not.toThrow();
|
|
for (const changed of [
|
|
selection({ ownerId: 'B' }),
|
|
selection({ seriesId: 'missing' }),
|
|
selection({ instrumentId: 'X1.US' }),
|
|
]) {
|
|
expect(() => validateBuiltinStrategyBindings([changed], load)).toThrow();
|
|
}
|
|
expect(() =>
|
|
validateBuiltinStrategyBindings([...fixture.selections, ...fixture.selections], load)
|
|
).toThrow();
|
|
const wrongMode = structuredClone(load);
|
|
wrongMode.config.matching.owners[0]!.mode = 'Orders';
|
|
expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongMode)).toThrow();
|
|
const wrongCadence = structuredClone(load);
|
|
wrongCadence.config.cadence[0]!.series_ids = [];
|
|
expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongCadence)).toThrow();
|
|
});
|
|
|
|
test('owner_budget_sizing uses exact decimal whole shares, never account equity or a forced minimum', () => {
|
|
for (const [budget, prices, expected] of [
|
|
['0.3', ['0.2', '0.01', '0.1'], '3'],
|
|
['0.09', ['0.2', '0.01', '0.1'], '0'],
|
|
['9007199254740993', ['2', '0.5', '1'], '9007199254740993'],
|
|
] as const) {
|
|
const program = createBuiltinStrategy(
|
|
selection({ ownerBudget: d(budget), parameters: { fastPeriod: 1, slowPeriod: 2 } })
|
|
);
|
|
const result = decide(program, [...prices]);
|
|
expect(result.intent).toEqual({
|
|
mode: 'target',
|
|
targets: [{ instrumentId: 'X0.US', quantity: d(expected) }],
|
|
});
|
|
expect(JSON.stringify(result.nextState)).not.toContain('BigInt');
|
|
}
|
|
});
|
|
|
|
test('warmup requires a real crossover; target survives equality and a repeated golden cross until death', () => {
|
|
const program = createBuiltinStrategy(
|
|
selection({ parameters: { fastPeriod: 1, slowPeriod: 2 } })
|
|
);
|
|
expect(decide(program, ['1', '2']).intent).toEqual({ mode: 'target', targets: [] });
|
|
expect(decide(program, ['1', '2', '3']).intent).toEqual({ mode: 'target', targets: [] });
|
|
let result = decide(program, ['3', '1', '2']);
|
|
expect(result.nextState.targetQuantity).toBe(d('20'));
|
|
result = decide(program, ['2'], result.nextState, 3); // equality retains long
|
|
expect(result.nextState.targetQuantity).toBe(d('20'));
|
|
result = decide(program, ['4'], result.nextState, 4); // golden after equality must not resize to10
|
|
expect(result.nextState.targetQuantity).toBe(d('20'));
|
|
result = decide(program, ['1'], result.nextState, 5);
|
|
expect(result.nextState.targetQuantity).toBe(d('0'));
|
|
});
|
|
|
|
test('stale, missing, mismatched freshness and no-new inputs preserve GTC intent without new targets', () => {
|
|
const program = createBuiltinStrategy(selection());
|
|
const initial = decide(program, ['3', '2', '1', '4']);
|
|
for (const availability of [
|
|
'Missing',
|
|
{ Stale: { event_time: 5, available_at: 5 } },
|
|
{ Fresh: { event_time: 4, available_at: 4 } },
|
|
] as const) {
|
|
const input = context(initial.nextState, [observation('5', 4)]);
|
|
const result = program.decide({
|
|
...input,
|
|
barrier: { ...input.barrier, inputs: [{ series_id: 'X0.US:1m', availability }] },
|
|
});
|
|
expect(result.intent).toEqual({ mode: 'target', targets: [] });
|
|
expect(result.nextState.targetQuantity).toBe(d('10'));
|
|
}
|
|
expect(program.decide(context(initial.nextState, [])).intent).toEqual({
|
|
mode: 'target',
|
|
targets: [],
|
|
});
|
|
const delayed = observation('0.01', 1, { available_at: 10 });
|
|
const input = context(initial.nextState, [delayed], 10);
|
|
const result = program.decide({
|
|
...input,
|
|
barrier: {
|
|
...input.barrier,
|
|
inputs: [
|
|
{ series_id: 'X0.US:1m', availability: { Fresh: { event_time: 4, available_at: 4 } } },
|
|
],
|
|
},
|
|
});
|
|
expect(result.nextState).toEqual(initial.nextState);
|
|
expect(result.intent).toEqual({ mode: 'target', targets: [] });
|
|
expect(() => program.decide(context(initial.nextState, [observation('5', 4)], 4))).toThrow(
|
|
'availability'
|
|
);
|
|
});
|
|
|
|
test('sma_checkpoint_restore validates JSON state and reconstructs identical indicator decisions', () => {
|
|
const selected = selection();
|
|
const first = createBuiltinStrategy(selected);
|
|
const before = decide(first, ['3', '2', '1', '4']);
|
|
const restored = JSON.parse(JSON.stringify(before.nextState)) as SmaStrategyState;
|
|
expect(decide(createBuiltinStrategy(selected), ['5', '1'], restored, 4)).toEqual(
|
|
decide(first, ['5', '1'], before.nextState, 4)
|
|
);
|
|
expect(() => decide(first, ['5'], { ...restored, closes: [] }, 4)).toThrow();
|
|
expect(() =>
|
|
decide(createBuiltinStrategy(selection({ ownerId: 'B' })), ['5'], restored, 4)
|
|
).toThrow();
|
|
expect(() => decide(first, ['5'], { ...restored, targetQuantity: d('1.5') }, 4)).toThrow();
|
|
});
|
|
|
|
test('sma_next_open_trace buys and closes at eligible next opens with authoritative fees and exact equity', () => {
|
|
const fixture = canonicalSmaFixture();
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
validateBuiltinStrategyBindings(fixture.selections, load);
|
|
const run = (eventBudget: number) =>
|
|
runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
|
resultFormat: 'report',
|
|
eventBudget,
|
|
});
|
|
const first = run(1);
|
|
expect(run(64)).toEqual({ ...first, metrics: expect.anything() });
|
|
expect(first.result.projection.valuation.equity).toBe(d('9969.3'));
|
|
expect(first.result.projection.valuation.fees).toBe(d('0.7'));
|
|
expect(
|
|
first.result.projection.fills.map(fill => ({
|
|
price: fill.price,
|
|
quantityDelta: fill.quantityDelta,
|
|
}))
|
|
).toEqual([
|
|
{ price: d('5'), quantityDelta: d('10') },
|
|
{ price: d('2'), quantityDelta: d('-10') },
|
|
]);
|
|
});
|
|
|
|
test('warmup crossover sizes once at the first eligible fresh trading close and cannot fill during warmup', () => {
|
|
const fixture = canonicalSmaFixture(['A'], { tradeStartStep: 5 });
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
|
resultFormat: 'report',
|
|
});
|
|
expect(run.result.projection.fills.map(fill => [fill.eventTime, fill.quantityDelta])).toEqual([
|
|
[fixture.start + 5 * fixture.minute, d('8')],
|
|
[fixture.start + 6 * fixture.minute, d('-8')],
|
|
]);
|
|
expect(run.result.projection.valuation.equity).toBe(d('9975.44'));
|
|
});
|
|
|
|
test('canonical SMA cannot bypass native fee-inclusive funding or adverse-gap fill checks', () => {
|
|
for (const capital of ['40', '45']) {
|
|
const fixture = canonicalSmaFixture();
|
|
fixture.config.matching.risk.ledger.initialCapital = capital;
|
|
const run = runStrategyReplay(
|
|
prepareReplayLoad(fixture.dataset, fixture.config),
|
|
fixture.selections.map(createBuiltinStrategy),
|
|
{ resultFormat: 'report' }
|
|
);
|
|
expect(run.result.projection.fills).toEqual([]);
|
|
expect(run.result.projection.valuation.cash).toBe(d(capital));
|
|
const trace = runStrategyReplay(
|
|
prepareReplayLoad(fixture.dataset, fixture.config),
|
|
fixture.selections.map(createBuiltinStrategy),
|
|
{ resultFormat: 'trace' }
|
|
);
|
|
expect(JSON.stringify(trace.result.receipts)).toContain('InsufficientCash');
|
|
expect(run.diagnostics.strategies[0]!.state).toMatchObject({
|
|
lastCrossover: 'death',
|
|
targetQuantity: d('0'),
|
|
});
|
|
}
|
|
});
|
|
|
|
test('late older native observations cannot rewrite SMA history or alter its targets', () => {
|
|
const run = (lateClose: number) => {
|
|
const fixture = canonicalSmaFixture(['A'], {
|
|
closes: [3, lateClose, 1, 4, 5, 1, 1],
|
|
availabilitySteps: [1, 6, 3, 4, 5, 6, 7],
|
|
});
|
|
return runStrategyReplay(
|
|
prepareReplayLoad(fixture.dataset, fixture.config),
|
|
fixture.selections.map(createBuiltinStrategy),
|
|
{ resultFormat: 'report', eventBudget: 1 }
|
|
);
|
|
};
|
|
const first = run(2),
|
|
changed = run(200);
|
|
expect(changed.result.projection).toEqual(first.result.projection);
|
|
expect(changed.diagnostics.strategies).toEqual(first.diagnostics.strategies);
|
|
expect(first.result.projection.fills.map(fill => fill.quantityDelta)).toEqual([d('8'), d('-8')]);
|
|
});
|
|
|
|
test('repeating the desired target preserves the partially filled native order before a death closes owned inventory', () => {
|
|
const fixture = canonicalSmaFixture(['A'], { volume: 3 });
|
|
const run = runStrategyReplay(
|
|
prepareReplayLoad(fixture.dataset, fixture.config),
|
|
fixture.selections.map(createBuiltinStrategy),
|
|
{ resultFormat: 'report' }
|
|
);
|
|
const fills = run.result.projection.fills;
|
|
expect(fills.map(fill => fill.quantityDelta)).toEqual([d('3'), d('3'), d('-3')]);
|
|
expect(fills[0]!.orderId).toBe(fills[1]!.orderId);
|
|
expect(run.result.view.portfolio.positions[0]!.quantity).toBe(d('3'));
|
|
expect(run.result.projection.valuation.cash).toBe(d('9975.64'));
|
|
expect(run.result.projection.valuation.equity).toBe(d('9978.64'));
|
|
});
|
|
|
|
test('two owners sharing an asset keep independent targets, fills and P&L', () => {
|
|
const fixture = canonicalSmaFixture(['B', 'A']);
|
|
fixture.selections = fixture.selections.map(item =>
|
|
selection({ ...item, ownerBudget: d(item.ownerId === 'A' ? '40' : '20') })
|
|
);
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
validateBuiltinStrategyBindings(fixture.selections, load);
|
|
const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), {
|
|
resultFormat: 'report',
|
|
});
|
|
expect(run.result.projection.fills.map(fill => [fill.ownerId, fill.quantityDelta])).toEqual([
|
|
['A', d('10')],
|
|
['B', d('5')],
|
|
['A', d('-10')],
|
|
['B', d('-5')],
|
|
]);
|
|
expect(
|
|
run.result.projection.valuation.owners
|
|
.filter(owner => owner.ownerId !== 'reserve')
|
|
.map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees])
|
|
).toEqual([
|
|
['A', d('-30'), d('0.7')],
|
|
['B', d('-15'), d('0.35')],
|
|
]);
|
|
expect(run.result.projection.valuation.equity).toBe(d('9953.95'));
|
|
});
|
|
|
|
test('sma_checkpoint_restore whole-attempt retry after strategy failure recomputes identical decisions and economics', () => {
|
|
const fixture = canonicalSmaFixture();
|
|
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
|
const original = createBuiltinStrategy(fixture.selections[0]!);
|
|
const failing: StrategyProgram<SmaStrategyState> = {
|
|
...original,
|
|
decide(input) {
|
|
if (input.decisionSequence === 4) {
|
|
throw new Error('injected strategy failure');
|
|
}
|
|
return original.decide(input);
|
|
},
|
|
};
|
|
expect(() => runStrategyReplay(load, [failing], { resultFormat: 'report' })).toThrow(
|
|
StrategyReplayError
|
|
);
|
|
const baseline = runStrategyReplay(load, [createBuiltinStrategy(fixture.selections[0]!)], {
|
|
resultFormat: 'report',
|
|
eventBudget: 1,
|
|
});
|
|
const retried = runStrategyReplay(load, [original], { resultFormat: 'report', eventBudget: 7 });
|
|
expect(retried.result).toEqual(baseline.result);
|
|
expect(retried.diagnostics).toEqual(baseline.diagnostics);
|
|
expect(original.initialState.closes).toEqual([]);
|
|
});
|