Remove legacy strategy frameworks and clarify supported execution paths
This commit is contained in:
parent
4207bf2c1c
commit
783b619846
28 changed files with 996 additions and 4689 deletions
|
|
@ -1,162 +0,0 @@
|
|||
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
|
||||
import { resolveDataset } from '../data/historical-dataset';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import { RustStrategy } from '../strategies/RustStrategy';
|
||||
import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types';
|
||||
import { nativeResultSchema } from './native-result';
|
||||
|
||||
export interface RustBacktestConfig {
|
||||
name: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
dataFrequency: string;
|
||||
}
|
||||
|
||||
export interface RustBacktestResult {
|
||||
config: RustBacktestConfig;
|
||||
metrics: {
|
||||
totalReturn: number;
|
||||
totalTrades: number;
|
||||
profitableTrades: number;
|
||||
winRate: number;
|
||||
profitFactor: number | null;
|
||||
sharpeRatio: number;
|
||||
maxDrawdown: number;
|
||||
totalPnl: number;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
};
|
||||
equityCurve: Array<{ date: string; value: number }>;
|
||||
trades: import('./native-result').NativeBacktestResult['trades'];
|
||||
finalPositions: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated Diagnostic wrapper only. Use BacktestRunner for durable, isolated execution. */
|
||||
export class RustBacktestEngine {
|
||||
private engine: RustEngine;
|
||||
private container: IServiceContainer;
|
||||
private storageService: StorageService;
|
||||
private config: RustBacktestConfig;
|
||||
private readonly request: BacktestConfig;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
storageService: StorageService,
|
||||
config: BacktestConfig
|
||||
) {
|
||||
this.container = container;
|
||||
this.storageService = storageService;
|
||||
this.request = config;
|
||||
|
||||
// Convert config for Rust
|
||||
const rustConfig: RustBacktestConfig = {
|
||||
name: config.name || 'Backtest',
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
commission: config.commission ?? 0.001,
|
||||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency || '1d',
|
||||
};
|
||||
|
||||
this.config = rustConfig;
|
||||
this.engine = new RustEngine(rustConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a TypeScript strategy to the backtest
|
||||
*/
|
||||
addStrategy(strategy: RustStrategy): void {
|
||||
strategy.register(this.engine);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load historical data for the backtest
|
||||
*/
|
||||
async loadData(): Promise<void> {
|
||||
const dataset = await resolveDataset(this.storageService, this.request);
|
||||
this.engine.loadMarketData(dataset.bars.map(bar => ({ ...bar, type: 'bar' })));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the backtest
|
||||
*/
|
||||
async run(): Promise<RustBacktestResult> {
|
||||
this.container.logger.info('Starting backtest run...');
|
||||
|
||||
// Load data first
|
||||
await this.loadData();
|
||||
|
||||
// Run backtest in Rust
|
||||
const resultJson = await this.engine.run();
|
||||
|
||||
// Parse result and convert snake_case to camelCase
|
||||
const rustResult = nativeResultSchema.parse(JSON.parse(resultJson));
|
||||
|
||||
const result: RustBacktestResult = {
|
||||
config: this.config,
|
||||
metrics: {
|
||||
totalReturn: rustResult.metrics.totalReturn,
|
||||
totalTrades: rustResult.metrics.totalTrades,
|
||||
profitableTrades: rustResult.trades.filter(trade => (trade.pnl ?? 0) > 0).length,
|
||||
winRate: rustResult.metrics.winRate,
|
||||
profitFactor: rustResult.metrics.profitFactor,
|
||||
sharpeRatio: rustResult.metrics.sharpeRatio,
|
||||
maxDrawdown: rustResult.metrics.maxDrawdown,
|
||||
totalPnl: rustResult.trades.reduce((sum, trade) => sum + (trade.pnl ?? 0), 0),
|
||||
avgWin: rustResult.metrics.avgWin,
|
||||
avgLoss: rustResult.metrics.avgLoss,
|
||||
},
|
||||
equityCurve: rustResult.equity,
|
||||
trades: rustResult.trades,
|
||||
finalPositions: Object.fromEntries(
|
||||
rustResult.positions.map(position => [position.symbol, position])
|
||||
),
|
||||
};
|
||||
|
||||
// Log results
|
||||
this.container.logger.info('Rust backtest completed', {
|
||||
totalReturn: result.metrics.totalReturn,
|
||||
totalTrades: result.metrics.totalTrades,
|
||||
sharpeRatio: result.metrics.sharpeRatio,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the backtest configuration
|
||||
*/
|
||||
private getConfig(): RustBacktestConfig {
|
||||
return this.config;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory function to create a Rust-powered backtest
|
||||
*/
|
||||
export async function createRustBacktest(
|
||||
container: IServiceContainer,
|
||||
config: BacktestConfig,
|
||||
strategies: RustStrategy[]
|
||||
): Promise<RustBacktestResult> {
|
||||
const storageService =
|
||||
container.custom?.StorageService ||
|
||||
new StorageService(container, container.mongodb, container.postgres, container.questdb ?? null);
|
||||
|
||||
// Create engine
|
||||
const engine = new RustBacktestEngine(container, storageService, config);
|
||||
|
||||
// Add strategies
|
||||
for (const strategy of strategies) {
|
||||
engine.addStrategy(strategy);
|
||||
}
|
||||
|
||||
// Run backtest
|
||||
return await engine.run();
|
||||
}
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { type MarketData } from '../types';
|
||||
|
||||
const logger = getLogger('rust-strategy');
|
||||
|
||||
export interface Signal {
|
||||
symbol: string;
|
||||
signal_type: 'Buy' | 'Sell' | 'Close';
|
||||
strength: number; // -1.0 to 1.0
|
||||
quantity?: number;
|
||||
reason?: string;
|
||||
metadata?: unknown;
|
||||
}
|
||||
|
||||
export type StrategyCall =
|
||||
| { method: 'on_market_data'; data: MarketData }
|
||||
| { method: 'on_fill'; data: { symbol: string; quantity: number; price: number; side: string } };
|
||||
|
||||
export interface StrategyResponse {
|
||||
signals: Signal[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for TypeScript strategies that run in the Rust backtest engine
|
||||
*/
|
||||
export abstract class RustStrategy {
|
||||
protected name: string;
|
||||
protected id: string;
|
||||
protected parameters: Record<string, unknown>;
|
||||
protected positions: Map<string, number> = new Map();
|
||||
|
||||
constructor(name: string, id: string, parameters: Record<string, unknown> = {}) {
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
this.parameters = parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main callback that Rust will call
|
||||
*/
|
||||
public handleCall(call: StrategyCall): StrategyResponse {
|
||||
switch (call.method) {
|
||||
case 'on_market_data': {
|
||||
const signals = this.onMarketData(call.data);
|
||||
return { signals };
|
||||
}
|
||||
|
||||
case 'on_fill':
|
||||
this.onFill(call.data.symbol, call.data.quantity, call.data.price, call.data.side);
|
||||
return { signals: [] };
|
||||
|
||||
default:
|
||||
return { signals: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when new market data is received
|
||||
*/
|
||||
protected abstract onMarketData(data: MarketData): Signal[];
|
||||
|
||||
/**
|
||||
* Called when an order is filled
|
||||
*/
|
||||
protected onFill(symbol: string, quantity: number, price: number, side: string): void {
|
||||
const currentPosition = this.positions.get(symbol) || 0;
|
||||
const newPosition = side === 'buy' ? currentPosition + quantity : currentPosition - quantity;
|
||||
|
||||
if (Math.abs(newPosition) < 0.0001) {
|
||||
this.positions.delete(symbol);
|
||||
} else {
|
||||
this.positions.set(symbol, newPosition);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a buy signal
|
||||
*/
|
||||
protected buySignal(symbol: string, strength: number = 1.0, reason?: string): Signal {
|
||||
return {
|
||||
symbol,
|
||||
signal_type: 'Buy',
|
||||
strength,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a sell signal
|
||||
*/
|
||||
protected sellSignal(symbol: string, strength: number = 1.0, reason?: string): Signal {
|
||||
return {
|
||||
symbol,
|
||||
signal_type: 'Sell',
|
||||
strength,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a close position signal
|
||||
*/
|
||||
protected closeSignal(symbol: string, reason?: string): Signal {
|
||||
return {
|
||||
symbol,
|
||||
signal_type: 'Close',
|
||||
strength: 1.0,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register this strategy with a backtest engine
|
||||
*/
|
||||
public register(engine: BacktestEngine): void {
|
||||
logger.debug(`Registering strategy ${this.name} with id ${this.id}`);
|
||||
|
||||
// Convert the handleCall method to what Rust expects
|
||||
const callback = (callJson: string) => {
|
||||
logger.debug('Strategy callback', { callJson });
|
||||
const call: StrategyCall = JSON.parse(callJson);
|
||||
const response = this.handleCall(call);
|
||||
logger.debug('Strategy response:', response);
|
||||
return JSON.stringify(response);
|
||||
};
|
||||
|
||||
engine.addTypescriptStrategy(this.name, this.id, this.parameters, callback);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import type { MarketData } from '../types';
|
||||
import type { Signal } from './RustStrategy';
|
||||
|
||||
interface StrategyState {
|
||||
priceHistory: Map<string, number[]>;
|
||||
positions: Map<string, number>;
|
||||
}
|
||||
interface InlineStrategy {
|
||||
onMarketData(data: MarketData, state: StrategyState): Signal[];
|
||||
onFill?(
|
||||
fill: { symbol: string; quantity: number; price: number; side: string },
|
||||
state: StrategyState
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface IStrategyExecutor {
|
||||
onMarketData(data: MarketData): Signal[];
|
||||
onFill(symbol: string, quantity: number, price: number, side: string): void;
|
||||
getState(): Record<string, StrategyState>;
|
||||
setState(state: Record<string, StrategyState>): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes strategies in-process for backtesting
|
||||
* This avoids the complexity of async callbacks between Rust and TypeScript
|
||||
*/
|
||||
export class StrategyExecutor implements IStrategyExecutor {
|
||||
private strategies: Map<string, InlineStrategy> = new Map();
|
||||
private strategyStates: Map<string, StrategyState> = new Map();
|
||||
|
||||
registerStrategy(id: string, strategy: InlineStrategy) {
|
||||
this.strategies.set(id, strategy);
|
||||
this.strategyStates.set(id, {
|
||||
priceHistory: new Map<string, number[]>(),
|
||||
positions: new Map<string, number>(),
|
||||
});
|
||||
}
|
||||
|
||||
onMarketData(data: MarketData): Signal[] {
|
||||
const allSignals: Signal[] = [];
|
||||
|
||||
for (const [id, strategy] of this.strategies) {
|
||||
const state = defined(this.strategyStates.get(id));
|
||||
const signals = strategy.onMarketData(data, state);
|
||||
|
||||
if (signals && signals.length > 0) {
|
||||
allSignals.push(...signals);
|
||||
}
|
||||
}
|
||||
|
||||
return allSignals;
|
||||
}
|
||||
|
||||
onFill(symbol: string, quantity: number, price: number, side: string): void {
|
||||
for (const [id, strategy] of this.strategies) {
|
||||
const state = defined(this.strategyStates.get(id));
|
||||
|
||||
if (strategy.onFill) {
|
||||
strategy.onFill({ symbol, quantity, price, side }, state);
|
||||
}
|
||||
|
||||
// Update position tracking
|
||||
const currentPos = state.positions.get(symbol) || 0;
|
||||
const newPos = side === 'buy' ? currentPos + quantity : currentPos - quantity;
|
||||
|
||||
if (Math.abs(newPos) < 0.0001) {
|
||||
state.positions.delete(symbol);
|
||||
} else {
|
||||
state.positions.set(symbol, newPos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getState() {
|
||||
return Object.fromEntries(this.strategyStates);
|
||||
}
|
||||
|
||||
setState(state: Record<string, StrategyState>): void {
|
||||
this.strategyStates = new Map(Object.entries(state));
|
||||
}
|
||||
}
|
||||
|
||||
// Example SMA Crossover Strategy
|
||||
export const SMACrossoverStrategy = {
|
||||
onMarketData(data: MarketData, state: StrategyState): Signal[] {
|
||||
const signals: Signal[] = [];
|
||||
|
||||
// Check if it's bar data
|
||||
if (data.type !== 'bar') {
|
||||
return signals;
|
||||
}
|
||||
|
||||
const { symbol, close } = data.data;
|
||||
const fastPeriod = 5;
|
||||
const slowPeriod = 15;
|
||||
|
||||
// Update price history
|
||||
if (!state.priceHistory.has(symbol)) {
|
||||
state.priceHistory.set(symbol, []);
|
||||
}
|
||||
|
||||
const history = defined(state.priceHistory.get(symbol));
|
||||
history.push(close);
|
||||
|
||||
// Keep only necessary history
|
||||
if (history.length > slowPeriod + 1) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Need enough data
|
||||
if (history.length >= slowPeriod) {
|
||||
// Calculate SMAs
|
||||
const fastSMA = history.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod;
|
||||
const slowSMA = history.reduce((a, b) => a + b, 0) / history.length;
|
||||
|
||||
// Previous SMAs (if we have enough history)
|
||||
if (history.length > slowPeriod) {
|
||||
const prevHistory = history.slice(0, -1);
|
||||
const prevFastSMA = prevHistory.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod;
|
||||
const prevSlowSMA = prevHistory.reduce((a, b) => a + b, 0) / prevHistory.length;
|
||||
|
||||
const currentPosition = state.positions.get(symbol) || 0;
|
||||
|
||||
// Golden cross - buy signal
|
||||
if (prevFastSMA <= prevSlowSMA && fastSMA > slowSMA && currentPosition <= 0) {
|
||||
signals.push({
|
||||
symbol,
|
||||
signal_type: 'Buy',
|
||||
strength: 1.0,
|
||||
quantity: 100,
|
||||
reason: 'Golden cross',
|
||||
});
|
||||
}
|
||||
|
||||
// Death cross - sell signal
|
||||
else if (prevFastSMA >= prevSlowSMA && fastSMA < slowSMA && currentPosition >= 0) {
|
||||
signals.push({
|
||||
symbol,
|
||||
signal_type: 'Sell',
|
||||
strength: 1.0,
|
||||
quantity: 100,
|
||||
reason: 'Death cross',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return signals;
|
||||
},
|
||||
};
|
||||
|
|
@ -5,17 +5,15 @@ import { StrategyRegistry } from './StrategyRegistry';
|
|||
export function createBuiltinStrategyRegistry(): StrategyRegistry {
|
||||
return new StrategyRegistry()
|
||||
.register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => {
|
||||
const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy');
|
||||
const { MeanReversionStrategy } = await import('./builtin/MeanReversionStrategy');
|
||||
return new MeanReversionStrategy(config, modeManager, execution);
|
||||
})
|
||||
.register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => {
|
||||
const { SimpleMovingAverageCrossover } = await import(
|
||||
'./examples/SimpleMovingAverageCrossoverFixed'
|
||||
);
|
||||
return new SimpleMovingAverageCrossover(config, modeManager, execution);
|
||||
const { SmaCrossoverStrategy } = await import('./builtin/SmaCrossoverStrategy');
|
||||
return new SmaCrossoverStrategy(config, modeManager, execution);
|
||||
})
|
||||
.register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => {
|
||||
const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy');
|
||||
const { MLEnhancedStrategy } = await import('./experimental/MLEnhancedStrategy');
|
||||
return new MLEnhancedStrategy(config, modeManager, execution);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ interface MeanReversionIndicators {
|
|||
rsi: number;
|
||||
}
|
||||
|
||||
/** Versioned implementation used by the built-in mean-reversion aliases. */
|
||||
export class MeanReversionStrategy extends BaseStrategy {
|
||||
private priceHistory = new Map<string, number[]>();
|
||||
private indicators = new Map<string, MeanReversionIndicators>();
|
||||
|
|
@ -12,7 +12,7 @@ import { smaConfig } from '../strategy-config';
|
|||
|
||||
const logger = getLogger('SimpleMovingAverageCrossover');
|
||||
|
||||
export class SimpleMovingAverageCrossover extends BaseStrategy {
|
||||
export class SmaCrossoverStrategy extends BaseStrategy {
|
||||
private priceHistory = new Map<string, number[]>();
|
||||
private lastSignalBar = new Map<string, number>();
|
||||
private barCount = new Map<string, number>();
|
||||
|
|
@ -1,590 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/utils';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { IndicatorManager } from '../indicators/IndicatorManager';
|
||||
import { PositionManager } from '../position/PositionManager';
|
||||
import { RiskManager } from '../risk/RiskManager';
|
||||
import {
|
||||
CommonFilters,
|
||||
CommonRules,
|
||||
SignalManager,
|
||||
type TradingSignal,
|
||||
} from '../signals/SignalManager';
|
||||
|
||||
const logger = getLogger('AdvancedMultiIndicatorStrategy');
|
||||
|
||||
export interface AdvancedStrategyConfig {
|
||||
// Indicator settings
|
||||
fastMA?: number;
|
||||
slowMA?: number;
|
||||
rsiPeriod?: number;
|
||||
atrPeriod?: number;
|
||||
|
||||
// Risk settings
|
||||
riskPerTrade?: number;
|
||||
maxPositions?: number;
|
||||
maxDrawdown?: number;
|
||||
useATRStops?: boolean;
|
||||
atrMultiplier?: number;
|
||||
|
||||
// Signal settings
|
||||
signalAggregation?: 'weighted' | 'majority' | 'unanimous' | 'threshold';
|
||||
minSignalStrength?: number;
|
||||
minSignalConfidence?: number;
|
||||
|
||||
// Position sizing
|
||||
positionSizing?: 'fixed' | 'risk' | 'kelly' | 'volatility';
|
||||
|
||||
// Other
|
||||
debugMode?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advanced strategy using multiple indicators, risk management, and signal aggregation
|
||||
*/
|
||||
export class AdvancedMultiIndicatorStrategy extends BaseStrategy {
|
||||
private indicatorManager: IndicatorManager;
|
||||
private positionManager: PositionManager;
|
||||
private riskManager: RiskManager;
|
||||
private signalManager: SignalManager;
|
||||
|
||||
private readonly indicatorConfig: Required<AdvancedStrategyConfig>;
|
||||
private stopLosses: Map<string, number> = new Map();
|
||||
private takeProfits: Map<string, number> = new Map();
|
||||
|
||||
constructor(
|
||||
strategyConfig: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
super(strategyConfig, modeManager, executionService);
|
||||
|
||||
// Initialize config
|
||||
this.indicatorConfig = {
|
||||
fastMA: 20,
|
||||
slowMA: 50,
|
||||
rsiPeriod: 14,
|
||||
atrPeriod: 14,
|
||||
riskPerTrade: 0.02,
|
||||
maxPositions: 5,
|
||||
maxDrawdown: 0.2,
|
||||
useATRStops: true,
|
||||
atrMultiplier: 2,
|
||||
signalAggregation: 'weighted',
|
||||
minSignalStrength: 0.5,
|
||||
minSignalConfidence: 0.3,
|
||||
positionSizing: 'risk',
|
||||
debugMode: false,
|
||||
...strategyConfig.parameters,
|
||||
};
|
||||
|
||||
// Initialize managers
|
||||
const initialCapital = Number(strategyConfig.parameters.initialCapital ?? 100000);
|
||||
this.indicatorManager = new IndicatorManager();
|
||||
this.positionManager = new PositionManager(initialCapital);
|
||||
this.riskManager = new RiskManager(initialCapital, {
|
||||
maxPositions: this.indicatorConfig.maxPositions,
|
||||
maxDrawdownPct: this.indicatorConfig.maxDrawdown,
|
||||
maxPositionSizePct: 0.1,
|
||||
});
|
||||
|
||||
this.signalManager = new SignalManager({
|
||||
method: this.indicatorConfig.signalAggregation,
|
||||
});
|
||||
|
||||
// Setup signal rules
|
||||
this.setupSignalRules();
|
||||
|
||||
logger.info('AdvancedMultiIndicatorStrategy initialized:', this.indicatorConfig);
|
||||
}
|
||||
|
||||
private setupSignalRules(): void {
|
||||
// Moving average rules
|
||||
this.signalManager.addRule({
|
||||
name: `MA Crossover (${this.indicatorConfig.fastMA}/${this.indicatorConfig.slowMA})`,
|
||||
condition: indicators => {
|
||||
const fast = indicators[`sma${this.indicatorConfig.fastMA}`];
|
||||
const slow = indicators[`sma${this.indicatorConfig.slowMA}`];
|
||||
const prevFast = indicators[`sma${this.indicatorConfig.fastMA}_prev`];
|
||||
const prevSlow = indicators[`sma${this.indicatorConfig.slowMA}_prev`];
|
||||
|
||||
if (!fast || !slow || !prevFast || !prevSlow) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for crossover
|
||||
const crossover = prevFast <= prevSlow && fast > slow;
|
||||
const crossunder = prevFast >= prevSlow && fast < slow;
|
||||
|
||||
return crossover || crossunder;
|
||||
},
|
||||
weight: 1,
|
||||
direction: 'both',
|
||||
});
|
||||
|
||||
// RSI rules
|
||||
this.signalManager.addRules([CommonRules.rsiOversold(30), CommonRules.rsiOverbought(70)]);
|
||||
|
||||
// MACD rules
|
||||
this.signalManager.addRules([CommonRules.macdBullishCross(), CommonRules.macdBearishCross()]);
|
||||
|
||||
// Bollinger Band rules
|
||||
this.signalManager.addRules([
|
||||
CommonRules.priceAtLowerBand(),
|
||||
CommonRules.priceAtUpperBand(),
|
||||
CommonRules.bollingerSqueeze(),
|
||||
]);
|
||||
|
||||
// Add filters
|
||||
this.signalManager.addFilter(CommonFilters.minStrength(this.indicatorConfig.minSignalStrength));
|
||||
this.signalManager.addFilter(
|
||||
CommonFilters.minConfidence(this.indicatorConfig.minSignalConfidence)
|
||||
);
|
||||
this.signalManager.addFilter(CommonFilters.trendAlignment('sma200'));
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { symbol, timestamp, open, high, low, close, volume } = data.data;
|
||||
|
||||
// First time setup for symbol
|
||||
if (!this.indicatorManager.getHistoryLength(symbol)) {
|
||||
this.setupSymbolIndicators(symbol);
|
||||
}
|
||||
|
||||
// Update price history
|
||||
this.indicatorManager.updatePrice({
|
||||
symbol,
|
||||
timestamp,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
});
|
||||
|
||||
// Update position market values
|
||||
this.updatePositionValues(symbol, close);
|
||||
|
||||
// Check stop losses and take profits
|
||||
this.checkExitConditions(symbol, close);
|
||||
}
|
||||
|
||||
private setupSymbolIndicators(symbol: string): void {
|
||||
// Setup incremental indicators
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', {
|
||||
type: 'sma',
|
||||
period: this.indicatorConfig.fastMA,
|
||||
});
|
||||
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', {
|
||||
type: 'sma',
|
||||
period: this.indicatorConfig.slowMA,
|
||||
});
|
||||
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'rsi', {
|
||||
type: 'rsi',
|
||||
period: this.indicatorConfig.rsiPeriod,
|
||||
});
|
||||
|
||||
logger.info(`Initialized indicators for ${symbol}`);
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { symbol, timestamp, close } = data.data;
|
||||
const historyLength = this.indicatorManager.getHistoryLength(symbol);
|
||||
|
||||
// Need enough data
|
||||
if (historyLength < Math.max(this.indicatorConfig.slowMA, 26)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Prepare indicators for signal generation
|
||||
const indicators = this.prepareIndicators(symbol, close);
|
||||
if (!indicators) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check risk before generating signals
|
||||
const currentPositions = this.getCurrentPositionMap();
|
||||
const riskCheck = this.riskManager.checkNewPosition(
|
||||
symbol,
|
||||
100, // Dummy size for check
|
||||
close,
|
||||
currentPositions
|
||||
);
|
||||
|
||||
if (!riskCheck.allowed && !this.positionManager.hasPosition(symbol)) {
|
||||
if (this.indicatorConfig.debugMode) {
|
||||
logger.warn(`Risk check failed for ${symbol}: ${riskCheck.reason}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Generate trading signal
|
||||
const tradingSignal = this.signalManager.generateSignal(symbol, timestamp, indicators, {
|
||||
position: this.positionManager.getPositionQuantity(symbol),
|
||||
});
|
||||
|
||||
if (!tradingSignal) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Log signal if in debug mode
|
||||
if (this.indicatorConfig.debugMode) {
|
||||
logger.info(`Signal generated for ${symbol}:`, {
|
||||
direction: tradingSignal.direction,
|
||||
strength: tradingSignal.strength.toFixed(2),
|
||||
confidence: tradingSignal.confidence.toFixed(2),
|
||||
rules: tradingSignal.rules,
|
||||
});
|
||||
}
|
||||
|
||||
// Convert to strategy signal
|
||||
return this.convertToStrategySignal(tradingSignal, symbol, close);
|
||||
}
|
||||
|
||||
private prepareIndicators(symbol: string, currentPrice: number): Record<string, number> | null {
|
||||
const indicators: Record<string, number> = { price: currentPrice };
|
||||
|
||||
// Get moving averages
|
||||
const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastMA);
|
||||
const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowMA);
|
||||
const sma200 = this.indicatorManager.getSMA(symbol, 200);
|
||||
|
||||
if (!fastMA || !slowMA) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Current and previous values
|
||||
indicators[`sma${this.indicatorConfig.fastMA}`] = defined(
|
||||
this.indicatorManager.getLatest(fastMA)
|
||||
);
|
||||
indicators[`sma${this.indicatorConfig.slowMA}`] = defined(
|
||||
this.indicatorManager.getLatest(slowMA)
|
||||
);
|
||||
|
||||
if (fastMA.length >= 2 && slowMA.length >= 2) {
|
||||
indicators[`sma${this.indicatorConfig.fastMA}_prev`] = at(fastMA, fastMA.length - 2);
|
||||
indicators[`sma${this.indicatorConfig.slowMA}_prev`] = at(slowMA, slowMA.length - 2);
|
||||
}
|
||||
|
||||
if (sma200) {
|
||||
indicators.sma200 = defined(this.indicatorManager.getLatest(sma200));
|
||||
}
|
||||
|
||||
// RSI
|
||||
const rsi = this.indicatorManager.getRSI(symbol, this.indicatorConfig.rsiPeriod);
|
||||
if (rsi) {
|
||||
indicators.rsi = defined(this.indicatorManager.getLatest(rsi));
|
||||
}
|
||||
|
||||
// MACD
|
||||
const macd = this.indicatorManager.getMACD(symbol);
|
||||
if (macd) {
|
||||
indicators.macd = defined(this.indicatorManager.getLatest(macd.macd));
|
||||
indicators.macd_signal = defined(this.indicatorManager.getLatest(macd.signal));
|
||||
indicators.macd_histogram = defined(this.indicatorManager.getLatest(macd.histogram));
|
||||
|
||||
if (macd.macd.length >= 2) {
|
||||
indicators.macd_prev = at(macd.macd, macd.macd.length - 2);
|
||||
indicators.macd_signal_prev = at(macd.signal, macd.signal.length - 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Bollinger Bands
|
||||
const bb = this.indicatorManager.getBollingerBands(symbol);
|
||||
if (bb) {
|
||||
indicators.bb_upper = defined(this.indicatorManager.getLatest(bb.upper));
|
||||
indicators.bb_middle = defined(this.indicatorManager.getLatest(bb.middle));
|
||||
indicators.bb_lower = defined(this.indicatorManager.getLatest(bb.lower));
|
||||
}
|
||||
|
||||
// ATR for volatility
|
||||
const atr = this.indicatorManager.getATR(symbol, this.indicatorConfig.atrPeriod);
|
||||
if (atr) {
|
||||
indicators.atr = defined(this.indicatorManager.getLatest(atr));
|
||||
}
|
||||
|
||||
// Volume
|
||||
const priceHistory = this.indicatorManager.getPriceHistory(symbol);
|
||||
if (priceHistory) {
|
||||
indicators.volume = at(priceHistory.volume, priceHistory.volume.length - 1);
|
||||
const avgVolume = priceHistory.volume.slice(-20).reduce((a, b) => a + b, 0) / 20;
|
||||
indicators.avg_volume = avgVolume;
|
||||
}
|
||||
|
||||
return indicators;
|
||||
}
|
||||
|
||||
private convertToStrategySignal(
|
||||
tradingSignal: TradingSignal,
|
||||
symbol: string,
|
||||
currentPrice: number
|
||||
): Signal | null {
|
||||
const currentPosition = this.positionManager.getPositionQuantity(symbol);
|
||||
|
||||
// Determine action based on signal and current position
|
||||
let type: 'buy' | 'sell' | 'close';
|
||||
let quantity: number;
|
||||
|
||||
if (tradingSignal.direction === 'buy') {
|
||||
if (currentPosition < 0) {
|
||||
// Close short position
|
||||
type = 'buy';
|
||||
quantity = Math.abs(currentPosition);
|
||||
} else if (currentPosition === 0) {
|
||||
// Open long position
|
||||
type = 'buy';
|
||||
quantity = this.calculateIndicatorPositionSize(symbol, currentPrice, tradingSignal);
|
||||
} else {
|
||||
// Already long
|
||||
return null;
|
||||
}
|
||||
} else if (tradingSignal.direction === 'sell') {
|
||||
if (currentPosition > 0) {
|
||||
// Close long position
|
||||
type = 'sell';
|
||||
quantity = currentPosition;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
type,
|
||||
symbol,
|
||||
strength: tradingSignal.strength,
|
||||
reason: tradingSignal.rules.join(', '),
|
||||
metadata: {
|
||||
...tradingSignal.indicators,
|
||||
quantity,
|
||||
confidence: tradingSignal.confidence,
|
||||
rules: tradingSignal.rules,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private calculateIndicatorPositionSize(
|
||||
symbol: string,
|
||||
price: number,
|
||||
signal: TradingSignal
|
||||
): number {
|
||||
const accountBalance = this.positionManager.getAccountBalance();
|
||||
|
||||
switch (this.indicatorConfig.positionSizing) {
|
||||
case 'fixed': // Fixed percentage of account
|
||||
{
|
||||
const fixedValue = accountBalance * this.indicatorConfig.riskPerTrade * 5;
|
||||
return Math.floor(fixedValue / price);
|
||||
}
|
||||
|
||||
case 'risk': // Risk-based sizing with ATR stop
|
||||
{
|
||||
const atr = signal.indicators.atr;
|
||||
if (atr && this.indicatorConfig.useATRStops) {
|
||||
const stopDistance = atr * this.indicatorConfig.atrMultiplier;
|
||||
return this.positionManager.calculatePositionSize(
|
||||
{
|
||||
accountBalance,
|
||||
riskPerTrade: this.indicatorConfig.riskPerTrade,
|
||||
stopLossDistance: stopDistance,
|
||||
},
|
||||
price
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'kelly': // Kelly criterion based on historical performance
|
||||
{
|
||||
const metrics = this.positionManager.getPerformanceMetrics();
|
||||
if (metrics.totalTrades >= 20) {
|
||||
return this.positionManager.calculateKellySize(
|
||||
metrics.winRate / 100,
|
||||
metrics.avgWin,
|
||||
metrics.avgLoss,
|
||||
price
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'volatility': // Volatility-adjusted sizing
|
||||
{
|
||||
const atrVol = signal.indicators.atr;
|
||||
if (atrVol) {
|
||||
return this.positionManager.calculatePositionSize(
|
||||
{
|
||||
accountBalance,
|
||||
riskPerTrade: this.indicatorConfig.riskPerTrade,
|
||||
volatilityAdjustment: true,
|
||||
atr: atrVol,
|
||||
},
|
||||
price
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Default sizing
|
||||
return this.positionManager.calculatePositionSize(
|
||||
{
|
||||
accountBalance,
|
||||
riskPerTrade: this.indicatorConfig.riskPerTrade,
|
||||
},
|
||||
price
|
||||
);
|
||||
}
|
||||
|
||||
private updatePositionValues(symbol: string, currentPrice: number): void {
|
||||
const prices = new Map([[symbol, currentPrice]]);
|
||||
this.positionManager.updateMarketPrices(prices);
|
||||
}
|
||||
|
||||
private checkExitConditions(symbol: string, currentPrice: number): void {
|
||||
const position = this.positionManager.getPosition(symbol);
|
||||
if (!position) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stopLoss = this.stopLosses.get(symbol);
|
||||
const takeProfit = this.takeProfits.get(symbol);
|
||||
|
||||
// Check stop loss
|
||||
if (stopLoss) {
|
||||
if (
|
||||
(position.quantity > 0 && currentPrice <= stopLoss) ||
|
||||
(position.quantity < 0 && currentPrice >= stopLoss)
|
||||
) {
|
||||
logger.info(`Stop loss triggered for ${symbol} at ${currentPrice}`);
|
||||
this.emit('signal', {
|
||||
type: 'close',
|
||||
symbol,
|
||||
strength: 1,
|
||||
reason: 'Stop loss triggered',
|
||||
metadata: { stopLoss, currentPrice },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check take profit
|
||||
if (takeProfit) {
|
||||
if (
|
||||
(position.quantity > 0 && currentPrice >= takeProfit) ||
|
||||
(position.quantity < 0 && currentPrice <= takeProfit)
|
||||
) {
|
||||
logger.info(`Take profit triggered for ${symbol} at ${currentPrice}`);
|
||||
this.emit('signal', {
|
||||
type: 'close',
|
||||
symbol,
|
||||
strength: 1,
|
||||
reason: 'Take profit triggered',
|
||||
metadata: { takeProfit, currentPrice },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getCurrentPositionMap(): Map<string, { quantity: number; value: number }> {
|
||||
const positionMap = new Map();
|
||||
|
||||
for (const position of this.positionManager.getOpenPositions()) {
|
||||
positionMap.set(position.symbol, {
|
||||
quantity: position.quantity,
|
||||
value: Math.abs(position.quantity * (position.currentPrice || position.avgPrice)),
|
||||
});
|
||||
}
|
||||
|
||||
return positionMap;
|
||||
}
|
||||
|
||||
override async onOrderUpdate(update: StrategyOrderUpdate): Promise<void> {
|
||||
await super.onOrderUpdate(update);
|
||||
|
||||
if (update.status === 'filled' && update.fills?.length > 0) {
|
||||
for (const fill of update.fills) {
|
||||
const trade = {
|
||||
symbol: update.symbol,
|
||||
side: update.side as 'buy' | 'sell',
|
||||
quantity: fill.quantity,
|
||||
price: fill.price,
|
||||
commission: fill.commission || 0,
|
||||
timestamp: new Date(fill.timestamp),
|
||||
};
|
||||
|
||||
const position = this.positionManager.updatePosition(trade);
|
||||
|
||||
// Update risk manager
|
||||
if (typeof fill.pnl === 'number') {
|
||||
this.riskManager.updateAfterTrade(fill.pnl ?? 0);
|
||||
}
|
||||
|
||||
// Set stop loss and take profit for new positions
|
||||
if (this.indicatorConfig.useATRStops && position.quantity !== 0) {
|
||||
const atr = this.indicatorManager.getATR(update.symbol);
|
||||
if (atr) {
|
||||
const currentATR = this.indicatorManager.getLatest(atr);
|
||||
if (currentATR) {
|
||||
const stopDistance = currentATR * this.indicatorConfig.atrMultiplier;
|
||||
const profitDistance = currentATR * this.indicatorConfig.atrMultiplier * 2;
|
||||
|
||||
if (position.quantity > 0) {
|
||||
this.stopLosses.set(update.symbol, fill.price - stopDistance);
|
||||
this.takeProfits.set(update.symbol, fill.price + profitDistance);
|
||||
} else {
|
||||
this.stopLosses.set(update.symbol, fill.price + stopDistance);
|
||||
this.takeProfits.set(update.symbol, fill.price - profitDistance);
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Set stop/take profit for ${update.symbol}: Stop=${this.stopLosses.get(update.symbol)?.toFixed(2)}, TP=${this.takeProfits.get(update.symbol)?.toFixed(2)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear stops if position closed
|
||||
if (position.quantity === 0) {
|
||||
this.stopLosses.delete(update.symbol);
|
||||
this.takeProfits.delete(update.symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override getPerformance() {
|
||||
const basePerf = super.getPerformance();
|
||||
const positionMetrics = this.positionManager.getPerformanceMetrics();
|
||||
const riskMetrics = this.riskManager.getMetrics(this.getCurrentPositionMap());
|
||||
const signalStats = this.signalManager.getSignalStats();
|
||||
|
||||
return {
|
||||
...basePerf,
|
||||
...positionMetrics,
|
||||
risk: riskMetrics,
|
||||
signals: signalStats,
|
||||
};
|
||||
}
|
||||
|
||||
// Daily reset for risk metrics
|
||||
onDayEnd(): void {
|
||||
this.riskManager.resetDaily();
|
||||
logger.info('Daily risk metrics reset');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import {
|
||||
IncrementalIndicators,
|
||||
SignalGenerator,
|
||||
type TradingSignal,
|
||||
} from '../../indicators/TechnicalAnalysis';
|
||||
import type { ExecutionService } from '../../services/ExecutionService';
|
||||
import type { MarketData, StrategyConfig } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
|
||||
/** Example of the common strategy lifecycle with native incremental indicators. */
|
||||
export class IndicatorBasedStrategy extends BaseStrategy {
|
||||
private readonly incrementalIndicators = new IncrementalIndicators();
|
||||
private readonly signalGenerator = new SignalGenerator();
|
||||
private readonly priceHistory = {
|
||||
close: [] as number[],
|
||||
high: [] as number[],
|
||||
low: [] as number[],
|
||||
volume: [] as number[],
|
||||
};
|
||||
private lastSignal: TradingSignal | null = null;
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
super(config, modeManager, executionService);
|
||||
this.incrementalIndicators.createSMA('sma20', 20);
|
||||
this.incrementalIndicators.createSMA('sma50', 50);
|
||||
this.incrementalIndicators.createEMA('ema12', 12);
|
||||
this.incrementalIndicators.createEMA('ema26', 26);
|
||||
this.incrementalIndicators.createRSI('rsi14', 14);
|
||||
}
|
||||
|
||||
protected override updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
const bar = data.data;
|
||||
this.priceHistory.close.push(bar.close);
|
||||
this.priceHistory.high.push(bar.high);
|
||||
this.priceHistory.low.push(bar.low);
|
||||
this.priceHistory.volume.push(bar.volume);
|
||||
for (const values of Object.values(this.priceHistory)) {
|
||||
if (values.length > 100) {
|
||||
values.shift();
|
||||
}
|
||||
}
|
||||
for (const key of ['sma20', 'sma50', 'ema12', 'ema26', 'rsi14']) {
|
||||
this.incrementalIndicators.update(key, bar.close);
|
||||
}
|
||||
}
|
||||
|
||||
protected override async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar' || this.priceHistory.close.length < 50) {
|
||||
return null;
|
||||
}
|
||||
const signal = this.signalGenerator.generateSignals(
|
||||
data.data.symbol,
|
||||
this.priceHistory,
|
||||
data.data.timestamp
|
||||
);
|
||||
this.lastSignal = signal;
|
||||
const minimum = Number(this.config.parameters.minSignalStrength ?? 0.6);
|
||||
if (signal.action === 'HOLD' || signal.strength < minimum) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: signal.action === 'BUY' ? 'buy' : 'sell',
|
||||
symbol: signal.symbol,
|
||||
strength: signal.strength,
|
||||
reason: signal.reason,
|
||||
metadata: { quantity: Number(this.config.parameters.positionSize ?? 100) },
|
||||
};
|
||||
}
|
||||
|
||||
getState() {
|
||||
return {
|
||||
priceHistoryLength: this.priceHistory.close.length,
|
||||
lastSignal: this.lastSignal,
|
||||
config: this.config,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,359 +0,0 @@
|
|||
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');
|
||||
|
||||
export class SimpleMovingAverageCrossover extends BaseStrategy {
|
||||
private priceHistory = new Map<string, number[]>();
|
||||
private lastTradeTime = new Map<string, number>();
|
||||
private barCount = new Map<string, number>();
|
||||
private totalSignals = 0;
|
||||
override getCheckpointVersion() {
|
||||
return 'sma-crossover-original/v2';
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return {
|
||||
priceHistory: [...this.priceHistory],
|
||||
lastSignalBar: [...this.lastTradeTime],
|
||||
barCount: [...this.barCount],
|
||||
totalSignals: this.totalSignals,
|
||||
lastCrossoverType: [],
|
||||
};
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
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;
|
||||
}
|
||||
|
||||
private settings: SmaParameters;
|
||||
private readonly DEBUG_INTERVAL = 10;
|
||||
|
||||
constructor(
|
||||
config: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
const validated = smaConfig(config, 1);
|
||||
super(validated, modeManager, executionService);
|
||||
this.settings = validated.parameters;
|
||||
logger.info(
|
||||
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
|
||||
);
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const price = data.data.close;
|
||||
|
||||
// Update price history
|
||||
if (!this.priceHistory.has(symbol)) {
|
||||
this.priceHistory.set(symbol, []);
|
||||
this.barCount.set(symbol, 0);
|
||||
logger.info(`📊 Starting to track ${symbol} @ ${price}`);
|
||||
}
|
||||
|
||||
const history = defined(this.priceHistory.get(symbol));
|
||||
history.push(price);
|
||||
|
||||
// Increment bar count
|
||||
const currentBar = (this.barCount.get(symbol) || 0) + 1;
|
||||
this.barCount.set(symbol, currentBar);
|
||||
|
||||
// Keep only needed history
|
||||
if (history.length > this.settings.slowPeriod * 2) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Log when we have enough data to start trading
|
||||
if (history.length === this.settings.slowPeriod) {
|
||||
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const symbol = data.data.symbol;
|
||||
const history = this.priceHistory.get(symbol);
|
||||
|
||||
if (!history || history.length <= this.settings.slowPeriod) {
|
||||
if (history && history.length % 5 === 0) {
|
||||
logger.debug(
|
||||
`${symbol} - Not enough history: ${history.length}/${this.settings.slowPeriod + 1} bars`
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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;
|
||||
const timestamp = new Date(data.data.timestamp).toISOString().split('T')[0];
|
||||
|
||||
// Check minimum holding period
|
||||
const currentBar = this.barCount.get(symbol) || 0;
|
||||
const lastTradeBar = this.lastTradeTime.get(symbol) || 0;
|
||||
const barsSinceLastTrade =
|
||||
lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER;
|
||||
|
||||
// Enhanced debugging - log more frequently and when MAs are close
|
||||
const maDiff = fastMA - slowMA;
|
||||
const maDiffPct = (maDiff / slowMA) * 100;
|
||||
const masAreClose = Math.abs(maDiffPct) < 1.0; // Within 1%
|
||||
|
||||
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.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}`);
|
||||
|
||||
if (goldenCross) {
|
||||
logger.info(` 🟢 GOLDEN CROSS DETECTED!`);
|
||||
}
|
||||
if (deathCross) {
|
||||
logger.info(` 🔴 DEATH CROSS DETECTED!`);
|
||||
}
|
||||
}
|
||||
|
||||
// Note: We removed the MIN_HOLDING_BARS check here to allow closing and opening on same bar
|
||||
// The check is now done individually for new position entries
|
||||
|
||||
if (goldenCross) {
|
||||
logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`);
|
||||
logger.info(` Current position: ${currentPosition} shares`);
|
||||
|
||||
// For golden cross, we want to be long
|
||||
if (currentPosition < 0) {
|
||||
// Close short position first
|
||||
logger.info(` Closing short position of ${Math.abs(currentPosition)} shares`);
|
||||
const signal: Signal = {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Golden cross - Closing short position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'golden',
|
||||
price: currentPrice,
|
||||
quantity: Math.abs(currentPosition), // Buy to close short
|
||||
},
|
||||
};
|
||||
|
||||
this.lastTradeTime.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
} else if (currentPosition === 0) {
|
||||
// No position, open long
|
||||
logger.info(` No current position, opening long`);
|
||||
logger.info(
|
||||
` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} > Slow MA: ${slowMA.toFixed(2)}`
|
||||
);
|
||||
logger.info(
|
||||
` Prev Fast MA: ${prevFastMA.toFixed(2)} <= Prev Slow MA: ${prevSlowMA.toFixed(2)}`
|
||||
);
|
||||
|
||||
// Calculate position size
|
||||
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
||||
logger.info(` Opening long position: ${positionSize} shares`);
|
||||
|
||||
const signal: Signal = {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Golden cross - Fast MA crossed above Slow MA',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'golden',
|
||||
price: currentPrice,
|
||||
quantity: positionSize,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastTradeTime.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
} else {
|
||||
logger.info(` ⚠️ Already long, skipping buy signal`);
|
||||
}
|
||||
} else if (deathCross) {
|
||||
logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`);
|
||||
logger.info(` Current position: ${currentPosition} shares`);
|
||||
|
||||
// For death cross, we want to be flat or short
|
||||
if (currentPosition > 0) {
|
||||
// Close long position
|
||||
logger.info(` Closing long position of ${currentPosition} shares`);
|
||||
logger.info(
|
||||
` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} < Slow MA: ${slowMA.toFixed(2)}`
|
||||
);
|
||||
logger.info(
|
||||
` Prev Fast MA: ${prevFastMA.toFixed(2)} >= Prev Slow MA: ${prevSlowMA.toFixed(2)}`
|
||||
);
|
||||
|
||||
const signal: Signal = {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Death cross - Fast MA crossed below Slow MA',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'death',
|
||||
price: currentPrice,
|
||||
quantity: currentPosition,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastTradeTime.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
} else if (currentPosition === 0) {
|
||||
// Open short position for long/short strategy
|
||||
logger.info(` No current position, opening short`);
|
||||
|
||||
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
||||
logger.info(` Opening short position: ${positionSize} shares`);
|
||||
|
||||
const signal: Signal = {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Death cross - Opening short position',
|
||||
metadata: {
|
||||
fastMA,
|
||||
slowMA,
|
||||
prevFastMA,
|
||||
prevSlowMA,
|
||||
crossoverType: 'death',
|
||||
price: currentPrice,
|
||||
quantity: positionSize,
|
||||
},
|
||||
};
|
||||
|
||||
this.lastTradeTime.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
||||
return signal;
|
||||
} else {
|
||||
logger.info(` ⚠️ Already short, skipping sell signal`);
|
||||
}
|
||||
}
|
||||
|
||||
// Log near-crossover conditions
|
||||
const fastApproachingSlow = Math.abs(fastMA - slowMA) / slowMA < 0.01; // Within 1%
|
||||
if (fastApproachingSlow && history.length % 20 === 0) {
|
||||
logger.debug(
|
||||
`${symbol} - MAs converging: Fast MA ${fastMA.toFixed(2)} ~ Slow MA ${slowMA.toFixed(2)} (${((Math.abs(fastMA - slowMA) / slowMA) * 100).toFixed(2)}% diff)`
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
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.settings.positionFraction;
|
||||
const shares = Math.floor(positionValue / price);
|
||||
|
||||
logger.debug(
|
||||
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
|
||||
);
|
||||
|
||||
return Math.max(1, shares); // At least 1 share
|
||||
}
|
||||
|
||||
protected onOrderFilled(fill: StrategyFill): void {
|
||||
const { symbol, side, quantity, price } = fill;
|
||||
|
||||
logger.info(`✅ ${side.toUpperCase()} filled: ${symbol} - ${quantity} shares @ ${price}`);
|
||||
|
||||
// Position tracking is handled by BaseStrategy.onOrderUpdate
|
||||
// Just log the current position
|
||||
const currentPosition = this.getPosition(symbol);
|
||||
logger.info(`Position for ${symbol}: ${currentPosition} shares`);
|
||||
}
|
||||
|
||||
// Override to provide custom order generation
|
||||
protected override async signalToOrder(signal: Signal): Promise<OrderRequest | null> {
|
||||
logger.info(`🔄 Converting signal to order:`, signal);
|
||||
|
||||
const _currentPosition = this.getPosition(signal.symbol);
|
||||
|
||||
// Get position sizing from metadata
|
||||
const quantity = typeof signal.metadata?.quantity === 'number' ? signal.metadata.quantity : 100;
|
||||
|
||||
if (signal.type === 'buy') {
|
||||
const order: OrderRequest = {
|
||||
symbol: signal.symbol,
|
||||
side: 'buy',
|
||||
quantity,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
logger.info(`📈 Generated BUY order:`, order);
|
||||
return order;
|
||||
} else if (signal.type === 'sell') {
|
||||
const order: OrderRequest = {
|
||||
symbol: signal.symbol,
|
||||
side: 'sell',
|
||||
quantity,
|
||||
orderType: 'market',
|
||||
timeInForce: 'DAY',
|
||||
};
|
||||
logger.info(`📉 Generated SELL order:`, order);
|
||||
return order;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,333 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
||||
import { IndicatorManager } from '../indicators/IndicatorManager';
|
||||
import { PositionManager, type PositionSizingParams } from '../position/PositionManager';
|
||||
|
||||
const logger = getLogger('SimpleMovingAverageCrossoverV2');
|
||||
|
||||
export interface SMAStrategyConfig {
|
||||
fastPeriod?: number;
|
||||
slowPeriod?: number;
|
||||
positionSizePct?: number;
|
||||
riskPerTrade?: number;
|
||||
useATRStops?: boolean;
|
||||
minHoldingBars?: number;
|
||||
debugInterval?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refactored SMA Crossover Strategy using new TA library
|
||||
*/
|
||||
export class SimpleMovingAverageCrossoverV2 extends BaseStrategy {
|
||||
private indicatorManager: IndicatorManager;
|
||||
private positionManager: PositionManager;
|
||||
|
||||
// Strategy parameters
|
||||
private readonly indicatorConfig: Required<SMAStrategyConfig>;
|
||||
private lastTradeBar = new Map<string, number>();
|
||||
private barCount = new Map<string, number>();
|
||||
private totalSignals = 0;
|
||||
|
||||
constructor(
|
||||
strategyConfig: StrategyConfig,
|
||||
modeManager: ModeManager,
|
||||
executionService: ExecutionService
|
||||
) {
|
||||
super(strategyConfig, modeManager, executionService);
|
||||
|
||||
// Initialize config with defaults
|
||||
this.indicatorConfig = {
|
||||
fastPeriod: 10,
|
||||
slowPeriod: 20,
|
||||
positionSizePct: 0.1,
|
||||
riskPerTrade: 0.02,
|
||||
useATRStops: true,
|
||||
minHoldingBars: 1,
|
||||
debugInterval: 20,
|
||||
...strategyConfig.parameters,
|
||||
};
|
||||
|
||||
this.indicatorManager = new IndicatorManager();
|
||||
this.positionManager = new PositionManager(
|
||||
Number(strategyConfig.parameters.initialCapital ?? 100000)
|
||||
);
|
||||
|
||||
logger.info(`SimpleMovingAverageCrossoverV2 initialized:`, this.indicatorConfig);
|
||||
}
|
||||
|
||||
protected updateIndicators(data: MarketData): void {
|
||||
if (data.type !== 'bar') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { symbol, timestamp } = data.data;
|
||||
const { open, high, low, close, volume } = data.data;
|
||||
|
||||
// Update bar count
|
||||
const currentBar = (this.barCount.get(symbol) || 0) + 1;
|
||||
this.barCount.set(symbol, currentBar);
|
||||
|
||||
// First time seeing this symbol
|
||||
if (!this.indicatorManager.getHistoryLength(symbol)) {
|
||||
logger.info(`📊 Starting to track ${symbol} @ ${close}`);
|
||||
|
||||
// Setup incremental indicators for real-time updates
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', {
|
||||
type: 'sma',
|
||||
period: this.indicatorConfig.fastPeriod,
|
||||
});
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', {
|
||||
type: 'sma',
|
||||
period: this.indicatorConfig.slowPeriod,
|
||||
});
|
||||
|
||||
if (this.indicatorConfig.useATRStops) {
|
||||
this.indicatorManager.setupIncrementalIndicator(symbol, 'atr', {
|
||||
type: 'sma', // Using SMA as proxy for now
|
||||
period: 14,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Update price history
|
||||
this.indicatorManager.updatePrice({
|
||||
symbol,
|
||||
timestamp,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
});
|
||||
|
||||
// Update position market prices
|
||||
const currentPrices = new Map([[symbol, close]]);
|
||||
this.positionManager.updateMarketPrices(currentPrices);
|
||||
|
||||
// Log when we have enough data
|
||||
const historyLength = this.indicatorManager.getHistoryLength(symbol);
|
||||
if (historyLength === this.indicatorConfig.slowPeriod) {
|
||||
logger.info(`✅ ${symbol} has enough history (${historyLength} bars) to start trading`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
if (data.type !== 'bar') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { symbol, timestamp } = data.data;
|
||||
const { close } = data.data;
|
||||
const historyLength = this.indicatorManager.getHistoryLength(symbol);
|
||||
|
||||
// Need enough data for slow MA
|
||||
if (historyLength < this.indicatorConfig.slowPeriod) {
|
||||
if (historyLength % 5 === 0) {
|
||||
logger.debug(
|
||||
`${symbol} - Building history: ${historyLength}/${this.indicatorConfig.slowPeriod} bars`
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Calculate indicators
|
||||
const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastPeriod);
|
||||
const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowPeriod);
|
||||
|
||||
if (!fastMA || !slowMA) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get current and previous values
|
||||
const currentFast = this.indicatorManager.getLatest(fastMA);
|
||||
const currentSlow = this.indicatorManager.getLatest(slowMA);
|
||||
|
||||
if (currentFast === null || currentSlow === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check for crossovers
|
||||
const goldenCross = this.indicatorManager.checkCrossover(fastMA, slowMA);
|
||||
const deathCross = this.indicatorManager.checkCrossunder(fastMA, slowMA);
|
||||
|
||||
// Get current position
|
||||
const currentPosition = this.positionManager.getPositionQuantity(symbol);
|
||||
const currentBar = this.barCount.get(symbol) || 0;
|
||||
const lastTradeBar = this.lastTradeBar.get(symbol) || 0;
|
||||
const barsSinceLastTrade =
|
||||
lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER;
|
||||
|
||||
// Enhanced debugging
|
||||
const maDiff = currentFast - currentSlow;
|
||||
const maDiffPct = (maDiff / currentSlow) * 100;
|
||||
const shouldLog =
|
||||
historyLength % this.indicatorConfig.debugInterval === 0 ||
|
||||
Math.abs(maDiffPct) < 1.0 ||
|
||||
goldenCross ||
|
||||
deathCross;
|
||||
|
||||
if (shouldLog) {
|
||||
const dateStr = new Date(timestamp).toISOString().split('T')[0];
|
||||
logger.info(`${symbol} @ ${dateStr} [Bar ${currentBar}]:`);
|
||||
logger.info(` Price: $${close.toFixed(2)}`);
|
||||
logger.info(` Fast MA (${this.indicatorConfig.fastPeriod}): $${currentFast.toFixed(2)}`);
|
||||
logger.info(` Slow MA (${this.indicatorConfig.slowPeriod}): $${currentSlow.toFixed(2)}`);
|
||||
logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`);
|
||||
logger.info(` Position: ${currentPosition} shares`);
|
||||
|
||||
// Show additional indicators if available
|
||||
const rsi = this.indicatorManager.getRSI(symbol);
|
||||
if (rsi) {
|
||||
const currentRSI = this.indicatorManager.getLatest(rsi);
|
||||
logger.info(` RSI: ${currentRSI?.toFixed(2)}`);
|
||||
}
|
||||
|
||||
if (goldenCross) {
|
||||
logger.info(` 🟢 GOLDEN CROSS DETECTED!`);
|
||||
}
|
||||
if (deathCross) {
|
||||
logger.info(` 🔴 DEATH CROSS DETECTED!`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check minimum holding period
|
||||
if (barsSinceLastTrade < this.indicatorConfig.minHoldingBars && lastTradeBar > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Position sizing parameters
|
||||
const sizingParams: PositionSizingParams = {
|
||||
accountBalance: this.positionManager.getAccountBalance(),
|
||||
riskPerTrade: this.indicatorConfig.riskPerTrade,
|
||||
volatilityAdjustment: this.indicatorConfig.useATRStops,
|
||||
};
|
||||
|
||||
if (this.indicatorConfig.useATRStops) {
|
||||
const atr = this.indicatorManager.getATR(symbol);
|
||||
if (atr) {
|
||||
sizingParams.atr = this.indicatorManager.getLatest(atr) || undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate signals
|
||||
if (goldenCross) {
|
||||
logger.info(`🟢 Golden cross detected for ${symbol}`);
|
||||
|
||||
if (currentPosition < 0) {
|
||||
// Close short position
|
||||
this.lastTradeBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
return {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Golden cross - Closing short position',
|
||||
metadata: {
|
||||
fastMA: currentFast,
|
||||
slowMA: currentSlow,
|
||||
crossoverType: 'golden',
|
||||
price: close,
|
||||
quantity: Math.abs(currentPosition),
|
||||
},
|
||||
};
|
||||
} else if (currentPosition === 0) {
|
||||
// Calculate position size
|
||||
const positionSize = this.positionManager.calculatePositionSize(sizingParams, close);
|
||||
|
||||
logger.info(` Opening long position: ${positionSize} shares`);
|
||||
logger.info(` Account balance: $${sizingParams.accountBalance.toFixed(2)}`);
|
||||
|
||||
this.lastTradeBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
|
||||
return {
|
||||
type: 'buy',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Golden cross - Fast MA crossed above Slow MA',
|
||||
metadata: {
|
||||
fastMA: currentFast,
|
||||
slowMA: currentSlow,
|
||||
crossoverType: 'golden',
|
||||
price: close,
|
||||
quantity: positionSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
} else if (deathCross && currentPosition > 0) {
|
||||
logger.info(`🔴 Death cross detected for ${symbol}`);
|
||||
|
||||
this.lastTradeBar.set(symbol, currentBar);
|
||||
this.totalSignals++;
|
||||
|
||||
return {
|
||||
type: 'sell',
|
||||
symbol,
|
||||
strength: 0.8,
|
||||
reason: 'Death cross - Fast MA crossed below Slow MA',
|
||||
metadata: {
|
||||
fastMA: currentFast,
|
||||
slowMA: currentSlow,
|
||||
crossoverType: 'death',
|
||||
price: close,
|
||||
quantity: currentPosition,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
override async onOrderUpdate(update: StrategyOrderUpdate): Promise<void> {
|
||||
await super.onOrderUpdate(update);
|
||||
|
||||
// Update position manager with fills
|
||||
if (update.status === 'filled' && update.fills?.length > 0) {
|
||||
for (const fill of update.fills) {
|
||||
this.positionManager.updatePosition({
|
||||
symbol: update.symbol,
|
||||
side: update.side,
|
||||
quantity: fill.quantity,
|
||||
price: fill.price,
|
||||
commission: fill.commission || 0,
|
||||
timestamp: new Date(fill.timestamp),
|
||||
});
|
||||
}
|
||||
|
||||
// Log performance metrics periodically
|
||||
if (this.totalSignals % 5 === 0) {
|
||||
const metrics = this.positionManager.getPerformanceMetrics();
|
||||
logger.info('📊 Strategy Performance:', {
|
||||
trades: metrics.totalTrades,
|
||||
winRate: `${metrics.winRate.toFixed(2)}%`,
|
||||
totalPnL: `$${metrics.totalPnl.toFixed(2)}`,
|
||||
returnPct: `${metrics.returnPct.toFixed(2)}%`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override getPerformance() {
|
||||
const metrics = this.positionManager.getPerformanceMetrics();
|
||||
return {
|
||||
...super.getPerformance(),
|
||||
...metrics,
|
||||
totalSignals: this.totalSignals,
|
||||
openPositions: this.positionManager.getOpenPositions(),
|
||||
};
|
||||
}
|
||||
|
||||
// Optional: Get current state for debugging
|
||||
getState() {
|
||||
return {
|
||||
config: this.indicatorConfig,
|
||||
totalSignals: this.totalSignals,
|
||||
performance: this.getPerformance(),
|
||||
positions: Array.from(this.positions.entries()),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,7 @@ interface MLModelConfig {
|
|||
minTrainingSize: number;
|
||||
}
|
||||
|
||||
/** Optional run-local experiment; deliberately lacks a durable paper checkpoint contract. */
|
||||
export class MLEnhancedStrategy extends BaseStrategy {
|
||||
private tensorflow: typeof tf | undefined;
|
||||
private get tf(): typeof tf {
|
||||
|
|
@ -1,337 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { IncrementalIndicators, TechnicalAnalysis } from '../../indicators/TechnicalAnalysis';
|
||||
|
||||
const logger = getLogger('IndicatorManager');
|
||||
|
||||
export interface IndicatorConfig {
|
||||
type: 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger' | 'stochastic' | 'atr';
|
||||
period?: number;
|
||||
fastPeriod?: number;
|
||||
slowPeriod?: number;
|
||||
signalPeriod?: number;
|
||||
stdDev?: number;
|
||||
kPeriod?: number;
|
||||
dPeriod?: number;
|
||||
smoothK?: number;
|
||||
}
|
||||
|
||||
export interface PriceData {
|
||||
symbol: string;
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages technical indicators for a strategy
|
||||
* Handles both batch and incremental calculations
|
||||
*/
|
||||
export class IndicatorManager {
|
||||
private ta: TechnicalAnalysis;
|
||||
private incrementalIndicators: IncrementalIndicators;
|
||||
private priceHistory: Map<
|
||||
string,
|
||||
{
|
||||
open: number[];
|
||||
high: number[];
|
||||
low: number[];
|
||||
close: number[];
|
||||
volume: number[];
|
||||
}
|
||||
> = new Map();
|
||||
|
||||
private indicatorCache: Map<string, Map<string, unknown>> = new Map();
|
||||
private maxHistoryLength: number;
|
||||
|
||||
constructor(maxHistoryLength = 500) {
|
||||
this.ta = new TechnicalAnalysis();
|
||||
this.incrementalIndicators = new IncrementalIndicators();
|
||||
this.maxHistoryLength = maxHistoryLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update price history with new data
|
||||
*/
|
||||
updatePrice(data: PriceData): void {
|
||||
const { symbol, open, high, low, close, volume } = data;
|
||||
|
||||
if (!this.priceHistory.has(symbol)) {
|
||||
this.priceHistory.set(symbol, {
|
||||
open: [],
|
||||
high: [],
|
||||
low: [],
|
||||
close: [],
|
||||
volume: [],
|
||||
});
|
||||
}
|
||||
|
||||
const history = defined(this.priceHistory.get(symbol));
|
||||
|
||||
// Add new data
|
||||
history.open.push(open);
|
||||
history.high.push(high);
|
||||
history.low.push(low);
|
||||
history.close.push(close);
|
||||
history.volume.push(volume);
|
||||
|
||||
// Trim to max length
|
||||
if (history.close.length > this.maxHistoryLength) {
|
||||
history.open.shift();
|
||||
history.high.shift();
|
||||
history.low.shift();
|
||||
history.close.shift();
|
||||
history.volume.shift();
|
||||
}
|
||||
|
||||
// Clear cache for this symbol as data has changed
|
||||
this.indicatorCache.delete(symbol);
|
||||
|
||||
// Update incremental indicators
|
||||
this.updateIncrementalIndicators(symbol, close);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get price history for a symbol
|
||||
*/
|
||||
getPriceHistory(symbol: string) {
|
||||
return this.priceHistory.get(symbol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of price bars for a symbol
|
||||
*/
|
||||
getHistoryLength(symbol: string): number {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
return history ? history.close.length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate SMA
|
||||
*/
|
||||
getSMA(symbol: string, period: number): number[] | null {
|
||||
const cacheKey = `sma_${period}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < period) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.sma(history.close, period);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate EMA
|
||||
*/
|
||||
getEMA(symbol: string, period: number): number[] | null {
|
||||
const cacheKey = `ema_${period}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < period) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.ema(history.close, period);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate RSI
|
||||
*/
|
||||
getRSI(symbol: string, period: number = 14): number[] | null {
|
||||
const cacheKey = `rsi_${period}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < period + 1) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.rsi(history.close, period);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate MACD
|
||||
*/
|
||||
getMACD(symbol: string, fastPeriod = 12, slowPeriod = 26, signalPeriod = 9) {
|
||||
const cacheKey = `macd_${fastPeriod}_${slowPeriod}_${signalPeriod}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < slowPeriod + signalPeriod) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.macd(history.close, fastPeriod, slowPeriod, signalPeriod);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Bollinger Bands
|
||||
*/
|
||||
getBollingerBands(symbol: string, period = 20, stdDev = 2) {
|
||||
const cacheKey = `bb_${period}_${stdDev}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < period) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.bollingerBands(history.close, period, stdDev);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Stochastic
|
||||
*/
|
||||
getStochastic(symbol: string, kPeriod = 14, dPeriod = 3, smoothK = 1) {
|
||||
const cacheKey = `stoch_${kPeriod}_${dPeriod}_${smoothK}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < kPeriod) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.stochastic(
|
||||
history.high,
|
||||
history.low,
|
||||
history.close,
|
||||
kPeriod,
|
||||
dPeriod,
|
||||
smoothK
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate ATR
|
||||
*/
|
||||
getATR(symbol: string, period = 14): number[] | null {
|
||||
const cacheKey = `atr_${period}`;
|
||||
return this.getCachedOrCalculate(symbol, cacheKey, () => {
|
||||
const history = this.priceHistory.get(symbol);
|
||||
if (!history || history.close.length < period + 1) {
|
||||
return null;
|
||||
}
|
||||
return this.ta.atr(history.high, history.low, history.close, period);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest value from an indicator
|
||||
*/
|
||||
getLatest(values: number[] | null): number | null {
|
||||
if (!values || values.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return values[values.length - 1] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for crossover
|
||||
*/
|
||||
checkCrossover(series1: number[] | null, series2: number[] | null): boolean {
|
||||
if (!series1 || !series2) {
|
||||
return false;
|
||||
}
|
||||
return TechnicalAnalysis.crossover(series1, series2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for crossunder
|
||||
*/
|
||||
checkCrossunder(series1: number[] | null, series2: number[] | null): boolean {
|
||||
if (!series1 || !series2) {
|
||||
return false;
|
||||
}
|
||||
return TechnicalAnalysis.crossunder(series1, series2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup incremental indicators
|
||||
*/
|
||||
setupIncrementalIndicator(symbol: string, name: string, config: IndicatorConfig): void {
|
||||
const key = `${symbol}_${name}`;
|
||||
|
||||
switch (config.type) {
|
||||
case 'sma':
|
||||
this.incrementalIndicators.createSMA(key, defined(config.period));
|
||||
break;
|
||||
case 'ema':
|
||||
this.incrementalIndicators.createEMA(key, defined(config.period));
|
||||
break;
|
||||
case 'rsi':
|
||||
this.incrementalIndicators.createRSI(key, defined(config.period));
|
||||
break;
|
||||
default:
|
||||
logger.warn(`Incremental indicator type ${config.type} not supported`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get incremental indicator value
|
||||
*/
|
||||
getIncrementalValue(symbol: string, name: string): number | null {
|
||||
const key = `${symbol}_${name}`;
|
||||
return this.incrementalIndicators.current(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all data for a symbol
|
||||
*/
|
||||
clearSymbol(symbol: string): void {
|
||||
this.priceHistory.delete(symbol);
|
||||
this.indicatorCache.delete(symbol);
|
||||
|
||||
// Reset incremental indicators for this symbol
|
||||
for (const [key, indicator] of this.incrementalIndicators.entries()) {
|
||||
if (key.startsWith(`${symbol}_`)) {
|
||||
if ('reset' in indicator) {
|
||||
indicator.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all data
|
||||
*/
|
||||
clearAll(): void {
|
||||
this.priceHistory.clear();
|
||||
this.indicatorCache.clear();
|
||||
this.incrementalIndicators.resetAll();
|
||||
}
|
||||
|
||||
private getCachedOrCalculate<T>(
|
||||
symbol: string,
|
||||
cacheKey: string,
|
||||
calculator: () => T | null
|
||||
): T | null {
|
||||
if (!this.indicatorCache.has(symbol)) {
|
||||
this.indicatorCache.set(symbol, new Map());
|
||||
}
|
||||
|
||||
const symbolCache = defined(this.indicatorCache.get(symbol));
|
||||
|
||||
if (symbolCache.has(cacheKey)) {
|
||||
return symbolCache.get(cacheKey) as T;
|
||||
}
|
||||
|
||||
const result = calculator();
|
||||
if (result !== null) {
|
||||
symbolCache.set(cacheKey, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private updateIncrementalIndicators(symbol: string, price: number): void {
|
||||
// Update all incremental indicators for this symbol
|
||||
for (const [key] of this.incrementalIndicators.entries()) {
|
||||
if (key.startsWith(`${symbol}_`)) {
|
||||
try {
|
||||
this.incrementalIndicators.update(key, price);
|
||||
} catch (error) {
|
||||
logger.error(`Error updating incremental indicator ${key}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,304 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('PositionManager');
|
||||
|
||||
export interface Position {
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
avgPrice: number;
|
||||
currentPrice?: number;
|
||||
unrealizedPnl?: number;
|
||||
realizedPnl: number;
|
||||
openTime: Date;
|
||||
lastUpdateTime: Date;
|
||||
}
|
||||
|
||||
export interface Trade {
|
||||
symbol: string;
|
||||
side: 'buy' | 'sell';
|
||||
quantity: number;
|
||||
price: number;
|
||||
commission: number;
|
||||
timestamp: Date;
|
||||
pnl?: number;
|
||||
}
|
||||
|
||||
export interface PositionSizingParams {
|
||||
accountBalance: number;
|
||||
riskPerTrade: number; // As percentage (e.g., 0.02 for 2%)
|
||||
stopLossDistance?: number; // Price distance for stop loss
|
||||
maxPositionSize?: number; // Max % of account in one position
|
||||
volatilityAdjustment?: boolean;
|
||||
atr?: number; // For volatility-based sizing
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages positions and calculates position sizes
|
||||
*/
|
||||
export class PositionManager {
|
||||
private positions: Map<string, Position> = new Map();
|
||||
private trades: Trade[] = [];
|
||||
private accountBalance: number;
|
||||
private initialBalance: number;
|
||||
|
||||
constructor(initialBalance: number = 100000) {
|
||||
this.initialBalance = initialBalance;
|
||||
this.accountBalance = initialBalance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update position with a new trade
|
||||
*/
|
||||
updatePosition(trade: Trade): Position {
|
||||
const { symbol, side, quantity, price, commission } = trade;
|
||||
let position = this.positions.get(symbol);
|
||||
|
||||
if (!position) {
|
||||
// New position
|
||||
position = {
|
||||
symbol,
|
||||
quantity: side === 'buy' ? quantity : -quantity,
|
||||
avgPrice: price,
|
||||
realizedPnl: -commission,
|
||||
openTime: trade.timestamp,
|
||||
lastUpdateTime: trade.timestamp,
|
||||
};
|
||||
} else {
|
||||
const oldQuantity = position.quantity;
|
||||
const newQuantity = side === 'buy' ? oldQuantity + quantity : oldQuantity - quantity;
|
||||
|
||||
if (Math.sign(oldQuantity) !== Math.sign(newQuantity) && oldQuantity !== 0) {
|
||||
// Position flip or close
|
||||
const closedQuantity = Math.min(Math.abs(oldQuantity), quantity);
|
||||
const pnl = this.calculatePnl(
|
||||
position.avgPrice,
|
||||
price,
|
||||
closedQuantity,
|
||||
oldQuantity > 0 ? 'sell' : 'buy'
|
||||
);
|
||||
|
||||
position.realizedPnl += pnl - commission;
|
||||
trade.pnl = pnl - commission;
|
||||
|
||||
// Update average price if position continues
|
||||
if (Math.abs(newQuantity) > 0.0001) {
|
||||
position.avgPrice = price;
|
||||
}
|
||||
} else if (Math.sign(oldQuantity) === Math.sign(newQuantity) || oldQuantity === 0) {
|
||||
// Adding to position
|
||||
const totalCost = Math.abs(oldQuantity) * position.avgPrice + quantity * price;
|
||||
const totalQuantity = Math.abs(oldQuantity) + quantity;
|
||||
position.avgPrice = totalCost / totalQuantity;
|
||||
position.realizedPnl -= commission;
|
||||
}
|
||||
|
||||
position.quantity = newQuantity;
|
||||
position.lastUpdateTime = trade.timestamp;
|
||||
}
|
||||
|
||||
// Store or remove position
|
||||
if (Math.abs(position.quantity) < 0.0001) {
|
||||
this.positions.delete(symbol);
|
||||
logger.info(
|
||||
`Closed position for ${symbol}, realized P&L: $${position.realizedPnl.toFixed(2)}`
|
||||
);
|
||||
} else {
|
||||
this.positions.set(symbol, position);
|
||||
}
|
||||
|
||||
// Record trade
|
||||
this.trades.push(trade);
|
||||
|
||||
// Update account balance
|
||||
if (trade.pnl !== undefined) {
|
||||
this.accountBalance += trade.pnl;
|
||||
}
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current position for a symbol
|
||||
*/
|
||||
getPosition(symbol: string): Position | undefined {
|
||||
return this.positions.get(symbol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get position quantity
|
||||
*/
|
||||
getPositionQuantity(symbol: string): number {
|
||||
const position = this.positions.get(symbol);
|
||||
return position ? position.quantity : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if has position
|
||||
*/
|
||||
hasPosition(symbol: string): boolean {
|
||||
const position = this.positions.get(symbol);
|
||||
return position !== undefined && Math.abs(position.quantity) > 0.0001;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all open positions
|
||||
*/
|
||||
getOpenPositions(): Position[] {
|
||||
return Array.from(this.positions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Update market prices for positions
|
||||
*/
|
||||
updateMarketPrices(prices: Map<string, number>): void {
|
||||
for (const [symbol, position] of this.positions) {
|
||||
const currentPrice = prices.get(symbol);
|
||||
if (currentPrice) {
|
||||
position.currentPrice = currentPrice;
|
||||
position.unrealizedPnl = this.calculatePnl(
|
||||
position.avgPrice,
|
||||
currentPrice,
|
||||
Math.abs(position.quantity),
|
||||
position.quantity > 0 ? 'sell' : 'buy'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate position size based on risk parameters
|
||||
*/
|
||||
calculatePositionSize(params: PositionSizingParams, currentPrice: number): number {
|
||||
const {
|
||||
accountBalance,
|
||||
riskPerTrade,
|
||||
stopLossDistance,
|
||||
maxPositionSize = 0.25,
|
||||
volatilityAdjustment = false,
|
||||
atr,
|
||||
} = params;
|
||||
|
||||
let positionSize: number;
|
||||
|
||||
if (stopLossDistance && stopLossDistance > 0) {
|
||||
// Risk-based position sizing
|
||||
const riskAmount = accountBalance * riskPerTrade;
|
||||
positionSize = Math.floor(riskAmount / stopLossDistance);
|
||||
} else if (volatilityAdjustment && atr) {
|
||||
// Volatility-based position sizing
|
||||
const riskAmount = accountBalance * riskPerTrade;
|
||||
const stopDistance = atr * 2; // 2 ATR stop
|
||||
positionSize = Math.floor(riskAmount / stopDistance);
|
||||
} else {
|
||||
// Fixed percentage position sizing
|
||||
const positionValue = accountBalance * riskPerTrade * 10; // Simplified
|
||||
positionSize = Math.floor(positionValue / currentPrice);
|
||||
}
|
||||
|
||||
// Apply max position size limit
|
||||
const maxShares = Math.floor((accountBalance * maxPositionSize) / currentPrice);
|
||||
positionSize = Math.min(positionSize, maxShares);
|
||||
|
||||
// Ensure minimum position size
|
||||
return Math.max(1, positionSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Kelly Criterion position size
|
||||
*/
|
||||
calculateKellySize(
|
||||
winRate: number,
|
||||
avgWin: number,
|
||||
avgLoss: number,
|
||||
currentPrice: number
|
||||
): number {
|
||||
if (avgLoss === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const b = avgWin / avgLoss;
|
||||
const p = winRate;
|
||||
const q = 1 - p;
|
||||
const kelly = (p * b - q) / b;
|
||||
|
||||
// Apply Kelly fraction (usually 0.25 to be conservative)
|
||||
const kellyFraction = 0.25;
|
||||
const percentageOfCapital = Math.max(0, Math.min(0.25, kelly * kellyFraction));
|
||||
|
||||
const positionValue = this.accountBalance * percentageOfCapital;
|
||||
return Math.max(1, Math.floor(positionValue / currentPrice));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get performance metrics
|
||||
*/
|
||||
getPerformanceMetrics() {
|
||||
const totalTrades = this.trades.length;
|
||||
const winningTrades = this.trades.filter(t => (t.pnl || 0) > 0);
|
||||
const losingTrades = this.trades.filter(t => (t.pnl || 0) < 0);
|
||||
|
||||
const totalPnl = this.trades.reduce((sum, t) => sum + (t.pnl || 0), 0);
|
||||
const unrealizedPnl = Array.from(this.positions.values()).reduce(
|
||||
(sum, p) => sum + (p.unrealizedPnl || 0),
|
||||
0
|
||||
);
|
||||
|
||||
const winRate = totalTrades > 0 ? winningTrades.length / totalTrades : 0;
|
||||
const avgWin =
|
||||
winningTrades.length > 0
|
||||
? winningTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / winningTrades.length
|
||||
: 0;
|
||||
const avgLoss =
|
||||
losingTrades.length > 0
|
||||
? Math.abs(losingTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / losingTrades.length)
|
||||
: 0;
|
||||
|
||||
const profitFactor =
|
||||
avgLoss > 0 ? (avgWin * winningTrades.length) / (avgLoss * losingTrades.length) : 0;
|
||||
|
||||
return {
|
||||
totalTrades,
|
||||
winningTrades: winningTrades.length,
|
||||
losingTrades: losingTrades.length,
|
||||
winRate: winRate * 100,
|
||||
totalPnl,
|
||||
unrealizedPnl,
|
||||
totalEquity: this.accountBalance + unrealizedPnl,
|
||||
avgWin,
|
||||
avgLoss,
|
||||
profitFactor,
|
||||
returnPct: ((this.accountBalance - this.initialBalance) / this.initialBalance) * 100,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get account balance
|
||||
*/
|
||||
getAccountBalance(): number {
|
||||
return this.accountBalance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total equity (balance + unrealized P&L)
|
||||
*/
|
||||
getTotalEquity(): number {
|
||||
const unrealizedPnl = Array.from(this.positions.values()).reduce(
|
||||
(sum, p) => sum + (p.unrealizedPnl || 0),
|
||||
0
|
||||
);
|
||||
return this.accountBalance + unrealizedPnl;
|
||||
}
|
||||
|
||||
private calculatePnl(
|
||||
entryPrice: number,
|
||||
exitPrice: number,
|
||||
quantity: number,
|
||||
side: 'buy' | 'sell'
|
||||
): number {
|
||||
if (side === 'sell') {
|
||||
return (exitPrice - entryPrice) * quantity;
|
||||
} else {
|
||||
return (entryPrice - exitPrice) * quantity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,275 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/utils';
|
||||
|
||||
const logger = getLogger('RiskManager');
|
||||
|
||||
export interface RiskLimits {
|
||||
maxPositions?: number;
|
||||
maxPositionSizePct?: number; // Max % of account per position
|
||||
maxTotalExposurePct?: number; // Max % of account in all positions
|
||||
maxDailyLossPct?: number; // Max daily loss as % of account
|
||||
maxDrawdownPct?: number; // Max drawdown allowed
|
||||
maxConsecutiveLosses?: number;
|
||||
minWinRate?: number; // Minimum win rate to continue trading
|
||||
}
|
||||
|
||||
export interface RiskMetrics {
|
||||
currentExposure: number;
|
||||
currentExposurePct: number;
|
||||
dailyPnl: number;
|
||||
dailyPnlPct: number;
|
||||
currentDrawdown: number;
|
||||
currentDrawdownPct: number;
|
||||
maxDrawdown: number;
|
||||
maxDrawdownPct: number;
|
||||
consecutiveLosses: number;
|
||||
volatility: number;
|
||||
sharpeRatio: number;
|
||||
var95: number; // Value at Risk 95%
|
||||
}
|
||||
|
||||
export interface RiskCheckResult {
|
||||
allowed: boolean;
|
||||
reason?: string;
|
||||
adjustedSize?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages risk limits and calculates risk metrics
|
||||
*/
|
||||
export class RiskManager {
|
||||
private limits: Required<RiskLimits>;
|
||||
private dailyPnl = 0;
|
||||
private dailyStartBalance: number;
|
||||
private peakBalance: number;
|
||||
private consecutiveLosses = 0;
|
||||
private dailyReturns: number[] = [];
|
||||
private readonly lookbackDays = 30;
|
||||
|
||||
constructor(
|
||||
private accountBalance: number,
|
||||
limits: RiskLimits = {}
|
||||
) {
|
||||
this.limits = {
|
||||
maxPositions: 10,
|
||||
maxPositionSizePct: 0.1,
|
||||
maxTotalExposurePct: 0.6,
|
||||
maxDailyLossPct: 0.05,
|
||||
maxDrawdownPct: 0.2,
|
||||
maxConsecutiveLosses: 5,
|
||||
minWinRate: 0.3,
|
||||
...limits,
|
||||
};
|
||||
|
||||
this.dailyStartBalance = accountBalance;
|
||||
this.peakBalance = accountBalance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a new position is allowed
|
||||
*/
|
||||
checkNewPosition(
|
||||
symbol: string,
|
||||
proposedSize: number,
|
||||
price: number,
|
||||
currentPositions: Map<string, { quantity: number; value: number }>
|
||||
): RiskCheckResult {
|
||||
const proposedValue = Math.abs(proposedSize * price);
|
||||
const proposedPct = proposedValue / this.accountBalance;
|
||||
|
||||
// Check max position size
|
||||
if (proposedPct > this.limits.maxPositionSizePct) {
|
||||
const maxValue = this.accountBalance * this.limits.maxPositionSizePct;
|
||||
const adjustedSize = Math.floor(maxValue / price);
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
reason: `Position size reduced from ${proposedSize} to ${adjustedSize} (max ${(this.limits.maxPositionSizePct * 100).toFixed(1)}% per position)`,
|
||||
adjustedSize,
|
||||
};
|
||||
}
|
||||
|
||||
// Check max positions
|
||||
if (currentPositions.size >= this.limits.maxPositions && !currentPositions.has(symbol)) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Maximum number of positions (${this.limits.maxPositions}) reached`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check total exposure
|
||||
let totalExposure = proposedValue;
|
||||
for (const [sym, pos] of currentPositions) {
|
||||
if (sym !== symbol) {
|
||||
totalExposure += Math.abs(pos.value);
|
||||
}
|
||||
}
|
||||
|
||||
const totalExposurePct = totalExposure / this.accountBalance;
|
||||
if (totalExposurePct > this.limits.maxTotalExposurePct) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Total exposure would be ${(totalExposurePct * 100).toFixed(1)}% (max ${(this.limits.maxTotalExposurePct * 100).toFixed(1)}%)`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check daily loss limit
|
||||
const dailyLossPct = Math.abs(this.dailyPnl) / this.dailyStartBalance;
|
||||
if (this.dailyPnl < 0 && dailyLossPct >= this.limits.maxDailyLossPct) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Daily loss limit reached (${(dailyLossPct * 100).toFixed(1)}%)`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check consecutive losses
|
||||
if (this.consecutiveLosses >= this.limits.maxConsecutiveLosses) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Maximum consecutive losses (${this.limits.maxConsecutiveLosses}) reached`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check drawdown
|
||||
const currentDrawdownPct = (this.peakBalance - this.accountBalance) / this.peakBalance;
|
||||
if (currentDrawdownPct >= this.limits.maxDrawdownPct) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Maximum drawdown reached (${(currentDrawdownPct * 100).toFixed(1)}%)`,
|
||||
};
|
||||
}
|
||||
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update metrics after a trade
|
||||
*/
|
||||
updateAfterTrade(pnl: number): void {
|
||||
this.dailyPnl += pnl;
|
||||
this.accountBalance += pnl;
|
||||
|
||||
if (pnl < 0) {
|
||||
this.consecutiveLosses++;
|
||||
} else if (pnl > 0) {
|
||||
this.consecutiveLosses = 0;
|
||||
}
|
||||
|
||||
if (this.accountBalance > this.peakBalance) {
|
||||
this.peakBalance = this.accountBalance;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset daily metrics
|
||||
*/
|
||||
resetDaily(): void {
|
||||
// Record daily return
|
||||
const dailyReturn = (this.accountBalance - this.dailyStartBalance) / this.dailyStartBalance;
|
||||
this.dailyReturns.push(dailyReturn);
|
||||
|
||||
// Keep only recent returns
|
||||
if (this.dailyReturns.length > this.lookbackDays) {
|
||||
this.dailyReturns.shift();
|
||||
}
|
||||
|
||||
this.dailyPnl = 0;
|
||||
this.dailyStartBalance = this.accountBalance;
|
||||
|
||||
logger.info(
|
||||
`Daily reset - Balance: $${this.accountBalance.toFixed(2)}, Daily return: ${(dailyReturn * 100).toFixed(2)}%`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate current risk metrics
|
||||
*/
|
||||
getMetrics(currentPositions: Map<string, { quantity: number; value: number }>): RiskMetrics {
|
||||
let currentExposure = 0;
|
||||
for (const pos of currentPositions.values()) {
|
||||
currentExposure += Math.abs(pos.value);
|
||||
}
|
||||
|
||||
const currentDrawdown = this.peakBalance - this.accountBalance;
|
||||
const currentDrawdownPct = this.peakBalance > 0 ? currentDrawdown / this.peakBalance : 0;
|
||||
|
||||
return {
|
||||
currentExposure,
|
||||
currentExposurePct: currentExposure / this.accountBalance,
|
||||
dailyPnl: this.dailyPnl,
|
||||
dailyPnlPct: this.dailyPnl / this.dailyStartBalance,
|
||||
currentDrawdown,
|
||||
currentDrawdownPct,
|
||||
maxDrawdown: Math.max(currentDrawdown, 0),
|
||||
maxDrawdownPct: Math.max(currentDrawdownPct, 0),
|
||||
consecutiveLosses: this.consecutiveLosses,
|
||||
volatility: this.calculateVolatility(),
|
||||
sharpeRatio: this.calculateSharpeRatio(),
|
||||
var95: this.calculateVaR(0.95),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update risk limits
|
||||
*/
|
||||
updateLimits(newLimits: Partial<RiskLimits>): void {
|
||||
this.limits = { ...this.limits, ...newLimits };
|
||||
logger.info('Risk limits updated:', this.limits);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current limits
|
||||
*/
|
||||
getLimits(): Required<RiskLimits> {
|
||||
return { ...this.limits };
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate portfolio volatility
|
||||
*/
|
||||
private calculateVolatility(): number {
|
||||
if (this.dailyReturns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length;
|
||||
const variance =
|
||||
this.dailyReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) /
|
||||
(this.dailyReturns.length - 1);
|
||||
|
||||
return Math.sqrt(variance) * Math.sqrt(252); // Annualized
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Sharpe ratio
|
||||
*/
|
||||
private calculateSharpeRatio(riskFreeRate = 0.02): number {
|
||||
if (this.dailyReturns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const avgReturn = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length;
|
||||
const annualizedReturn = avgReturn * 252;
|
||||
const volatility = this.calculateVolatility();
|
||||
|
||||
if (volatility === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (annualizedReturn - riskFreeRate) / volatility;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Value at Risk
|
||||
*/
|
||||
private calculateVaR(confidence: number): number {
|
||||
if (this.dailyReturns.length < 5) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b);
|
||||
const index = Math.floor((1 - confidence) * sortedReturns.length);
|
||||
|
||||
return Math.abs(at(sortedReturns, index) * this.accountBalance);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
import { defined } from '@stock-bot/invariants';
|
||||
import { type MarketData } from '../../types';
|
||||
import { RustStrategy, type Signal } from '../RustStrategy';
|
||||
|
||||
interface BarData {
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export class SimpleMovingAverageCrossoverRust extends RustStrategy {
|
||||
private priceHistory: Map<string, number[]> = new Map();
|
||||
private lastCrossover: Map<string, 'golden' | 'death' | null> = new Map();
|
||||
private barsSinceSignal: Map<string, number> = new Map();
|
||||
|
||||
private fastPeriod: number;
|
||||
private slowPeriod: number;
|
||||
private minHoldingBars: number;
|
||||
|
||||
constructor(
|
||||
parameters: {
|
||||
fastPeriod?: number;
|
||||
slowPeriod?: number;
|
||||
minHoldingBars?: number;
|
||||
} = {}
|
||||
) {
|
||||
super('SimpleMovingAverageCrossover', `sma-crossover-${Date.now()}`, parameters);
|
||||
|
||||
this.fastPeriod = parameters.fastPeriod || 5;
|
||||
this.slowPeriod = parameters.slowPeriod || 15;
|
||||
this.minHoldingBars = parameters.minHoldingBars || 3;
|
||||
}
|
||||
|
||||
protected onMarketData(data: MarketData): Signal[] {
|
||||
const signals: Signal[] = [];
|
||||
|
||||
// Only process bar data
|
||||
if (data.type !== 'bar') {
|
||||
return signals;
|
||||
}
|
||||
|
||||
const bar = data.data as BarData;
|
||||
const symbol = data.data.symbol;
|
||||
const price = bar.close;
|
||||
|
||||
// Update price history
|
||||
if (!this.priceHistory.has(symbol)) {
|
||||
this.priceHistory.set(symbol, []);
|
||||
this.barsSinceSignal.set(symbol, 0);
|
||||
}
|
||||
|
||||
const history = defined(this.priceHistory.get(symbol));
|
||||
history.push(price);
|
||||
|
||||
// Keep only necessary history
|
||||
if (history.length > this.slowPeriod) {
|
||||
history.shift();
|
||||
}
|
||||
|
||||
// Update bars since signal
|
||||
const currentBar = this.barsSinceSignal.get(symbol) || 0;
|
||||
this.barsSinceSignal.set(symbol, currentBar + 1);
|
||||
|
||||
// Need enough data
|
||||
if (history.length < this.slowPeriod) {
|
||||
return signals;
|
||||
}
|
||||
|
||||
// Calculate moving averages
|
||||
const fastMA = this.calculateSMA(history, this.fastPeriod);
|
||||
const slowMA = this.calculateSMA(history, this.slowPeriod);
|
||||
|
||||
// Calculate previous MAs
|
||||
const prevHistory = history.slice(0, -1);
|
||||
const prevFastMA = this.calculateSMA(prevHistory, this.fastPeriod);
|
||||
const prevSlowMA = this.calculateSMA(prevHistory, this.slowPeriod);
|
||||
|
||||
// Check for crossovers
|
||||
const currentPosition = this.positions.get(symbol) || 0;
|
||||
const lastCrossover = this.lastCrossover.get(symbol);
|
||||
const barsSinceSignal = this.barsSinceSignal.get(symbol) || 0;
|
||||
|
||||
// Golden cross - bullish signal
|
||||
if (prevFastMA <= prevSlowMA && fastMA > slowMA) {
|
||||
this.lastCrossover.set(symbol, 'golden');
|
||||
|
||||
if (currentPosition < 0) {
|
||||
// Close short position
|
||||
signals.push(this.closeSignal(symbol, 'Golden cross - Close short'));
|
||||
} else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) {
|
||||
// Open long position
|
||||
signals.push(this.buySignal(symbol, 0.8, 'Golden cross - Open long'));
|
||||
this.barsSinceSignal.set(symbol, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Death cross - bearish signal
|
||||
else if (prevFastMA >= prevSlowMA && fastMA < slowMA) {
|
||||
this.lastCrossover.set(symbol, 'death');
|
||||
|
||||
if (currentPosition > 0) {
|
||||
// Close long position
|
||||
signals.push(this.closeSignal(symbol, 'Death cross - Close long'));
|
||||
} else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) {
|
||||
// Open short position
|
||||
signals.push(this.sellSignal(symbol, 0.8, 'Death cross - Open short'));
|
||||
this.barsSinceSignal.set(symbol, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Trend following - enter on pullbacks
|
||||
else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) {
|
||||
if (lastCrossover === 'golden' && fastMA > slowMA) {
|
||||
// Bullish trend continues
|
||||
signals.push(this.buySignal(symbol, 0.8, 'Bullish trend - Open long'));
|
||||
this.barsSinceSignal.set(symbol, 0);
|
||||
} else if (lastCrossover === 'death' && fastMA < slowMA) {
|
||||
// Bearish trend continues
|
||||
signals.push(this.sellSignal(symbol, 0.8, 'Bearish trend - Open short'));
|
||||
this.barsSinceSignal.set(symbol, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return signals;
|
||||
}
|
||||
|
||||
private calculateSMA(prices: number[], period: number): number {
|
||||
if (prices.length < period) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const relevantPrices = prices.slice(-period);
|
||||
const sum = relevantPrices.reduce((a, b) => a + b, 0);
|
||||
return sum / period;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,497 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('SignalManager');
|
||||
|
||||
export interface SignalRule {
|
||||
name: string;
|
||||
condition: (indicators: Record<string, number>) => boolean;
|
||||
weight: number;
|
||||
direction: 'buy' | 'sell' | 'both';
|
||||
}
|
||||
|
||||
export interface SignalFilter {
|
||||
name: string;
|
||||
filter: (signal: TradingSignal, context: Record<string, unknown>) => boolean;
|
||||
}
|
||||
|
||||
export interface TradingSignal {
|
||||
symbol: string;
|
||||
timestamp: number;
|
||||
direction: 'buy' | 'sell' | 'neutral';
|
||||
strength: number; // -1 to 1 (-1 = strong sell, 1 = strong buy)
|
||||
confidence: number; // 0 to 1
|
||||
rules: string[]; // Rules that triggered
|
||||
indicators: Record<string, number>;
|
||||
metadata?: unknown;
|
||||
}
|
||||
|
||||
export interface SignalAggregation {
|
||||
method: 'weighted' | 'majority' | 'unanimous' | 'threshold';
|
||||
threshold?: number; // For threshold method
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages trading signals and rules
|
||||
*/
|
||||
export class SignalManager {
|
||||
private rules: SignalRule[] = [];
|
||||
private filters: SignalFilter[] = [];
|
||||
private signalHistory: TradingSignal[] = [];
|
||||
private maxHistorySize = 1000;
|
||||
|
||||
constructor(private aggregation: SignalAggregation = { method: 'weighted' }) {}
|
||||
|
||||
/**
|
||||
* Add a signal rule
|
||||
*/
|
||||
addRule(rule: SignalRule): void {
|
||||
this.rules.push(rule);
|
||||
logger.info(`Added signal rule: ${rule.name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple rules
|
||||
*/
|
||||
addRules(rules: SignalRule[]): void {
|
||||
rules.forEach(rule => this.addRule(rule));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a signal filter
|
||||
*/
|
||||
addFilter(filter: SignalFilter): void {
|
||||
this.filters.push(filter);
|
||||
logger.info(`Added signal filter: ${filter.name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a rule by name
|
||||
*/
|
||||
removeRule(name: string): void {
|
||||
this.rules = this.rules.filter(r => r.name !== name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate signal based on indicators
|
||||
*/
|
||||
generateSignal(
|
||||
symbol: string,
|
||||
timestamp: number,
|
||||
indicators: Record<string, number>,
|
||||
context: Record<string, unknown> = {}
|
||||
): TradingSignal | null {
|
||||
const triggeredRules: { rule: SignalRule; triggered: boolean }[] = [];
|
||||
|
||||
// Check each rule
|
||||
for (const rule of this.rules) {
|
||||
try {
|
||||
const triggered = rule.condition(indicators);
|
||||
if (triggered) {
|
||||
triggeredRules.push({ rule, triggered: true });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Error evaluating rule ${rule.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (triggeredRules.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Aggregate signals based on method
|
||||
const signal = this.aggregateSignals(symbol, timestamp, indicators, triggeredRules);
|
||||
|
||||
if (!signal) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
for (const filter of this.filters) {
|
||||
try {
|
||||
if (!filter.filter(signal, context)) {
|
||||
logger.debug(`Signal filtered by ${filter.name}`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Error applying filter ${filter.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Store in history
|
||||
this.addToHistory(signal);
|
||||
|
||||
return signal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate multiple rule triggers into a single signal
|
||||
*/
|
||||
private aggregateSignals(
|
||||
symbol: string,
|
||||
timestamp: number,
|
||||
indicators: Record<string, number>,
|
||||
triggeredRules: { rule: SignalRule; triggered: boolean }[]
|
||||
): TradingSignal | null {
|
||||
let buyWeight = 0;
|
||||
let sellWeight = 0;
|
||||
let totalWeight = 0;
|
||||
const rules: string[] = [];
|
||||
|
||||
for (const { rule } of triggeredRules) {
|
||||
rules.push(rule.name);
|
||||
totalWeight += Math.abs(rule.weight);
|
||||
|
||||
if (rule.direction === 'buy' || rule.direction === 'both') {
|
||||
buyWeight += rule.weight;
|
||||
}
|
||||
if (rule.direction === 'sell' || rule.direction === 'both') {
|
||||
sellWeight += rule.weight;
|
||||
}
|
||||
}
|
||||
|
||||
let direction: 'buy' | 'sell' | 'neutral' = 'neutral';
|
||||
let strength = 0;
|
||||
let confidence = 0;
|
||||
|
||||
switch (this.aggregation.method) {
|
||||
case 'weighted': {
|
||||
const netWeight = buyWeight - sellWeight;
|
||||
strength = totalWeight > 0 ? netWeight / totalWeight : 0;
|
||||
confidence = Math.min(triggeredRules.length / this.rules.length, 1);
|
||||
|
||||
if (Math.abs(strength) > 0.1) {
|
||||
direction = strength > 0 ? 'buy' : 'sell';
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'majority': {
|
||||
const buyCount = triggeredRules.filter(
|
||||
t => t.rule.direction === 'buy' || t.rule.direction === 'both'
|
||||
).length;
|
||||
const sellCount = triggeredRules.filter(
|
||||
t => t.rule.direction === 'sell' || t.rule.direction === 'both'
|
||||
).length;
|
||||
|
||||
if (buyCount > sellCount) {
|
||||
direction = 'buy';
|
||||
strength = buyCount / triggeredRules.length;
|
||||
} else if (sellCount > buyCount) {
|
||||
direction = 'sell';
|
||||
strength = -sellCount / triggeredRules.length;
|
||||
}
|
||||
confidence = triggeredRules.length / this.rules.length;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'unanimous': {
|
||||
const allBuy = triggeredRules.every(
|
||||
t => t.rule.direction === 'buy' || t.rule.direction === 'both'
|
||||
);
|
||||
const allSell = triggeredRules.every(
|
||||
t => t.rule.direction === 'sell' || t.rule.direction === 'both'
|
||||
);
|
||||
|
||||
if (allBuy && triggeredRules.length >= 2) {
|
||||
direction = 'buy';
|
||||
strength = 1;
|
||||
confidence = 1;
|
||||
} else if (allSell && triggeredRules.length >= 2) {
|
||||
direction = 'sell';
|
||||
strength = -1;
|
||||
confidence = 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'threshold': {
|
||||
const threshold = this.aggregation.threshold || 0.7;
|
||||
const avgWeight = totalWeight > 0 ? (buyWeight - sellWeight) / totalWeight : 0;
|
||||
|
||||
if (avgWeight >= threshold) {
|
||||
direction = 'buy';
|
||||
strength = avgWeight;
|
||||
confidence = triggeredRules.length / this.rules.length;
|
||||
} else if (avgWeight <= -threshold) {
|
||||
direction = 'sell';
|
||||
strength = avgWeight;
|
||||
confidence = triggeredRules.length / this.rules.length;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (direction === 'neutral') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
symbol,
|
||||
timestamp,
|
||||
direction,
|
||||
strength,
|
||||
confidence,
|
||||
rules,
|
||||
indicators,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent signals for a symbol
|
||||
*/
|
||||
getRecentSignals(symbol: string, count = 10): TradingSignal[] {
|
||||
return this.signalHistory.filter(s => s.symbol === symbol).slice(-count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signal statistics
|
||||
*/
|
||||
getSignalStats(symbol?: string) {
|
||||
const signals = symbol
|
||||
? this.signalHistory.filter(s => s.symbol === symbol)
|
||||
: this.signalHistory;
|
||||
|
||||
const buySignals = signals.filter(s => s.direction === 'buy');
|
||||
const sellSignals = signals.filter(s => s.direction === 'sell');
|
||||
|
||||
const avgBuyStrength =
|
||||
buySignals.length > 0
|
||||
? buySignals.reduce((sum, s) => sum + s.strength, 0) / buySignals.length
|
||||
: 0;
|
||||
|
||||
const avgSellStrength =
|
||||
sellSignals.length > 0
|
||||
? sellSignals.reduce((sum, s) => sum + Math.abs(s.strength), 0) / sellSignals.length
|
||||
: 0;
|
||||
|
||||
const avgConfidence =
|
||||
signals.length > 0 ? signals.reduce((sum, s) => sum + s.confidence, 0) / signals.length : 0;
|
||||
|
||||
return {
|
||||
totalSignals: signals.length,
|
||||
buySignals: buySignals.length,
|
||||
sellSignals: sellSignals.length,
|
||||
avgBuyStrength,
|
||||
avgSellStrength,
|
||||
avgConfidence,
|
||||
ruleHitRate: this.calculateRuleHitRate(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear signal history
|
||||
*/
|
||||
clearHistory(): void {
|
||||
this.signalHistory = [];
|
||||
}
|
||||
|
||||
private addToHistory(signal: TradingSignal): void {
|
||||
this.signalHistory.push(signal);
|
||||
|
||||
if (this.signalHistory.length > this.maxHistorySize) {
|
||||
this.signalHistory.shift();
|
||||
}
|
||||
}
|
||||
|
||||
private calculateRuleHitRate(): Record<string, number> {
|
||||
const ruleHits: Record<string, number> = {};
|
||||
|
||||
for (const signal of this.signalHistory) {
|
||||
for (const rule of signal.rules) {
|
||||
ruleHits[rule] = (ruleHits[rule] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const hitRate: Record<string, number> = {};
|
||||
for (const [rule, hits] of Object.entries(ruleHits)) {
|
||||
hitRate[rule] = this.signalHistory.length > 0 ? hits / this.signalHistory.length : 0;
|
||||
}
|
||||
|
||||
return hitRate;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common signal rules
|
||||
*/
|
||||
export const CommonRules = {
|
||||
// Moving Average Rules
|
||||
goldenCross: (fastMA: string, slowMA: string): SignalRule => ({
|
||||
name: `Golden Cross (${fastMA}/${slowMA})`,
|
||||
condition: indicators => {
|
||||
const fast = indicators[fastMA];
|
||||
const slow = indicators[slowMA];
|
||||
const prevFast = indicators[`${fastMA}_prev`];
|
||||
const prevSlow = indicators[`${slowMA}_prev`];
|
||||
if (
|
||||
fast === undefined ||
|
||||
slow === undefined ||
|
||||
prevFast === undefined ||
|
||||
prevSlow === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return prevFast <= prevSlow && fast > slow;
|
||||
},
|
||||
weight: 1,
|
||||
direction: 'buy',
|
||||
}),
|
||||
|
||||
deathCross: (fastMA: string, slowMA: string): SignalRule => ({
|
||||
name: `Death Cross (${fastMA}/${slowMA})`,
|
||||
condition: indicators => {
|
||||
const fast = indicators[fastMA];
|
||||
const slow = indicators[slowMA];
|
||||
const prevFast = indicators[`${fastMA}_prev`];
|
||||
const prevSlow = indicators[`${slowMA}_prev`];
|
||||
if (
|
||||
fast === undefined ||
|
||||
slow === undefined ||
|
||||
prevFast === undefined ||
|
||||
prevSlow === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return prevFast >= prevSlow && fast < slow;
|
||||
},
|
||||
weight: 1,
|
||||
direction: 'sell',
|
||||
}),
|
||||
|
||||
// RSI Rules
|
||||
rsiOversold: (threshold = 30): SignalRule => ({
|
||||
name: `RSI Oversold (<${threshold})`,
|
||||
condition: indicators => Number(indicators.rsi) < threshold,
|
||||
weight: 0.5,
|
||||
direction: 'buy',
|
||||
}),
|
||||
|
||||
rsiOverbought: (threshold = 70): SignalRule => ({
|
||||
name: `RSI Overbought (>${threshold})`,
|
||||
condition: indicators => Number(indicators.rsi) > threshold,
|
||||
weight: 0.5,
|
||||
direction: 'sell',
|
||||
}),
|
||||
|
||||
// MACD Rules
|
||||
macdBullishCross: (): SignalRule => ({
|
||||
name: 'MACD Bullish Cross',
|
||||
condition: indicators => {
|
||||
return (
|
||||
Number(indicators.macd_prev) < Number(indicators.macd_signal_prev) &&
|
||||
Number(indicators.macd) > Number(indicators.macd_signal)
|
||||
);
|
||||
},
|
||||
weight: 0.8,
|
||||
direction: 'buy',
|
||||
}),
|
||||
|
||||
macdBearishCross: (): SignalRule => ({
|
||||
name: 'MACD Bearish Cross',
|
||||
condition: indicators => {
|
||||
return (
|
||||
Number(indicators.macd_prev) > Number(indicators.macd_signal_prev) &&
|
||||
Number(indicators.macd) < Number(indicators.macd_signal)
|
||||
);
|
||||
},
|
||||
weight: 0.8,
|
||||
direction: 'sell',
|
||||
}),
|
||||
|
||||
// Bollinger Band Rules
|
||||
bollingerSqueeze: (threshold = 0.02): SignalRule => ({
|
||||
name: `Bollinger Squeeze (<${threshold})`,
|
||||
condition: indicators => {
|
||||
const bandwidth =
|
||||
(Number(indicators.bb_upper) - Number(indicators.bb_lower)) / Number(indicators.bb_middle);
|
||||
return bandwidth < threshold;
|
||||
},
|
||||
weight: 0.3,
|
||||
direction: 'both',
|
||||
}),
|
||||
|
||||
priceAtLowerBand: (): SignalRule => ({
|
||||
name: 'Price at Lower Bollinger Band',
|
||||
condition: indicators => {
|
||||
const bbPercent =
|
||||
(Number(indicators.price) - Number(indicators.bb_lower)) /
|
||||
(Number(indicators.bb_upper) - Number(indicators.bb_lower));
|
||||
return bbPercent < 0.05;
|
||||
},
|
||||
weight: 0.6,
|
||||
direction: 'buy',
|
||||
}),
|
||||
|
||||
priceAtUpperBand: (): SignalRule => ({
|
||||
name: 'Price at Upper Bollinger Band',
|
||||
condition: indicators => {
|
||||
const bbPercent =
|
||||
(Number(indicators.price) - Number(indicators.bb_lower)) /
|
||||
(Number(indicators.bb_upper) - Number(indicators.bb_lower));
|
||||
return bbPercent > 0.95;
|
||||
},
|
||||
weight: 0.6,
|
||||
direction: 'sell',
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Common signal filters
|
||||
*/
|
||||
export const CommonFilters = {
|
||||
// Minimum signal strength
|
||||
minStrength: (threshold = 0.5): SignalFilter => ({
|
||||
name: `Min Strength (${threshold})`,
|
||||
filter: signal => Math.abs(signal.strength) >= threshold,
|
||||
}),
|
||||
|
||||
// Minimum confidence
|
||||
minConfidence: (threshold = 0.3): SignalFilter => ({
|
||||
name: `Min Confidence (${threshold})`,
|
||||
filter: signal => signal.confidence >= threshold,
|
||||
}),
|
||||
|
||||
// Time of day filter
|
||||
tradingHours: (startHour = 9.5, endHour = 16): SignalFilter => ({
|
||||
name: `Trading Hours (${startHour}-${endHour})`,
|
||||
filter: signal => {
|
||||
const date = new Date(signal.timestamp);
|
||||
const hour = date.getUTCHours() + date.getUTCMinutes() / 60;
|
||||
return hour >= startHour && hour < endHour;
|
||||
},
|
||||
}),
|
||||
|
||||
// Trend alignment
|
||||
trendAlignment: (trendIndicator = 'sma200'): SignalFilter => ({
|
||||
name: `Trend Alignment (${trendIndicator})`,
|
||||
filter: signal => {
|
||||
const trend = signal.indicators[trendIndicator];
|
||||
const price = signal.indicators.price;
|
||||
if (!trend || !price) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Buy signals only above trend, sell signals only below
|
||||
if (signal.direction === 'buy') {
|
||||
return price > trend;
|
||||
} else if (signal.direction === 'sell') {
|
||||
return price < trend;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
|
||||
// Volume confirmation
|
||||
volumeConfirmation: (multiplier = 1.5): SignalFilter => ({
|
||||
name: `Volume Confirmation (${multiplier}x)`,
|
||||
filter: signal => {
|
||||
const volume = signal.indicators.volume;
|
||||
const avgVolume = signal.indicators.avg_volume;
|
||||
if (!volume || !avgVolume) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return volume >= avgVolume * multiplier;
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
|
@ -4,14 +4,8 @@ import {
|
|||
} 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 smaConfig(config: StrategyConfig) {
|
||||
return { ...config, parameters: typescriptSmaParameters.parse(config.parameters) };
|
||||
}
|
||||
export function meanReversionConfig(config: StrategyConfig) {
|
||||
return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue