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
|
|
@ -465,6 +465,15 @@ Strategy-specific parameter validation remains with each execution backend. Inva
|
|||
execution settings now fail before a definition/run write rather than being queued for
|
||||
later rejection. Existing schema imports from the orchestrator remain compatibility exports.
|
||||
|
||||
`BacktestExecutionSettingsSchema` also identifies execution-only fields in legacy mixed
|
||||
`config` bags. After shared defaults and per-strategy overrides are merged, the common
|
||||
planner removes those fields before validating built-in parameters. For example,
|
||||
`dataFrequency` selects run input, not an indicator parameter; a per-strategy copy cannot
|
||||
override the run. Unknown parameter keys still fail validation. Custom TypeScript factories
|
||||
retain their existing extension-field contract. Original mixed configs remain unchanged in
|
||||
request snapshots and result provenance, including replay; no saved configuration migration
|
||||
or checkpoint-version change is required.
|
||||
|
||||
`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI.
|
||||
Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%).
|
||||
Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts
|
||||
|
|
|
|||
|
|
@ -33,12 +33,12 @@ export const RiskLimitsSchema = z.object({
|
|||
maxGrossExposure: z.number().finite().positive(),
|
||||
maxSymbolExposure: z.number().finite().positive(),
|
||||
});
|
||||
export const BacktestConfigSchema = z.object({
|
||||
/** Run-wide settings are owned here, never by an individual strategy's parameter bag. */
|
||||
export const BacktestExecutionSettingsSchema = z.object({
|
||||
mode: z.literal('backtest'),
|
||||
name: z.string().optional(),
|
||||
runId: z.string().uuid().optional(),
|
||||
backtestId: z.string().uuid().optional(),
|
||||
config: z.record(z.unknown()).optional(),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
symbols: z
|
||||
|
|
@ -49,16 +49,6 @@ export const BacktestConfigSchema = z.object({
|
|||
datasetHash: datasetHashSchema.optional(),
|
||||
initialCapital: z.number().finite().positive(),
|
||||
dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
strategy: z.string().min(1),
|
||||
strategies: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
enabled: z.boolean().default(true),
|
||||
config: z.record(z.unknown()).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
commission: z.number().finite().min(0).max(0.1).optional(),
|
||||
slippage: z.number().finite().min(0).max(0.1).optional(),
|
||||
fillModel: z
|
||||
|
|
@ -71,7 +61,45 @@ export const BacktestConfigSchema = z.object({
|
|||
speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max'),
|
||||
riskLimits: RiskLimitsSchema.optional(),
|
||||
});
|
||||
export const BacktestConfigSchema = BacktestExecutionSettingsSchema.extend({
|
||||
config: z.record(z.unknown()).optional(),
|
||||
strategy: z.string().min(1),
|
||||
strategies: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
enabled: z.boolean().default(true),
|
||||
config: z.record(z.unknown()).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
export type BacktestConfig = z.infer<typeof BacktestConfigSchema>;
|
||||
export type BacktestExecutionSettings = z.infer<typeof BacktestExecutionSettingsSchema>;
|
||||
|
||||
const executionSettingNames = new Set(Object.keys(BacktestExecutionSettingsSchema.shape));
|
||||
const legacyImplementationHint = z.boolean().optional();
|
||||
|
||||
export interface BacktestStrategyInput {
|
||||
parameters: Record<string, unknown>;
|
||||
/** Compatibility hint only: it never selects or changes the requested backend. */
|
||||
useTypeScriptImplementation?: boolean;
|
||||
}
|
||||
|
||||
/** Project a legacy mixed bag once at the request-to-built-in-strategy boundary.
|
||||
* Schema-owned execution settings cannot leak as parameters or override the run.
|
||||
* Unknown strategy keys remain visible so their strategy schema can reject typos. */
|
||||
export function normalizeBacktestStrategyConfig(
|
||||
input: Record<string, unknown>
|
||||
): BacktestStrategyInput {
|
||||
const { useTypeScriptImplementation, ...mixed } = input;
|
||||
return {
|
||||
parameters: Object.fromEntries(
|
||||
Object.entries(mixed).filter(([key]) => !executionSettingNames.has(key))
|
||||
),
|
||||
useTypeScriptImplementation: legacyImplementationHint.parse(useTypeScriptImplementation),
|
||||
};
|
||||
}
|
||||
|
||||
/** One acceptance/defaulting rule for API snapshots, direct execution and queued replay. */
|
||||
export function parseBacktestRequest(input: unknown): BacktestConfig {
|
||||
|
|
|
|||
|
|
@ -37,6 +37,15 @@ Built-ins cannot depend on experimental implementations. Parameter schemas live
|
|||
`backtest/strategy-plan.ts` gives both backends the same global-default/per-strategy-override
|
||||
precedence while retaining explicit backend-specific parameters and behavior.
|
||||
|
||||
Run-wide fields are defined by `BacktestExecutionSettingsSchema` in the portable
|
||||
`@stock-bot/stock-config/backtest` contract. The planner projects legacy mixed configs into
|
||||
built-in parameters using that schema; do not add another manual execution-field exclusion
|
||||
list. Per-strategy copies of execution settings never override the run. Unknown parameter
|
||||
keys remain visible to strict strategy validation. Custom TypeScript factories keep their
|
||||
factory-owned extension fields, and original request/result configs stay intact for replay.
|
||||
The legacy `useTypeScriptImplementation` hint never changes the selected backend; `true`
|
||||
is rejected by the native path.
|
||||
|
||||
Persisted aliases and checkpoint versions remain stable across this source relocation:
|
||||
SMA still reports `sma-crossover-fixed/v2`, and mean reversion reports
|
||||
`mean-reversion/v2`. The word `fixed` in the persisted version is compatibility metadata,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { normalizeBacktestStrategyConfig } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
nativeParameters,
|
||||
strategyParameters,
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../contracts/strategies';
|
||||
|
|
@ -18,12 +18,19 @@ export function backtestStrategies(config: BacktestConfig, backend: 'native' | '
|
|||
.map((entry, index) => {
|
||||
const kind = builtinStrategy(entry.name);
|
||||
const merged = { ...config.config, ...entry.config };
|
||||
// Custom TypeScript factories own their parameter contract; do not strip their extension fields.
|
||||
const parameters = kind ? strategyParameters(merged, backend) : structuredClone(merged);
|
||||
// Built-ins cross the shared execution/parameter boundary once, after merging defaults.
|
||||
// Custom TypeScript factories retain their historical, factory-owned extension contract.
|
||||
const input = kind
|
||||
? normalizeBacktestStrategyConfig(merged)
|
||||
: { parameters: structuredClone(merged) };
|
||||
const { parameters } = input;
|
||||
if (backend === 'native') {
|
||||
if (!kind) {
|
||||
throw new Error(`Unknown native strategy: ${entry.name}`);
|
||||
}
|
||||
if (input.useTypeScriptImplementation) {
|
||||
throw new Error('The native engine does not execute TypeScript strategy callbacks');
|
||||
}
|
||||
const parsed = nativeParameters(kind, parameters);
|
||||
if (
|
||||
kind === 'pairs_trading' &&
|
||||
|
|
|
|||
|
|
@ -86,32 +86,6 @@ export const nativePairsParameters = z
|
|||
.strict()
|
||||
.refine(value => value.pairA !== value.pairB, 'Pairs must use distinct instruments');
|
||||
|
||||
/** These are run settings, not strategy parameters. Preserve the original request in the result. */
|
||||
export function strategyParameters(
|
||||
input: Record<string, unknown>,
|
||||
backend: 'native' | 'typescript'
|
||||
): Record<string, unknown> {
|
||||
const {
|
||||
commission: _commission,
|
||||
slippage: _slippage,
|
||||
dataPolicy: _dataPolicy,
|
||||
datasetHash: _datasetHash,
|
||||
riskLimits: _riskLimits,
|
||||
fillModel: _fillModel,
|
||||
initialCapital: _initialCapital,
|
||||
symbols: _symbols,
|
||||
...parameters
|
||||
} = input;
|
||||
if (parameters.useTypeScriptImplementation !== undefined) {
|
||||
z.boolean().parse(parameters.useTypeScriptImplementation);
|
||||
if (backend === 'native' && parameters.useTypeScriptImplementation) {
|
||||
throw new Error('The native engine does not execute TypeScript strategy callbacks');
|
||||
}
|
||||
delete parameters.useTypeScriptImplementation;
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
export function nativeParameters(
|
||||
kind: BuiltinStrategy,
|
||||
input: Record<string, unknown>
|
||||
|
|
|
|||
|
|
@ -2,8 +2,10 @@ import { describe, expect, test } from 'bun:test';
|
|||
import {
|
||||
BACKTEST_DEFAULTS,
|
||||
BacktestConfigSchema,
|
||||
BacktestExecutionSettingsSchema,
|
||||
backtestRequestFromDefinition,
|
||||
isBacktestRequestError,
|
||||
normalizeBacktestStrategyConfig,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { parseBacktestRequest as runnerParser } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
|
|
@ -31,6 +33,31 @@ const definition = {
|
|||
};
|
||||
|
||||
describe('shared backtest request contract', () => {
|
||||
test('execution-owned fields are classified from their schema, not a second filtering list', () => {
|
||||
const settings = Object.fromEntries(
|
||||
Object.keys(BacktestExecutionSettingsSchema.shape).map(key => [key, 'execution-only'])
|
||||
);
|
||||
const input = {
|
||||
...settings,
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
featureWindow: 17,
|
||||
useTypeScriptImplementation: false,
|
||||
};
|
||||
const before = structuredClone(input);
|
||||
expect(normalizeBacktestStrategyConfig(input)).toEqual({
|
||||
parameters: { fastPeriod: 3, slowPeriod: 7, featureWindow: 17 },
|
||||
useTypeScriptImplementation: false,
|
||||
});
|
||||
expect(input).toEqual(before);
|
||||
expect(normalizeBacktestStrategyConfig({ fastPreriod: 3 }).parameters).toEqual({
|
||||
fastPreriod: 3,
|
||||
});
|
||||
expect(() =>
|
||||
normalizeBacktestStrategyConfig({ useTypeScriptImplementation: 'false' })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
test('runner and legacy schema exports delegate to the same pure contract', () => {
|
||||
expect(orchestratorSchema).toBe(BacktestConfigSchema);
|
||||
expect(runnerParser).toBe(parseBacktestRequest);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import {
|
||||
IncrementalSMA,
|
||||
BacktestEngine as NativeEngine,
|
||||
TechnicalIndicators,
|
||||
} from '@stock-bot/engine';
|
||||
import { BacktestExecutionSettingsSchema } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies';
|
||||
import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan';
|
||||
|
|
@ -20,11 +26,6 @@ import {
|
|||
normalizeStrategyName,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
|
|
@ -158,6 +159,74 @@ describe('explicit strategy contracts and shared planning', () => {
|
|||
expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('mixed execution settings never reach built-in parameters or alter run-wide precedence', () => {
|
||||
const mixed = {
|
||||
...config,
|
||||
config: {
|
||||
...BacktestExecutionSettingsSchema.parse(config),
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
useTypeScriptImplementation: false,
|
||||
},
|
||||
strategies: [
|
||||
{ name: 'disabled', enabled: false, config: {} },
|
||||
{
|
||||
name: 'sma',
|
||||
enabled: true,
|
||||
config: { slowPeriod: 9, dataFrequency: '1m', commission: 0.1 },
|
||||
},
|
||||
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 2 } },
|
||||
],
|
||||
};
|
||||
const before = structuredClone(mixed);
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
const plan = backtestStrategies(mixed, backend);
|
||||
expect(
|
||||
plan.map(entry => [entry.index, entry.parameters.fastPeriod, entry.parameters.slowPeriod])
|
||||
).toEqual([
|
||||
[0, 3, 9],
|
||||
[1, 2, 7],
|
||||
]);
|
||||
for (const entry of plan) {
|
||||
expect(entry.parameters).not.toHaveProperty('dataFrequency');
|
||||
expect(entry.parameters).not.toHaveProperty('commission');
|
||||
expect(entry.parameters).not.toHaveProperty('useTypeScriptImplementation');
|
||||
if (backend === 'typescript') {
|
||||
expect(entry.parameters.initialCapital).toBe(config.initialCapital);
|
||||
}
|
||||
}
|
||||
for (const parameters of [{ fastPreriod: 3 }, { dataFrequncy: '1d' }]) {
|
||||
expect(() => backtestStrategies({ ...config, config: parameters }, backend)).toThrow(
|
||||
'Unrecognized'
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(resolveNativeStrategies(mixed).map(entry => entry.id)).toEqual([
|
||||
'backtest-strategy-0',
|
||||
'backtest-strategy-1',
|
||||
]);
|
||||
expect(mixed).toEqual(before);
|
||||
expect(mixed.dataFrequency).toBe('1d');
|
||||
});
|
||||
|
||||
test('custom factories retain their existing extension bag, including names also used by execution', () => {
|
||||
const parameters = {
|
||||
vendorOption: { window: 9 },
|
||||
dataFrequency: 'feature cadence',
|
||||
commission: 12,
|
||||
};
|
||||
const custom = backtestStrategies(
|
||||
{ ...config, strategy: 'custom', config: parameters },
|
||||
'typescript'
|
||||
);
|
||||
expect(custom[0]?.parameters).toMatchObject({
|
||||
...parameters,
|
||||
initialCapital: config.initialCapital,
|
||||
});
|
||||
(custom[0]!.parameters.vendorOption as { window: number }).window = 100;
|
||||
expect(parameters.vendorOption.window).toBe(9);
|
||||
});
|
||||
|
||||
test('mean reversion and native-only strategies validate their actual, different contracts', () => {
|
||||
const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 });
|
||||
expect(mean.trendPeriod).toBe(80);
|
||||
|
|
|
|||
|
|
@ -234,10 +234,17 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
});
|
||||
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
|
||||
const f = await fixture();
|
||||
const parameters = {
|
||||
...f.definition.config,
|
||||
dataFrequency: '1d',
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
};
|
||||
await f.api.updateBacktest(f.definition.id, { config: parameters });
|
||||
const first = await f.runner.runQueued(
|
||||
(await f.api.createRun({ backtestId: f.definition.id })).id
|
||||
);
|
||||
const baseline = (await f.api.getRunResults(first.runId))!;
|
||||
expect(baseline.config.parameters).toEqual(parameters);
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadDataset(
|
||||
|
|
@ -260,6 +267,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const replay = (await f.api.getRunResults(run.id))!;
|
||||
expect(f.history.reads).toBe(reads);
|
||||
expect(replay.config.dataset).toEqual(baseline.config.dataset);
|
||||
expect(replay.config.parameters).toEqual(parameters);
|
||||
expect(replay.trades).toEqual(baseline.trades);
|
||||
expect(replay.metrics).toEqual(baseline.metrics);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue