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
|
|
@ -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>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue