continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
47
apps/stock/orchestrator/src/backtest/native-worker.ts
Normal file
47
apps/stock/orchestrator/src/backtest/native-worker.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { resolveNativeStrategies } from './native-strategies';
|
||||
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
|
||||
|
||||
/** 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 { config, data } = nativeWorkerRequestSchema.parse(input);
|
||||
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,
|
||||
});
|
||||
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));
|
||||
Loading…
Add table
Add a link
Reference in a new issue