Centralize strategy contracts and share indicator calculations
This commit is contained in:
parent
366d39001b
commit
4207bf2c1c
25 changed files with 1323 additions and 477 deletions
131
apps/stock/orchestrator/src/contracts/strategies.ts
Normal file
131
apps/stock/orchestrator/src/contracts/strategies.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import { z } from 'zod';
|
||||
import { instrumentIdSchema } from './historical';
|
||||
import type { BuiltinStrategy } from './strategy-names';
|
||||
|
||||
export const maxStrategyPeriod = 10000;
|
||||
const period = z.number().finite().int().min(1).max(maxStrategyPeriod);
|
||||
const positive = z.number().finite().positive();
|
||||
const quantity = positive.min(1e-8).max(1e9);
|
||||
const context = {
|
||||
initialCapital: positive.optional(),
|
||||
symbols: z.array(z.string()).optional(),
|
||||
};
|
||||
const smaPeriods = { fastPeriod: period.default(5), slowPeriod: period.min(2).default(15) };
|
||||
const validSma = (value: { fastPeriod: number; slowPeriod: number }) =>
|
||||
value.fastPeriod < value.slowPeriod;
|
||||
const smaMessage = 'SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000';
|
||||
|
||||
export const typescriptSmaParameters = z
|
||||
.object({
|
||||
...context,
|
||||
...smaPeriods,
|
||||
positionFraction: positive.max(1).default(0.1),
|
||||
minHoldingBars: z.number().int().min(0).max(maxStrategyPeriod).default(3),
|
||||
quantity: quantity.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(validSma, smaMessage);
|
||||
export const nativeSmaParameters = z
|
||||
.object({ ...smaPeriods, quantity: quantity.default(100) })
|
||||
.strict()
|
||||
.refine(validSma, smaMessage);
|
||||
export type SmaParameters = z.infer<typeof typescriptSmaParameters>;
|
||||
|
||||
export const typescriptMeanReversionParameters = z
|
||||
.object({
|
||||
...context,
|
||||
lookbackPeriod: period.min(2).default(20),
|
||||
trendPeriod: period.optional(),
|
||||
entryThreshold: positive.default(2),
|
||||
exitZScore: z.number().finite().min(0).default(0.5),
|
||||
rsiPeriod: period.default(14),
|
||||
rsiOversold: z.number().finite().min(0).max(100).default(30),
|
||||
rsiOverbought: z.number().finite().min(0).max(100).default(70),
|
||||
minNotionalVolume: z.number().finite().min(0).default(1000000),
|
||||
quantity: quantity.optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
value => value.exitZScore < value.entryThreshold,
|
||||
'exitZScore must be below entryThreshold'
|
||||
)
|
||||
.refine(
|
||||
value => value.rsiOversold < value.rsiOverbought,
|
||||
'rsiOversold must be below rsiOverbought'
|
||||
)
|
||||
.refine(
|
||||
value => value.trendPeriod === undefined || value.trendPeriod >= value.lookbackPeriod,
|
||||
'trendPeriod must be at least lookbackPeriod'
|
||||
)
|
||||
.transform(value => ({
|
||||
...value,
|
||||
trendPeriod: value.trendPeriod ?? Math.max(50, value.lookbackPeriod),
|
||||
}));
|
||||
export type MeanReversionParameters = z.infer<typeof typescriptMeanReversionParameters>;
|
||||
|
||||
const nativeMean = {
|
||||
lookbackPeriod: period.min(2).default(20),
|
||||
entryThreshold: positive.default(2),
|
||||
// Native mean/momentum/pairs retain their existing absolute-share positionSize contract.
|
||||
positionSize: quantity.default(100),
|
||||
};
|
||||
export const nativeMeanReversionParameters = z.object(nativeMean).strict();
|
||||
export const nativeMomentumParameters = z
|
||||
.object({
|
||||
lookbackPeriod: period.default(14),
|
||||
momentumThreshold: positive.default(5),
|
||||
positionSize: quantity.default(100),
|
||||
})
|
||||
.strict();
|
||||
export const nativePairsParameters = z
|
||||
.object({
|
||||
...nativeMean,
|
||||
pairA: instrumentIdSchema,
|
||||
pairB: instrumentIdSchema,
|
||||
})
|
||||
.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>
|
||||
): Record<string, unknown> {
|
||||
switch (kind) {
|
||||
case 'sma_crossover':
|
||||
return nativeSmaParameters.parse(input);
|
||||
case 'mean_reversion':
|
||||
return nativeMeanReversionParameters.parse(input);
|
||||
case 'momentum':
|
||||
return nativeMomentumParameters.parse(input);
|
||||
case 'pairs_trading':
|
||||
return nativePairsParameters.parse(input);
|
||||
default:
|
||||
throw new Error(`Unsupported native strategy: ${kind}`);
|
||||
}
|
||||
}
|
||||
20
apps/stock/orchestrator/src/contracts/strategy-names.ts
Normal file
20
apps/stock/orchestrator/src/contracts/strategy-names.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
export function normalizeStrategyName(name: string): string {
|
||||
return name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\s_-]/g, '');
|
||||
}
|
||||
export const strategyAliases = {
|
||||
sma_crossover: ['sma', 'smacrossover', 'simplemovingaveragecrossover', 'movingaverage'],
|
||||
mean_reversion: ['meanreversion'],
|
||||
momentum: ['momentum'],
|
||||
pairs_trading: ['pairs', 'pairstrading'],
|
||||
ml_enhanced: ['mlenhanced'],
|
||||
} as const;
|
||||
export type BuiltinStrategy = keyof typeof strategyAliases;
|
||||
export function builtinStrategy(name: string): BuiltinStrategy | undefined {
|
||||
const normalized = normalizeStrategyName(name);
|
||||
return (Object.keys(strategyAliases) as BuiltinStrategy[]).find(kind =>
|
||||
(strategyAliases[kind] as readonly string[]).includes(normalized)
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue