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
|
|
@ -12,6 +12,7 @@ import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
|||
import { BacktestReport } from './BacktestReport';
|
||||
import type { BacktestExecutionEngine } from './execution-engine';
|
||||
import { closedTradesSchema } from './native-result';
|
||||
import { backtestStrategies } from './strategy-plan';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
export type { BacktestResult } from './typescript-result';
|
||||
|
|
@ -57,6 +58,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
playback: BacktestPlayback,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<BacktestResult> {
|
||||
const plan = backtestStrategies(config, 'typescript');
|
||||
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||
const dataset = await playback.read(() =>
|
||||
resolveDataset(this.storageService, config, resolver)
|
||||
|
|
@ -64,27 +66,14 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
playback.assertRunning();
|
||||
const dataManager = new DataManager(this.storageService);
|
||||
dataManager.inspectDataset(dataset);
|
||||
const strategies = config.strategies?.map((strategy, index) => ({
|
||||
id: [strategy.name, index].join('-'),
|
||||
name: strategy.name,
|
||||
enabled: strategy.enabled,
|
||||
parameters: { ...strategy.config, initialCapital: config.initialCapital },
|
||||
const strategies = plan.map(({ name, parameters, index }) => ({
|
||||
id: name + '-' + index,
|
||||
name,
|
||||
enabled: true,
|
||||
parameters,
|
||||
symbols: config.symbols,
|
||||
allocation: 1 / (config.strategies?.length ?? 1),
|
||||
})) ?? [
|
||||
{
|
||||
id: config.strategy + '-0',
|
||||
name: config.strategy,
|
||||
enabled: true,
|
||||
parameters: {
|
||||
symbols: config.symbols,
|
||||
initialCapital: config.initialCapital,
|
||||
...config.config,
|
||||
},
|
||||
symbols: config.symbols,
|
||||
allocation: 1,
|
||||
},
|
||||
];
|
||||
allocation: 1 / plan.length,
|
||||
}));
|
||||
await this.strategyManager.initializeStrategies(strategies);
|
||||
playback.assertRunning();
|
||||
const trading = defined(
|
||||
|
|
|
|||
|
|
@ -1,36 +1,12 @@
|
|||
import type { BacktestConfig } from '../types';
|
||||
import { backtestStrategies } from './strategy-plan';
|
||||
|
||||
/** Resolve before fetching data, and validate again in the isolated worker. */
|
||||
/** Resolve and validate before fetching data, and validate again in the isolated worker. */
|
||||
export function resolveNativeStrategies(config: BacktestConfig) {
|
||||
const strategies = config.strategies
|
||||
? config.strategies
|
||||
.filter(strategy => strategy.enabled)
|
||||
.map(strategy => ({
|
||||
name: strategy.name,
|
||||
parameters: { ...config.config, ...strategy.config },
|
||||
}))
|
||||
: [{ name: config.strategy, parameters: config.config ?? {} }];
|
||||
if (!strategies.length) {
|
||||
throw new Error('No enabled backtest strategies');
|
||||
}
|
||||
const aliases: Record<string, string> = {
|
||||
sma: 'sma_crossover',
|
||||
smacrossover: 'sma_crossover',
|
||||
simplemovingaveragecrossover: 'sma_crossover',
|
||||
movingaverage: 'sma_crossover',
|
||||
meanreversion: 'mean_reversion',
|
||||
momentum: 'momentum',
|
||||
pairs: 'pairs_trading',
|
||||
pairstrading: 'pairs_trading',
|
||||
};
|
||||
return strategies.map(({ name, parameters }, index) => {
|
||||
if (parameters.useTypeScriptImplementation) {
|
||||
throw new Error('The native engine does not execute TypeScript strategy callbacks');
|
||||
return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => {
|
||||
if (!kind) {
|
||||
throw new Error('Unknown native strategy: ' + name);
|
||||
}
|
||||
const strategy = aliases[name.toLowerCase().replace(/[-_ ]/g, '')];
|
||||
if (!strategy) {
|
||||
throw new Error(`Unknown native strategy: ${name}`);
|
||||
}
|
||||
return { strategy, name, id: `backtest-strategy-${index}`, parameters };
|
||||
return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters };
|
||||
});
|
||||
}
|
||||
|
|
|
|||
48
apps/stock/orchestrator/src/backtest/strategy-plan.ts
Normal file
48
apps/stock/orchestrator/src/backtest/strategy-plan.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import {
|
||||
nativeParameters,
|
||||
strategyParameters,
|
||||
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 };
|
||||
// Custom TypeScript factories own their parameter contract; do not strip their extension fields.
|
||||
const parameters = kind ? strategyParameters(merged, backend) : structuredClone(merged);
|
||||
if (backend === 'native') {
|
||||
if (!kind) {
|
||||
throw new Error(`Unknown native strategy: ${entry.name}`);
|
||||
}
|
||||
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 };
|
||||
});
|
||||
}
|
||||
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)
|
||||
);
|
||||
}
|
||||
74
apps/stock/orchestrator/src/indicators/window-statistics.ts
Normal file
74
apps/stock/orchestrator/src/indicators/window-statistics.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
|
||||
/** Scalar trailing-window math. Missing warm-up is undefined, never a synthetic zero average. */
|
||||
export function trailingMean(
|
||||
values: readonly number[],
|
||||
period: number,
|
||||
offset = 0
|
||||
): number | undefined {
|
||||
if (!Number.isSafeInteger(period) || period < 1 || !Number.isSafeInteger(offset) || offset < 0) {
|
||||
throw new Error('Indicator period must be positive and offset nonnegative integers');
|
||||
}
|
||||
const end = values.length - offset;
|
||||
if (end < period) {
|
||||
return undefined;
|
||||
}
|
||||
let sum = 0;
|
||||
for (let i = end - period; i < end; i++) {
|
||||
const value = values[i];
|
||||
if (value === undefined || !Number.isFinite(value)) {
|
||||
throw new Error('Indicator prices must be finite');
|
||||
}
|
||||
sum += value;
|
||||
}
|
||||
const mean = sum / period;
|
||||
if (!Number.isFinite(mean)) {
|
||||
throw new Error('Indicator mean overflow');
|
||||
}
|
||||
return mean;
|
||||
}
|
||||
|
||||
export function trailingPopulationDeviation(
|
||||
values: readonly number[],
|
||||
period: number
|
||||
): number | undefined {
|
||||
const mean = trailingMean(values, period);
|
||||
if (mean === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
let squared = 0;
|
||||
for (let i = values.length - period; i < values.length; i++) {
|
||||
squared += (at(values, i) - mean) ** 2;
|
||||
}
|
||||
const deviation = Math.sqrt(squared / period);
|
||||
if (!Number.isFinite(deviation)) {
|
||||
throw new Error('Indicator deviation overflow');
|
||||
}
|
||||
return deviation;
|
||||
}
|
||||
|
||||
export function movingAverageCrossover(values: readonly number[], fast: number, slow: number) {
|
||||
if (fast >= slow) {
|
||||
throw new Error('fastPeriod must be below slowPeriod');
|
||||
}
|
||||
const fastMA = trailingMean(values, fast);
|
||||
const slowMA = trailingMean(values, slow);
|
||||
const prevFastMA = trailingMean(values, fast, 1);
|
||||
const prevSlowMA = trailingMean(values, slow, 1);
|
||||
if (
|
||||
fastMA === undefined ||
|
||||
slowMA === undefined ||
|
||||
prevFastMA === undefined ||
|
||||
prevSlowMA === undefined
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
goldenCross: prevFastMA <= prevSlowMA && fastMA > slowMA,
|
||||
deathCross: prevFastMA >= prevSlowMA && fastMA < slowMA,
|
||||
};
|
||||
}
|
||||
|
|
@ -70,7 +70,7 @@ export abstract class BaseStrategy extends EventEmitter {
|
|||
protected executionService: ExecutionService
|
||||
) {
|
||||
super();
|
||||
this.config = config;
|
||||
this.config = structuredClone(config);
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
|
|
@ -192,7 +192,7 @@ export abstract class BaseStrategy extends EventEmitter {
|
|||
}
|
||||
|
||||
getConfig(): Readonly<StrategyConfig> {
|
||||
return this.config;
|
||||
return structuredClone(this.config);
|
||||
}
|
||||
|
||||
hasOrder(orderId: string): boolean {
|
||||
|
|
@ -272,7 +272,7 @@ export abstract class BaseStrategy extends EventEmitter {
|
|||
'Active strategy configuration is immutable; use an explicit new strategy ID'
|
||||
);
|
||||
}
|
||||
this.config = { ...this.config, ...updates };
|
||||
this.config = this.validateConfig(structuredClone({ ...this.config, ...updates }));
|
||||
logger.info(`Updated config for strategy ${this.config.id}`);
|
||||
|
||||
// Strategies can override to handle specific config changes
|
||||
|
|
@ -377,4 +377,8 @@ export abstract class BaseStrategy extends EventEmitter {
|
|||
protected onStart(): void | Promise<void> {}
|
||||
protected onStop(): void | Promise<void> {}
|
||||
protected onConfigUpdate(_updates: Partial<StrategyConfig>): void {}
|
||||
/** Validate before assignment, so a rejected inactive edit cannot poison the current definition. */
|
||||
protected validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { normalizeStrategyName } from '../contracts/strategy-names';
|
||||
import type { ModeManager } from '../core/ModeManager';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../types';
|
||||
|
|
@ -17,7 +18,7 @@ export class StrategyRegistry {
|
|||
private readonly factories = new Map<string, StrategyFactory>();
|
||||
|
||||
register(names: readonly string[], factory: StrategyFactory): this {
|
||||
const keys = names.map(name => name.trim().toLowerCase());
|
||||
const keys = names.map(normalizeStrategyName);
|
||||
if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) {
|
||||
throw new Error('Strategy aliases must be nonempty and distinct');
|
||||
}
|
||||
|
|
@ -33,7 +34,7 @@ export class StrategyRegistry {
|
|||
}
|
||||
|
||||
async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise<BaseStrategy> {
|
||||
const factory = this.factories.get(config.name.trim().toLowerCase());
|
||||
const factory = this.factories.get(normalizeStrategyName(config.name));
|
||||
if (!factory) {
|
||||
throw new Error(`Unknown strategy: ${config.name}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,20 @@
|
|||
import { strategyAliases } from '../contracts/strategy-names';
|
||||
import { StrategyRegistry } from './StrategyRegistry';
|
||||
|
||||
/** Lazy factories avoid loading every strategy (and ML dependency) at startup. */
|
||||
export function createBuiltinStrategyRegistry(): StrategyRegistry {
|
||||
return new StrategyRegistry()
|
||||
.register(['meanreversion', 'mean-reversion'], async (config, { modeManager, execution }) => {
|
||||
.register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => {
|
||||
const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy');
|
||||
return new MeanReversionStrategy(config, modeManager, execution);
|
||||
})
|
||||
.register(
|
||||
['smacrossover', 'sma-crossover', 'moving-average'],
|
||||
async (config, { modeManager, execution }) => {
|
||||
const { SimpleMovingAverageCrossover } = await import(
|
||||
'./examples/SimpleMovingAverageCrossoverFixed'
|
||||
);
|
||||
return new SimpleMovingAverageCrossover(config, modeManager, execution);
|
||||
}
|
||||
)
|
||||
.register(['mlenhanced', 'ml-enhanced'], async (config, { modeManager, execution }) => {
|
||||
.register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => {
|
||||
const { SimpleMovingAverageCrossover } = await import(
|
||||
'./examples/SimpleMovingAverageCrossoverFixed'
|
||||
);
|
||||
return new SimpleMovingAverageCrossover(config, modeManager, execution);
|
||||
})
|
||||
.register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => {
|
||||
const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy');
|
||||
return new MLEnhancedStrategy(config, modeManager, execution);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const priceHistoryState = z.array(
|
||||
z.tuple([z.string(), z.array(z.number().finite().positive()).max(60)])
|
||||
);
|
||||
export const priceHistoryState = (capacity: number) =>
|
||||
z.array(z.tuple([z.string(), z.array(z.number().finite().positive()).max(capacity)]));
|
||||
export const barCounterState = z.array(z.tuple([z.string(), z.number().int().nonnegative()]));
|
||||
export const crossoverCheckpointSchema = z
|
||||
.object({
|
||||
priceHistory: priceHistoryState,
|
||||
barCount: barCounterState,
|
||||
lastSignalBar: barCounterState,
|
||||
totalSignals: z.number().int().nonnegative(),
|
||||
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
|
||||
})
|
||||
.strict();
|
||||
export const crossoverCheckpointSchema = (capacity: number) =>
|
||||
z
|
||||
.object({
|
||||
priceHistory: priceHistoryState(capacity),
|
||||
barCount: barCounterState,
|
||||
lastSignalBar: barCounterState,
|
||||
totalSignals: z.number().int().nonnegative(),
|
||||
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
|
||||
})
|
||||
.strict();
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
import { z } from 'zod';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/utils';
|
||||
import type { MeanReversionParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import { trailingMean, trailingPopulationDeviation } from '../../indicators/window-statistics';
|
||||
import type { ExecutionService } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { priceHistoryState } from '../checkpoint-schemas';
|
||||
import { meanReversionConfig } from '../strategy-config';
|
||||
|
||||
const logger = getLogger('MeanReversionStrategy');
|
||||
|
||||
interface MeanReversionIndicators {
|
||||
sma20: number;
|
||||
sma50: number;
|
||||
mean: number;
|
||||
trendMean: number;
|
||||
stdDev: number;
|
||||
zScore: number;
|
||||
rsi: number;
|
||||
|
|
@ -21,7 +25,7 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
private priceHistory = new Map<string, number[]>();
|
||||
private indicators = new Map<string, MeanReversionIndicators>();
|
||||
override getCheckpointVersion() {
|
||||
return 'mean-reversion/v1';
|
||||
return 'mean-reversion/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return { priceHistory: [...this.priceHistory], indicators: [...this.indicators] };
|
||||
|
|
@ -30,11 +34,17 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
const finite = z.number().finite();
|
||||
const state = z
|
||||
.object({
|
||||
priceHistory: priceHistoryState,
|
||||
priceHistory: priceHistoryState(this.historyCapacity),
|
||||
indicators: z.array(
|
||||
z.tuple([
|
||||
z.string(),
|
||||
z.object({ sma20: finite, sma50: finite, stdDev: finite, zScore: finite, rsi: finite }),
|
||||
z.object({
|
||||
mean: finite,
|
||||
trendMean: finite,
|
||||
stdDev: finite,
|
||||
zScore: finite,
|
||||
rsi: finite,
|
||||
}),
|
||||
])
|
||||
),
|
||||
})
|
||||
|
|
@ -44,13 +54,32 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
this.indicators = new Map(state.indicators);
|
||||
}
|
||||
|
||||
// Strategy parameters
|
||||
private readonly LOOKBACK_PERIOD = 20;
|
||||
private readonly Z_SCORE_ENTRY = 2.0;
|
||||
private readonly Z_SCORE_EXIT = 0.5;
|
||||
private readonly RSI_OVERSOLD = 30;
|
||||
private readonly RSI_OVERBOUGHT = 70;
|
||||
private readonly MIN_VOLUME = 1000000; // $1M daily volume
|
||||
private settings: MeanReversionParameters;
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
const validated = meanReversionConfig(config);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
}
|
||||
|
||||
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
const validated = meanReversionConfig(config);
|
||||
this.settings = validated.parameters;
|
||||
return validated;
|
||||
}
|
||||
private get historyCapacity(): number {
|
||||
return Math.max(
|
||||
this.settings.lookbackPeriod * 3,
|
||||
this.settings.trendPeriod,
|
||||
this.settings.rsiPeriod + 1
|
||||
);
|
||||
}
|
||||
protected override calculatePositionSize(signal: Signal): number {
|
||||
return this.settings.quantity ?? super.calculatePositionSize(signal);
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
|
|
@ -69,12 +98,12 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
history.push(price);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.LOOKBACK_PERIOD * 3) {
|
||||
if (history.length > this.historyCapacity) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Calculate indicators if we have enough data
|
||||
if (history.length >= this.LOOKBACK_PERIOD) {
|
||||
if (history.length >= Math.max(this.settings.lookbackPeriod, this.settings.rsiPeriod + 1)) {
|
||||
const indicators = this.calculateIndicators(history);
|
||||
this.indicators.set(symbol, indicators);
|
||||
}
|
||||
|
|
@ -83,21 +112,18 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
private calculateIndicators(prices: number[]): MeanReversionIndicators {
|
||||
const len = prices.length;
|
||||
|
||||
// Calculate SMAs
|
||||
const sma20 = this.calculateSMA(prices, 20);
|
||||
const sma50 = len >= 50 ? this.calculateSMA(prices, 50) : sma20;
|
||||
|
||||
// Calculate standard deviation
|
||||
const stdDev = this.calculateStdDev(prices.slice(-20), sma20);
|
||||
const mean = defined(trailingMean(prices, this.settings.lookbackPeriod));
|
||||
const trendMean = trailingMean(prices, this.settings.trendPeriod) ?? mean;
|
||||
const stdDev = defined(trailingPopulationDeviation(prices, this.settings.lookbackPeriod));
|
||||
|
||||
// Calculate Z-score
|
||||
const currentPrice = at(prices, len - 1);
|
||||
const zScore = stdDev > 0 ? (currentPrice - sma20) / stdDev : 0;
|
||||
const zScore = stdDev > 0 ? (currentPrice - mean) / stdDev : 0;
|
||||
|
||||
// Calculate RSI
|
||||
const rsi = this.calculateRSI(prices, 14);
|
||||
const rsi = this.calculateRSI(prices, this.settings.rsiPeriod);
|
||||
|
||||
return { sma20, sma50, stdDev, zScore, rsi };
|
||||
return { mean, trendMean, stdDev, zScore, rsi };
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
|
|
@ -113,17 +139,21 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
}
|
||||
|
||||
// Check volume filter
|
||||
if (data.data.volume * data.data.close < this.MIN_VOLUME) {
|
||||
if (data.data.volume * data.data.close < this.settings.minNotionalVolume) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const position = this.getPosition(symbol);
|
||||
const { zScore, rsi, sma20, sma50 } = indicators;
|
||||
const { zScore, rsi, mean, trendMean } = indicators;
|
||||
|
||||
// Entry signals
|
||||
if (position === 0) {
|
||||
// Long entry: Oversold conditions
|
||||
if (zScore < -this.Z_SCORE_ENTRY && rsi < this.RSI_OVERSOLD && sma20 > sma50) {
|
||||
if (
|
||||
zScore < -this.settings.entryThreshold &&
|
||||
rsi < this.settings.rsiOversold &&
|
||||
mean > trendMean
|
||||
) {
|
||||
return {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
|
|
@ -134,7 +164,11 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
}
|
||||
|
||||
// Short entry: Overbought conditions
|
||||
if (zScore > this.Z_SCORE_ENTRY && rsi > this.RSI_OVERBOUGHT && sma20 < sma50) {
|
||||
if (
|
||||
zScore > this.settings.entryThreshold &&
|
||||
rsi > this.settings.rsiOverbought &&
|
||||
mean < trendMean
|
||||
) {
|
||||
return {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
|
|
@ -148,7 +182,7 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
// Exit signals
|
||||
if (position > 0) {
|
||||
// Exit long: Price reverted to mean or stop loss
|
||||
if (zScore > -this.Z_SCORE_EXIT || zScore > this.Z_SCORE_ENTRY) {
|
||||
if (zScore > -this.settings.exitZScore || zScore > this.settings.entryThreshold) {
|
||||
return {
|
||||
type: 'close',
|
||||
symbol,
|
||||
|
|
@ -159,7 +193,7 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
}
|
||||
} else if (position < 0) {
|
||||
// Exit short: Price reverted to mean or stop loss
|
||||
if (zScore < this.Z_SCORE_EXIT || zScore < -this.Z_SCORE_ENTRY) {
|
||||
if (zScore < this.settings.exitZScore || zScore < -this.settings.entryThreshold) {
|
||||
return {
|
||||
type: 'close',
|
||||
symbol,
|
||||
|
|
@ -173,17 +207,6 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
return null;
|
||||
}
|
||||
|
||||
private calculateSMA(prices: number[], period: number): number {
|
||||
const relevantPrices = prices.slice(-period);
|
||||
return relevantPrices.reduce((sum, p) => sum + p, 0) / relevantPrices.length;
|
||||
}
|
||||
|
||||
private calculateStdDev(prices: number[], mean: number): number {
|
||||
const squaredDiffs = prices.map(p => Math.pow(p - mean, 2));
|
||||
const variance = squaredDiffs.reduce((sum, d) => sum + d, 0) / prices.length;
|
||||
return Math.sqrt(variance);
|
||||
}
|
||||
|
||||
private calculateRSI(prices: number[], period: number = 14): number {
|
||||
if (prices.length < period + 1) {
|
||||
return 50;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { SmaParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import { movingAverageCrossover } from '../../indicators/window-statistics';
|
||||
import type { ExecutionService, StrategyFill } from '../../services/ExecutionService';
|
||||
import type { OrderRequest, StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
|
||||
import { smaConfig } from '../strategy-config';
|
||||
|
||||
const logger = getLogger('SimpleMovingAverageCrossover');
|
||||
|
||||
|
|
@ -15,7 +18,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
private barCount = new Map<string, number>();
|
||||
private totalSignals = 0;
|
||||
override getCheckpointVersion() {
|
||||
return 'sma-crossover-original/v1';
|
||||
return 'sma-crossover-original/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return {
|
||||
|
|
@ -27,28 +30,26 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
};
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const state = crossoverCheckpointSchema.parse(input);
|
||||
const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input);
|
||||
this.priceHistory = new Map(state.priceHistory);
|
||||
this.lastTradeTime = new Map(state.lastSignalBar);
|
||||
this.barCount = new Map(state.barCount);
|
||||
this.totalSignals = state.totalSignals;
|
||||
}
|
||||
|
||||
// Strategy parameters
|
||||
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals
|
||||
private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals
|
||||
private readonly POSITION_SIZE = 0.1; // 10% of capital per position
|
||||
private readonly MIN_HOLDING_BARS = 1; // Minimum bars to hold position
|
||||
private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging
|
||||
private settings: SmaParameters;
|
||||
private readonly DEBUG_INTERVAL = 10;
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
super(config, modeManager, executionService);
|
||||
const validated = smaConfig(config, 1);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
logger.info(
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -75,12 +76,12 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
this.barCount.set(symbol, currentBar);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.SLOW_PERIOD * 2) {
|
||||
if (history.length > this.settings.slowPeriod * 2) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Log when we have enough data to start trading
|
||||
if (history.length === this.SLOW_PERIOD) {
|
||||
if (history.length === this.settings.slowPeriod) {
|
||||
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
|
||||
}
|
||||
}
|
||||
|
|
@ -93,21 +94,24 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
const symbol = data.data.symbol;
|
||||
const history = this.priceHistory.get(symbol);
|
||||
|
||||
if (!history || history.length < this.SLOW_PERIOD) {
|
||||
if (!history || history.length <= this.settings.slowPeriod) {
|
||||
if (history && history.length % 5 === 0) {
|
||||
logger.debug(`${symbol} - Not enough history: ${history.length}/${this.SLOW_PERIOD} bars`);
|
||||
logger.debug(
|
||||
`${symbol} - Not enough history: ${history.length}/${this.settings.slowPeriod + 1} bars`
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Calculate moving averages
|
||||
const fastMA = this.calculateSMA(history, this.FAST_PERIOD);
|
||||
const slowMA = this.calculateSMA(history, this.SLOW_PERIOD);
|
||||
|
||||
// Get previous MAs for crossover detection
|
||||
const prevHistory = history.slice(0, -1);
|
||||
const prevFastMA = this.calculateSMA(prevHistory, this.FAST_PERIOD);
|
||||
const prevSlowMA = this.calculateSMA(prevHistory, this.SLOW_PERIOD);
|
||||
const crossover = movingAverageCrossover(
|
||||
history,
|
||||
this.settings.fastPeriod,
|
||||
this.settings.slowPeriod
|
||||
);
|
||||
if (!crossover) {
|
||||
return null;
|
||||
}
|
||||
const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover;
|
||||
|
||||
const currentPosition = this.getPosition(symbol);
|
||||
const currentPrice = data.data.close;
|
||||
|
|
@ -119,10 +123,6 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
const barsSinceLastTrade =
|
||||
lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER;
|
||||
|
||||
// Detect crossovers FIRST
|
||||
const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA;
|
||||
const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA;
|
||||
|
||||
// Enhanced debugging - log more frequently and when MAs are close
|
||||
const maDiff = fastMA - slowMA;
|
||||
const maDiffPct = (maDiff / slowMA) * 100;
|
||||
|
|
@ -131,8 +131,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
if (history.length % this.DEBUG_INTERVAL === 0 || masAreClose || goldenCross || deathCross) {
|
||||
logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`);
|
||||
logger.info(` Price: $${currentPrice.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.FAST_PERIOD}): $${fastMA.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`);
|
||||
logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`);
|
||||
logger.info(` Position: ${currentPosition} shares`);
|
||||
logger.info(` Bars since last trade: ${barsSinceLastTrade}`);
|
||||
|
|
@ -291,32 +291,22 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
return null;
|
||||
}
|
||||
|
||||
private calculateSMA(prices: number[], period: number): number {
|
||||
if (prices.length < period) {
|
||||
logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const slice = prices.slice(-period);
|
||||
const sum = slice.reduce((a, b) => a + b, 0);
|
||||
const sma = sum / period;
|
||||
|
||||
// Sanity check
|
||||
if (isNaN(sma) || !isFinite(sma)) {
|
||||
logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return sma;
|
||||
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
const validated = smaConfig(config, 1);
|
||||
this.settings = validated.parameters;
|
||||
return validated;
|
||||
}
|
||||
|
||||
private async calculateCrossoverPositionSize(price: number): Promise<number> {
|
||||
if (this.settings.quantity !== undefined) {
|
||||
return this.settings.quantity;
|
||||
}
|
||||
const accountBalance = (await this.executionService.getAccount()).equity;
|
||||
const positionValue = accountBalance * this.POSITION_SIZE;
|
||||
const positionValue = accountBalance * this.settings.positionFraction;
|
||||
const shares = Math.floor(positionValue / price);
|
||||
|
||||
logger.debug(
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
|
||||
);
|
||||
|
||||
return Math.max(1, shares); // At least 1 share
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { SmaParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import { movingAverageCrossover } from '../../indicators/window-statistics';
|
||||
import type { ExecutionService, StrategyFill } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
|
||||
import { smaConfig } from '../strategy-config';
|
||||
|
||||
const logger = getLogger('SimpleMovingAverageCrossover');
|
||||
|
||||
|
|
@ -16,7 +19,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
private totalSignals = 0;
|
||||
private lastCrossoverType = new Map<string, 'golden' | 'death' | null>();
|
||||
override getCheckpointVersion() {
|
||||
return 'sma-crossover-fixed/v1';
|
||||
return 'sma-crossover-fixed/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return {
|
||||
|
|
@ -28,7 +31,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
};
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const state = crossoverCheckpointSchema.parse(input);
|
||||
const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input);
|
||||
this.priceHistory = new Map(state.priceHistory);
|
||||
this.lastSignalBar = new Map(state.lastSignalBar);
|
||||
this.barCount = new Map(state.barCount);
|
||||
|
|
@ -36,21 +39,19 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
this.lastCrossoverType = new Map(state.lastCrossoverType);
|
||||
}
|
||||
|
||||
// Strategy parameters
|
||||
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals
|
||||
private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals
|
||||
private readonly POSITION_SIZE = 0.1; // 10% of capital per position
|
||||
private readonly MIN_HOLDING_BARS = 3; // Minimum bars to hold position
|
||||
private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging
|
||||
private settings: SmaParameters;
|
||||
private readonly DEBUG_INTERVAL = 10;
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
super(config, modeManager, executionService);
|
||||
const validated = smaConfig(config);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
logger.info(
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -77,12 +78,12 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
this.barCount.set(symbol, currentBar);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.SLOW_PERIOD * 2) {
|
||||
if (history.length > this.settings.slowPeriod * 2) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Log when we have enough data to start trading
|
||||
if (history.length === this.SLOW_PERIOD) {
|
||||
if (history.length === this.settings.slowPeriod + 1) {
|
||||
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
|
||||
}
|
||||
}
|
||||
|
|
@ -95,7 +96,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
const symbol = data.data.symbol;
|
||||
const history = this.priceHistory.get(symbol);
|
||||
|
||||
if (!history || history.length < this.SLOW_PERIOD) {
|
||||
if (!history || history.length < this.settings.slowPeriod) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -103,18 +104,15 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
const timestamp = data.data.timestamp;
|
||||
const currentBar = this.barCount.get(symbol) || 0;
|
||||
|
||||
// Calculate moving averages
|
||||
const fastMA = this.calculateSMA(history, this.FAST_PERIOD);
|
||||
const slowMA = this.calculateSMA(history, this.SLOW_PERIOD);
|
||||
|
||||
// Get previous MAs for crossover detection
|
||||
const historyWithoutLast = history.slice(0, -1);
|
||||
const prevFastMA = this.calculateSMA(historyWithoutLast, this.FAST_PERIOD);
|
||||
const prevSlowMA = this.calculateSMA(historyWithoutLast, this.SLOW_PERIOD);
|
||||
|
||||
// Detect crossovers
|
||||
const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA;
|
||||
const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA;
|
||||
const crossover = movingAverageCrossover(
|
||||
history,
|
||||
this.settings.fastPeriod,
|
||||
this.settings.slowPeriod
|
||||
);
|
||||
if (!crossover) {
|
||||
return null;
|
||||
}
|
||||
const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover;
|
||||
|
||||
// Get current position
|
||||
const currentPosition = this.getPosition(symbol);
|
||||
|
|
@ -131,8 +129,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
if (currentBar % this.DEBUG_INTERVAL === 0 || goldenCross || deathCross) {
|
||||
logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`);
|
||||
logger.info(` Price: $${currentPrice.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.FAST_PERIOD}): $${fastMA.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`);
|
||||
logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`);
|
||||
logger.info(` Position: ${currentPosition} shares`);
|
||||
logger.info(` Bars since last signal: ${barsSinceLastSignal}`);
|
||||
|
|
@ -155,7 +153,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
// Check if we should enter a position based on the current trend
|
||||
const lastCrossover = this.lastCrossoverType.get(symbol);
|
||||
|
||||
if (currentPosition === 0 && barsSinceLastSignal >= this.MIN_HOLDING_BARS) {
|
||||
if (currentPosition === 0 && barsSinceLastSignal >= this.settings.minHoldingBars) {
|
||||
// No position - check if we should enter based on last crossover
|
||||
if (lastCrossover === 'golden' && fastMA > slowMA) {
|
||||
// Trend is still bullish after golden cross - open long
|
||||
|
|
@ -278,32 +276,22 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|||
return null;
|
||||
}
|
||||
|
||||
private calculateSMA(prices: number[], period: number): number {
|
||||
if (prices.length < period) {
|
||||
logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const slice = prices.slice(-period);
|
||||
const sum = slice.reduce((a, b) => a + b, 0);
|
||||
const sma = sum / period;
|
||||
|
||||
// Sanity check
|
||||
if (isNaN(sma) || !isFinite(sma)) {
|
||||
logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return sma;
|
||||
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
||||
const validated = smaConfig(config);
|
||||
this.settings = validated.parameters;
|
||||
return validated;
|
||||
}
|
||||
|
||||
private async calculateCrossoverPositionSize(price: number): Promise<number> {
|
||||
if (this.settings.quantity !== undefined) {
|
||||
return this.settings.quantity;
|
||||
}
|
||||
const accountBalance = (await this.executionService.getAccount()).equity;
|
||||
const positionValue = accountBalance * this.POSITION_SIZE;
|
||||
const positionValue = accountBalance * this.settings.positionFraction;
|
||||
const shares = Math.floor(positionValue / price);
|
||||
|
||||
logger.debug(
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
|
||||
);
|
||||
|
||||
return Math.max(1, shares); // At least 1 share
|
||||
|
|
|
|||
18
apps/stock/orchestrator/src/strategies/strategy-config.ts
Normal file
18
apps/stock/orchestrator/src/strategies/strategy-config.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import {
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../contracts/strategies';
|
||||
import type { StrategyConfig } from '../types';
|
||||
|
||||
export function smaConfig(config: StrategyConfig, defaultHoldingBars = 3) {
|
||||
return {
|
||||
...config,
|
||||
parameters: typescriptSmaParameters.parse({
|
||||
...config.parameters,
|
||||
minHoldingBars: config.parameters.minHoldingBars ?? defaultHoldingBars,
|
||||
}),
|
||||
};
|
||||
}
|
||||
export function meanReversionConfig(config: StrategyConfig) {
|
||||
return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue