feat(research): run trusted SMA strategies through native workers
This commit is contained in:
parent
4f6e44a853
commit
ca5abdde0e
16 changed files with 1682 additions and 28 deletions
|
|
@ -8,6 +8,10 @@ import {
|
|||
replayIdentitySchema,
|
||||
replayResultFormatSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../contracts/strategy-replay';
|
||||
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
||||
|
|
@ -31,18 +35,25 @@ export class NativeBacktestWorker {
|
|||
if (this.active) {
|
||||
throw new BacktestConflictError('A native backtest worker is already running');
|
||||
}
|
||||
// Detach the entire normalized strategy request, including the frozen-data
|
||||
// payload. The caller must not mutate what is sent or what counts as success.
|
||||
const strategyRequest =
|
||||
request.type === 'runStrategyReplay'
|
||||
? structuredClone(strategyReplayRequestSchema.parse(request))
|
||||
: undefined;
|
||||
const submitted = strategyRequest ?? request;
|
||||
// Capture expected identity/policy before asynchronous execution. A caller
|
||||
// mutating its request cannot change which completed child result is valid.
|
||||
const expectedReplay =
|
||||
request.type === 'runReplayTrace'
|
||||
submitted.type === 'runReplayTrace' || submitted.type === 'runStrategyReplay'
|
||||
? {
|
||||
identity: replayIdentitySchema.parse({
|
||||
version: 1,
|
||||
sessionId: request.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
sessionId: submitted.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (submitted.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
}),
|
||||
policy: replayConfigSchema.parse(request.config),
|
||||
format: replayResultFormatSchema.parse(request.resultFormat ?? 'trace'),
|
||||
policy: replayConfigSchema.parse(submitted.config),
|
||||
format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'),
|
||||
}
|
||||
: undefined;
|
||||
const child = fork(fileURLToPath(this.workerUrl), [], {
|
||||
|
|
@ -85,13 +96,20 @@ export class NativeBacktestWorker {
|
|||
} else if (message.type === 'result') {
|
||||
if (expectedReplay) {
|
||||
try {
|
||||
const parse =
|
||||
expectedReplay.format === 'report'
|
||||
? parseReplayReportResult
|
||||
: expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
if (strategyRequest) {
|
||||
parseStrategyReplayResult(message.result, {
|
||||
...expectedReplay,
|
||||
strategies: strategyRequest.strategies,
|
||||
});
|
||||
} else {
|
||||
const parse =
|
||||
expectedReplay.format === 'report'
|
||||
? parseReplayReportResult
|
||||
: expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
}
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
|
|
@ -144,7 +162,7 @@ export class NativeBacktestWorker {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
child.send(request, error => {
|
||||
child.send(submitted, error => {
|
||||
if (error) {
|
||||
terminate(error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import { replayTraceSchema } from '../contracts/native-replay';
|
||||
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
|
||||
import { BacktestConfigSchema } from '../types';
|
||||
|
||||
const finite = z.number().finite();
|
||||
|
|
@ -21,7 +22,11 @@ const legacyRequestSchema = z.object({
|
|||
),
|
||||
});
|
||||
|
||||
export const nativeWorkerRequestSchema = z.union([legacyRequestSchema, replayTraceSchema]);
|
||||
export const nativeWorkerRequestSchema = z.union([
|
||||
legacyRequestSchema,
|
||||
replayTraceSchema,
|
||||
strategyReplayRequestSchema,
|
||||
]);
|
||||
|
||||
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
|
||||
|
|
@ -29,5 +34,5 @@ export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
|||
z.object({ type: z.literal('error'), message: z.string() }),
|
||||
]);
|
||||
|
||||
export type NativeWorkerRequest = z.infer<typeof nativeWorkerRequestSchema>;
|
||||
export type NativeWorkerRequest = z.input<typeof nativeWorkerRequestSchema>;
|
||||
export type NativeWorkerMessage = z.infer<typeof nativeWorkerMessageSchema>;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { executeReplayTrace } from './native-replay';
|
||||
import type { StrategyReplayResult } from '../contracts/strategy-replay';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../strategies/canonical-sma';
|
||||
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
|
||||
import { resolveNativeStrategies } from './native-strategies';
|
||||
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
|
||||
import { runStrategyReplay } from './strategy-runtime';
|
||||
|
||||
/** One process, one native engine, one request. No database or service-container access. */
|
||||
function send(message: NativeWorkerMessage): Promise<void> {
|
||||
|
|
@ -17,6 +23,36 @@ function send(message: NativeWorkerMessage): Promise<void> {
|
|||
process.once('message', async (input: unknown) => {
|
||||
try {
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
if (request.type === 'runStrategyReplay') {
|
||||
const load = prepareReplayLoad(request.dataset, request.config);
|
||||
validateBuiltinStrategyBindings(request.strategies, load);
|
||||
const programs = request.strategies.map(selection => {
|
||||
const program = createBuiltinStrategy(selection);
|
||||
if (
|
||||
program.ownerId !== selection.ownerId ||
|
||||
program.strategyId !== selection.strategyId ||
|
||||
program.strategyVersion !== selection.strategyVersion ||
|
||||
program.seed !== selection.seed ||
|
||||
program.mode !== 'target'
|
||||
) {
|
||||
throw new Error('Trusted strategy constructor identity mismatch');
|
||||
}
|
||||
return program;
|
||||
});
|
||||
await send({ type: 'progress', progress: 0, message: 'Canonical strategy replay started' });
|
||||
const { result } = runStrategyReplay(load, programs, {
|
||||
eventBudget: request.eventBudget,
|
||||
resultFormat: request.resultFormat,
|
||||
});
|
||||
const envelope: StrategyReplayResult = {
|
||||
type: 'strategyReplayResult',
|
||||
version: 1,
|
||||
strategies: request.strategies,
|
||||
result,
|
||||
};
|
||||
await send({ type: 'result', result: JSON.stringify(envelope) });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'runReplayTrace') {
|
||||
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
|
||||
// One load and a local pull loop; no per-observation IPC. The supervisor
|
||||
|
|
|
|||
51
apps/stock/orchestrator/src/contracts/builtin-strategy.ts
Normal file
51
apps/stock/orchestrator/src/contracts/builtin-strategy.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
/** Trusted built-in selection only. No callbacks, code paths or checkpoint transport. */
|
||||
import { z } from 'zod';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { maxStrategyPeriod } from './strategies';
|
||||
import { builtinStrategy } from './strategy-names';
|
||||
|
||||
const identity = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(value =>
|
||||
[...value].every(character => {
|
||||
const code = character.charCodeAt(0);
|
||||
return (
|
||||
code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff)
|
||||
);
|
||||
})
|
||||
);
|
||||
const period = z.number().int().min(1).max(maxStrategyPeriod);
|
||||
|
||||
export const builtinStrategySelectionSchema = z
|
||||
.object({
|
||||
ownerId: identity,
|
||||
strategyId: z
|
||||
.string()
|
||||
.refine(value => builtinStrategy(value) === 'sma_crossover', 'Unsupported canonical strategy')
|
||||
.transform(() => 'sma_crossover' as const),
|
||||
strategyVersion: z.literal('sma-crossover-long-only/v1'),
|
||||
seed: z.number().int().min(0).max(0xffffffff),
|
||||
instrumentId: identity,
|
||||
seriesId: identity,
|
||||
ownerBudget: z
|
||||
.string()
|
||||
.transform(value => parseFinancialDecimal(value))
|
||||
.refine(
|
||||
value => !value.startsWith('-') && value !== '0.00000000',
|
||||
'Owner budget must be positive'
|
||||
),
|
||||
parameters: z
|
||||
.object({
|
||||
fastPeriod: period.default(5),
|
||||
slowPeriod: period.min(2).default(15),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
value => value.fastPeriod < value.slowPeriod,
|
||||
'SMA fastPeriod must be below slowPeriod'
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type BuiltinStrategySelection = z.infer<typeof builtinStrategySelectionSchema>;
|
||||
72
apps/stock/orchestrator/src/contracts/strategy-replay.ts
Normal file
72
apps/stock/orchestrator/src/contracts/strategy-replay.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
/** Data-only trusted built-in execution protocol; no strategy code or native imports. */
|
||||
import { z } from 'zod';
|
||||
import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from './builtin-strategy';
|
||||
import {
|
||||
parseReplayProjectionValue,
|
||||
parseReplayReportValue,
|
||||
parseReplayResultValue,
|
||||
replayConfigSchema,
|
||||
replayResultFormatSchema,
|
||||
type ReplayConfig,
|
||||
type ReplayIdentity,
|
||||
type ReplayOutput,
|
||||
type ReplayResultFormat,
|
||||
} from './native-replay';
|
||||
|
||||
export const strategyReplayRequestSchema = z
|
||||
.object({
|
||||
type: z.literal('runStrategyReplay'),
|
||||
version: z.literal(1),
|
||||
dataset: z.unknown(),
|
||||
config: replayConfigSchema,
|
||||
eventBudget: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
||||
resultFormat: replayResultFormatSchema.optional(),
|
||||
strategies: z.array(builtinStrategySelectionSchema).min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type StrategyReplayRequest = z.input<typeof strategyReplayRequestSchema>;
|
||||
|
||||
const strategyReplayResultSchema = z
|
||||
.object({
|
||||
type: z.literal('strategyReplayResult'),
|
||||
version: z.literal(1),
|
||||
strategies: z.array(builtinStrategySelectionSchema).min(1),
|
||||
result: z.unknown(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export interface StrategyReplayResult {
|
||||
type: 'strategyReplayResult';
|
||||
version: 1;
|
||||
strategies: BuiltinStrategySelection[];
|
||||
result: ReplayOutput;
|
||||
}
|
||||
|
||||
export interface StrategyReplayExpectation {
|
||||
strategies: readonly BuiltinStrategySelection[];
|
||||
identity: ReplayIdentity;
|
||||
policy: ReplayConfig;
|
||||
format: ReplayResultFormat;
|
||||
}
|
||||
|
||||
/** Strategy selection is additional provenance; Rust remains the only result authority. */
|
||||
export function parseStrategyReplayResult(
|
||||
input: string,
|
||||
expected: StrategyReplayExpectation
|
||||
): StrategyReplayResult {
|
||||
const envelope = strategyReplayResultSchema.parse(JSON.parse(input));
|
||||
if (JSON.stringify(envelope.strategies) !== JSON.stringify(expected.strategies)) {
|
||||
throw new Error('Native strategy replay selection mismatch');
|
||||
}
|
||||
const parse =
|
||||
expected.format === 'report'
|
||||
? parseReplayReportValue
|
||||
: expected.format === 'projection'
|
||||
? parseReplayProjectionValue
|
||||
: parseReplayResultValue;
|
||||
return {
|
||||
...envelope,
|
||||
result: parse(envelope.result, expected.identity, expected.policy),
|
||||
};
|
||||
}
|
||||
200
apps/stock/orchestrator/src/strategies/canonical-sma.ts
Normal file
200
apps/stock/orchestrator/src/strategies/canonical-sma.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import { z } from 'zod';
|
||||
import { movingAverageCrossover } from '@stock-bot/calculations/indicators';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
type FinancialDecimal,
|
||||
type HistoricalDatasetManifestV2,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
type BuiltinStrategySelection,
|
||||
} from '../contracts/builtin-strategy';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { ReplayConfig } from '../contracts/native-replay';
|
||||
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const decimal = z.string().transform(value => parseFinancialDecimal(value));
|
||||
const nonnegative = decimal.refine(value => !value.startsWith('-'));
|
||||
const positive = nonnegative.refine(value => value !== '0.00000000');
|
||||
|
||||
export interface SmaStrategyState {
|
||||
version: 1;
|
||||
selectionKey: string;
|
||||
closes: number[];
|
||||
lastObservation: {
|
||||
eventTime: number;
|
||||
availableAt: number;
|
||||
sourceSequence: number;
|
||||
close: FinancialDecimal;
|
||||
} | null;
|
||||
lastCrossover: 'golden' | 'death' | null;
|
||||
targetQuantity: FinancialDecimal | null;
|
||||
}
|
||||
|
||||
/** Validate dataset/cadence membership before opening the native session. */
|
||||
export function validateBuiltinStrategyBindings(
|
||||
selections: readonly BuiltinStrategySelection[],
|
||||
load: { config: ReplayConfig; manifest: Pick<HistoricalDatasetManifestV2, 'series'> }
|
||||
): void {
|
||||
const parsed = selections.map(selection => builtinStrategySelectionSchema.parse(selection));
|
||||
const owners = load.config.matching.owners;
|
||||
if (
|
||||
new Set(parsed.map(selection => selection.ownerId)).size !== parsed.length ||
|
||||
parsed.length !== owners.length ||
|
||||
owners.some(owner => owner.mode !== 'Target' || !parsed.some(s => s.ownerId === owner.ownerId))
|
||||
) {
|
||||
throw new Error('Canonical built-ins must exactly match target-mode owners');
|
||||
}
|
||||
for (const selection of parsed) {
|
||||
const series = load.manifest.series.find(item => item.id === selection.seriesId);
|
||||
const cadence = load.config.cadence.filter(item => item.owner_id === selection.ownerId);
|
||||
if (
|
||||
series?.instrumentId !== selection.instrumentId ||
|
||||
!load.config.matching.series.some(item => item.instrumentId === selection.instrumentId) ||
|
||||
cadence.length !== 1 ||
|
||||
!cadence[0]?.series_ids.includes(selection.seriesId)
|
||||
) {
|
||||
throw new Error('Canonical SMA requires its instrument/series in its owner cadence');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whole-share intent sizing only. Rust remains authoritative for all financial effects. */
|
||||
function desiredShares(budget: FinancialDecimal, price: FinancialDecimal): FinancialDecimal {
|
||||
const units = (value: FinancialDecimal) => BigInt(value.replace('.', ''));
|
||||
return parseFinancialDecimal((units(budget) / units(price)).toString());
|
||||
}
|
||||
|
||||
/** One explicitly versioned long-only program; legacy factories remain unchanged. */
|
||||
export function createBuiltinStrategy(
|
||||
selectionInput: BuiltinStrategySelection
|
||||
): StrategyProgram<SmaStrategyState> {
|
||||
const selection = builtinStrategySelectionSchema.parse(selectionInput);
|
||||
const { fastPeriod, slowPeriod } = selection.parameters;
|
||||
const selectionKey = JSON.stringify(selection);
|
||||
const stateSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
selectionKey: z.literal(selectionKey),
|
||||
closes: z.array(z.number().finite().positive()).max(slowPeriod + 1),
|
||||
lastObservation: z
|
||||
.object({
|
||||
eventTime: time,
|
||||
availableAt: time,
|
||||
sourceSequence: counter,
|
||||
close: positive,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.availableAt >= value.eventTime)
|
||||
.nullable(),
|
||||
lastCrossover: z.enum(['golden', 'death']).nullable(),
|
||||
targetQuantity: nonnegative.refine(value => value.endsWith('.00000000')).nullable(),
|
||||
})
|
||||
.strict()
|
||||
.refine(state => {
|
||||
if (!state.lastObservation) {
|
||||
return (
|
||||
state.closes.length === 0 && state.lastCrossover === null && state.targetQuantity === null
|
||||
);
|
||||
}
|
||||
if (state.closes.at(-1) !== Number(state.lastObservation.close)) {
|
||||
return false;
|
||||
}
|
||||
if (state.lastCrossover === null) {
|
||||
return state.targetQuantity === null;
|
||||
}
|
||||
if (state.closes.length !== slowPeriod + 1) {
|
||||
return false;
|
||||
}
|
||||
return state.lastCrossover !== 'death' || state.targetQuantity === '0.00000000';
|
||||
}, 'Inconsistent SMA checkpoint');
|
||||
|
||||
return {
|
||||
ownerId: selection.ownerId,
|
||||
strategyId: selection.strategyId,
|
||||
strategyVersion: selection.strategyVersion,
|
||||
seed: selection.seed,
|
||||
mode: 'target',
|
||||
initialState: {
|
||||
version: 1,
|
||||
selectionKey,
|
||||
closes: [],
|
||||
lastObservation: null,
|
||||
lastCrossover: null,
|
||||
targetQuantity: null,
|
||||
},
|
||||
decide(context) {
|
||||
const nextState = stateSchema.parse(context.state);
|
||||
let advanced = false;
|
||||
for (const observation of context.observations) {
|
||||
if (observation.series_id !== selection.seriesId) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
observation.instrument_id !== selection.instrumentId ||
|
||||
observation.available_at > context.now
|
||||
) {
|
||||
throw new Error('Canonical SMA observation binding or availability mismatch');
|
||||
}
|
||||
const previous = nextState.lastObservation;
|
||||
// Arrival order is authoritative. A delayed older event cannot rewrite evaluated history.
|
||||
if (
|
||||
previous &&
|
||||
(observation.event_time < previous.eventTime ||
|
||||
(observation.event_time === previous.eventTime &&
|
||||
observation.source_sequence <= previous.sourceSequence))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const close = positive.parse(observation.close);
|
||||
nextState.closes.push(Number(close));
|
||||
if (nextState.closes.length > slowPeriod + 1) {
|
||||
nextState.closes.shift();
|
||||
}
|
||||
nextState.lastObservation = {
|
||||
eventTime: observation.event_time,
|
||||
availableAt: observation.available_at,
|
||||
sourceSequence: observation.source_sequence,
|
||||
close,
|
||||
};
|
||||
advanced = true;
|
||||
const cross = movingAverageCrossover(nextState.closes, fastPeriod, slowPeriod);
|
||||
if (cross?.goldenCross && nextState.lastCrossover !== 'golden') {
|
||||
nextState.lastCrossover = 'golden';
|
||||
nextState.targetQuantity = null;
|
||||
} else if (cross?.deathCross) {
|
||||
nextState.lastCrossover = 'death';
|
||||
nextState.targetQuantity = parseFinancialDecimal('0');
|
||||
}
|
||||
}
|
||||
const input = context.barrier.inputs.find(item => item.series_id === selection.seriesId);
|
||||
const availability = input?.availability;
|
||||
const last = nextState.lastObservation;
|
||||
const fresh =
|
||||
typeof availability === 'object' && 'Fresh' in availability ? availability.Fresh : null;
|
||||
if (
|
||||
!advanced ||
|
||||
!last ||
|
||||
!fresh ||
|
||||
fresh.event_time !== last.eventTime ||
|
||||
fresh.available_at !== last.availableAt
|
||||
) {
|
||||
return { nextState, intent: { mode: 'target', targets: [] } };
|
||||
}
|
||||
if (nextState.lastCrossover === 'golden' && nextState.targetQuantity === null) {
|
||||
nextState.targetQuantity = desiredShares(selection.ownerBudget, last.close);
|
||||
}
|
||||
return {
|
||||
nextState,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets:
|
||||
nextState.targetQuantity === null
|
||||
? []
|
||||
: [{ instrumentId: selection.instrumentId, quantity: nextState.targetQuantity }],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue