55 lines
2.4 KiB
TypeScript
55 lines
2.4 KiB
TypeScript
import { normalizeBacktestStrategyConfig } from '@stock-bot/stock-config/backtest';
|
|
import {
|
|
nativeParameters,
|
|
typescriptMeanReversionParameters,
|
|
typescriptSmaParameters,
|
|
} from '../contracts/strategies';
|
|
import { builtinStrategy } from '../contracts/strategy-names';
|
|
import type { BacktestConfig } from '../types';
|
|
|
|
/** One precedence rule for both backends: shared defaults, then per-strategy overrides. */
|
|
export function backtestStrategies(config: BacktestConfig, backend: 'native' | 'typescript') {
|
|
const entries = config.strategies ?? [{ name: config.strategy, enabled: true, config: {} }];
|
|
if (!entries.some(entry => entry.enabled)) {
|
|
throw new Error('No enabled backtest strategies');
|
|
}
|
|
return entries
|
|
.filter(entry => entry.enabled)
|
|
.map((entry, index) => {
|
|
const kind = builtinStrategy(entry.name);
|
|
const merged = { ...config.config, ...entry.config };
|
|
// 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' &&
|
|
(typeof parsed.pairA !== 'string' ||
|
|
typeof parsed.pairB !== 'string' ||
|
|
!config.symbols.includes(parsed.pairA) ||
|
|
!config.symbols.includes(parsed.pairB))
|
|
) {
|
|
throw new Error('Both pair instruments must be included in backtest symbols');
|
|
}
|
|
return { name: entry.name, kind, index, parameters: parsed };
|
|
}
|
|
const context = { ...parameters, initialCapital: config.initialCapital };
|
|
const parsed =
|
|
kind === 'sma_crossover'
|
|
? typescriptSmaParameters.parse(context)
|
|
: kind === 'mean_reversion'
|
|
? typescriptMeanReversionParameters.parse(context)
|
|
: context;
|
|
return { name: entry.name, kind, index, parameters: parsed };
|
|
});
|
|
}
|