96 lines
4 KiB
TypeScript
96 lines
4 KiB
TypeScript
import { BacktestEngine } from '@stock-bot/engine';
|
|
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> {
|
|
return new Promise((resolve, reject) => {
|
|
if (!process.send) {
|
|
reject(new Error('Native backtest worker requires an IPC channel'));
|
|
return;
|
|
}
|
|
process.send(message, (error: Error | null) => (error ? reject(error) : resolve()));
|
|
});
|
|
}
|
|
|
|
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
|
|
// can still SIGKILL native work, exactly as for the legacy one-shot path.
|
|
const { result } = executeReplayTrace(request);
|
|
await send({ type: 'result', result: JSON.stringify(result) });
|
|
return;
|
|
}
|
|
const { config, data } = request;
|
|
const engine = new BacktestEngine({
|
|
name: config.name ?? 'Backtest',
|
|
strategy: config.strategy,
|
|
symbols: config.symbols,
|
|
startDate: config.startDate,
|
|
endDate: config.endDate,
|
|
initialCapital: config.initialCapital,
|
|
commission: config.commission ?? 0.001,
|
|
slippage: config.slippage ?? 0.0001,
|
|
dataFrequency: config.dataFrequency,
|
|
});
|
|
if (config.riskLimits) {
|
|
engine.updateRiskLimits(config.riskLimits);
|
|
}
|
|
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
|
|
engine.addNativeStrategy(strategy, name, id, parameters);
|
|
}
|
|
data.sort((a, b) => a.timestamp - b.timestamp);
|
|
engine.loadMarketData(data);
|
|
await send({ type: 'progress', progress: 0, message: 'Native execution started' });
|
|
// This synchronous call is deliberately confined to the child process.
|
|
await send({ type: 'result', result: engine.run() });
|
|
} catch (error) {
|
|
await send({ type: 'error', message: error instanceof Error ? error.message : String(error) });
|
|
process.exitCode = 1;
|
|
} finally {
|
|
process.disconnect?.();
|
|
}
|
|
});
|
|
|
|
// Exit on parent disconnection once control returns from native code.
|
|
process.once('disconnect', () => process.exit(process.exitCode ?? 0));
|