Separate backtest execution settings from strategy parameters
This commit is contained in:
parent
420c47704e
commit
e4925ecdfe
9 changed files with 283 additions and 48 deletions
|
|
@ -24,6 +24,7 @@ import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/
|
|||
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
||||
import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/backtest/backtest.handler';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestRoutes as createV1Routes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
|
|
@ -34,6 +35,7 @@ import {
|
|||
createWebSocketHandler,
|
||||
type RunUpdateMessage,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
import { CounterStrategy } from '../fixtures/strategy-recovery';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('workflow-test');
|
||||
|
|
@ -145,7 +147,10 @@ async function fixture(
|
|||
return { postgres, mongodb, storage, engine, repository, runner, services, routes };
|
||||
}
|
||||
|
||||
async function typescriptRuntime(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
async function typescriptRuntime(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
strategyRegistry?: StrategyRegistry
|
||||
) {
|
||||
const di = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
|
|
@ -164,12 +169,111 @@ async function typescriptRuntime(f: Awaited<ReturnType<typeof fixture>>) {
|
|||
custom: {},
|
||||
};
|
||||
di.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false });
|
||||
await registerOrchestratorServices(di, {
|
||||
initializeMode: false,
|
||||
useRustEngine: false,
|
||||
strategyRegistry,
|
||||
});
|
||||
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
|
||||
return services;
|
||||
}
|
||||
|
||||
describe('one backtest execution workflow', () => {
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => {
|
||||
const f = await fixture();
|
||||
const services = backend === 'typescript' ? await typescriptRuntime(f) : f.services;
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
if (backend === 'typescript')
|
||||
await (services as OrchestratorServices).custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const api = new BacktestServiceV2(services);
|
||||
const parameters = {
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
};
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: 'Mixed parameters', config: parameters },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id });
|
||||
const before = (
|
||||
await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0]!.request_snapshot;
|
||||
const result = await runner.runQueued(run.id);
|
||||
const saved = (await api.getRunResults(result.runId))!;
|
||||
expect(saved.engine).toBe(backend);
|
||||
expect(saved.trades.length).toBeGreaterThan(0);
|
||||
expect(saved.config.parameters).toEqual(parameters);
|
||||
expect(saved.config.dataFrequency).toBe('1d');
|
||||
expect(saved.config.commission).toBe(0);
|
||||
const request = {
|
||||
...before,
|
||||
runId: undefined,
|
||||
backtestId: undefined,
|
||||
datasetHash: saved.config.dataset!.hash,
|
||||
};
|
||||
const replayed = await runner.runBacktest(request);
|
||||
expect(replayed.config.parameters).toEqual(parameters);
|
||||
expect(replayed.config.dataset).toEqual(saved.config.dataset);
|
||||
expect(replayed.trades).toEqual(saved.trades);
|
||||
expect(replayed.metrics).toEqual(saved.metrics);
|
||||
expect(
|
||||
(await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id]))
|
||||
.rows[0]!.request_snapshot
|
||||
).toEqual(before);
|
||||
if (backend === 'typescript') {
|
||||
const strategies = (
|
||||
services as OrchestratorServices
|
||||
).custom!.StrategyManager!.getAllStrategies();
|
||||
expect(strategies[0]!.getConfig().parameters).not.toHaveProperty('dataFrequency');
|
||||
expect(strategies[0]!.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('custom strategy extension fields survive the full API and TypeScript workflow', async () => {
|
||||
const f = await fixture();
|
||||
const seen: Record<string, unknown>[] = [];
|
||||
const registry = new StrategyRegistry().register(
|
||||
['custom-fixture'],
|
||||
(definition, dependencies) => {
|
||||
seen.push(structuredClone(definition.parameters));
|
||||
return new CounterStrategy(dependencies.execution, definition);
|
||||
}
|
||||
);
|
||||
const services = await typescriptRuntime(f, registry);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const parameters = {
|
||||
vendorFeature: { window: 17, version: 'v1' },
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
};
|
||||
const api = new BacktestServiceV2(services);
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: 'Custom extension', strategy: 'custom-fixture', config: parameters },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id });
|
||||
await runner.runQueued(run.id);
|
||||
expect((await api.getRunResults(run.id))?.config.parameters).toEqual(parameters);
|
||||
expect(seen[0]).toMatchObject({ ...parameters, initialCapital: config.initialCapital });
|
||||
expect(services.custom!.StrategyManager!.getAllStrategies()[0]!.getCheckpointVersion()).toBe(
|
||||
'counter/v1'
|
||||
);
|
||||
});
|
||||
|
||||
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
|
||||
const f = await fixture();
|
||||
const api = createBacktestV2Routes(f.services);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue