310 lines
11 KiB
TypeScript
310 lines
11 KiB
TypeScript
import { defined } from '@stock-bot/invariants';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import type { SmaParameters } from '../../contracts/strategies';
|
|
import type { ModeManager } from '../../core/ModeManager';
|
|
import { movingAverageCrossover } from '../../indicators/window-statistics';
|
|
import type { ExecutionService, StrategyFill } from '../../services/ExecutionService';
|
|
import type { StrategyConfig } from '../../types';
|
|
import { type MarketData } from '../../types';
|
|
import { BaseStrategy, type Signal } from '../BaseStrategy';
|
|
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
|
|
import { smaConfig } from '../strategy-config';
|
|
|
|
const logger = getLogger('SimpleMovingAverageCrossover');
|
|
|
|
export class SimpleMovingAverageCrossover extends BaseStrategy {
|
|
private priceHistory = new Map<string, number[]>();
|
|
private lastSignalBar = new Map<string, number>();
|
|
private barCount = new Map<string, number>();
|
|
private totalSignals = 0;
|
|
private lastCrossoverType = new Map<string, 'golden' | 'death' | null>();
|
|
override getCheckpointVersion() {
|
|
return 'sma-crossover-fixed/v2';
|
|
}
|
|
protected override captureIndicators() {
|
|
return {
|
|
priceHistory: [...this.priceHistory],
|
|
lastSignalBar: [...this.lastSignalBar],
|
|
barCount: [...this.barCount],
|
|
totalSignals: this.totalSignals,
|
|
lastCrossoverType: [...this.lastCrossoverType],
|
|
};
|
|
}
|
|
protected override restoreIndicators(input: unknown) {
|
|
const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input);
|
|
this.priceHistory = new Map(state.priceHistory);
|
|
this.lastSignalBar = new Map(state.lastSignalBar);
|
|
this.barCount = new Map(state.barCount);
|
|
this.totalSignals = state.totalSignals;
|
|
this.lastCrossoverType = new Map(state.lastCrossoverType);
|
|
}
|
|
|
|
private settings: SmaParameters;
|
|
private readonly DEBUG_INTERVAL = 10;
|
|
|
|
constructor(
|
|
config: StrategyConfig,
|
|
modeManager: ModeManager,
|
|
executionService: ExecutionService
|
|
) {
|
|
const validated = smaConfig(config);
|
|
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;
|
|
|
|
// Initialize or get price history
|
|
if (!this.priceHistory.has(symbol)) {
|
|
this.priceHistory.set(symbol, []);
|
|
this.barCount.set(symbol, 0);
|
|
logger.info(`📊 Starting to track ${symbol} @ ${price.toFixed(2)}`);
|
|
}
|
|
|
|
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 + 1) {
|
|
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) {
|
|
return null;
|
|
}
|
|
|
|
const currentPrice = data.data.close;
|
|
const timestamp = data.data.timestamp;
|
|
const currentBar = this.barCount.get(symbol) || 0;
|
|
|
|
const crossover = movingAverageCrossover(
|
|
history,
|
|
this.settings.fastPeriod,
|
|
this.settings.slowPeriod
|
|
);
|
|
if (!crossover) {
|
|
return null;
|
|
}
|
|
const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover;
|
|
|
|
// Get current position
|
|
const currentPosition = this.getPosition(symbol);
|
|
|
|
// Track last signal bar
|
|
const lastSignalBar = this.lastSignalBar.get(symbol) || 0;
|
|
const barsSinceLastSignal = currentBar - lastSignalBar;
|
|
|
|
// Calculate MA difference for debugging
|
|
const maDiff = fastMA - slowMA;
|
|
const maDiffPct = (maDiff / slowMA) * 100;
|
|
|
|
// Debug logging every N bars
|
|
if (currentBar % this.DEBUG_INTERVAL === 0 || goldenCross || deathCross) {
|
|
logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`);
|
|
logger.info(` Price: $${currentPrice.toFixed(2)}`);
|
|
logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`);
|
|
logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`);
|
|
logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`);
|
|
logger.info(` Position: ${currentPosition} shares`);
|
|
logger.info(` Bars since last signal: ${barsSinceLastSignal}`);
|
|
|
|
if (goldenCross) {
|
|
logger.info(` 🟢 GOLDEN CROSS DETECTED!`);
|
|
}
|
|
if (deathCross) {
|
|
logger.info(` 🔴 DEATH CROSS DETECTED!`);
|
|
}
|
|
}
|
|
|
|
// Store crossover type for position management
|
|
if (goldenCross) {
|
|
this.lastCrossoverType.set(symbol, 'golden');
|
|
} else if (deathCross) {
|
|
this.lastCrossoverType.set(symbol, 'death');
|
|
}
|
|
|
|
// Check if we should enter a position based on the current trend
|
|
const lastCrossover = this.lastCrossoverType.get(symbol);
|
|
|
|
if (currentPosition === 0 && barsSinceLastSignal >= this.settings.minHoldingBars) {
|
|
// No position - check if we should enter based on last crossover
|
|
if (lastCrossover === 'golden' && fastMA > slowMA) {
|
|
// Trend is still bullish after golden cross - open long
|
|
logger.info(`🟢 Opening LONG position - Bullish trend after golden cross`);
|
|
logger.info(` Current position: 0 shares`);
|
|
|
|
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
|
logger.info(` Opening long position: ${positionSize} shares`);
|
|
|
|
const signal: Signal = {
|
|
type: 'buy',
|
|
symbol,
|
|
strength: 0.8,
|
|
reason: 'Bullish trend - Opening long position',
|
|
metadata: {
|
|
fastMA,
|
|
slowMA,
|
|
prevFastMA,
|
|
prevSlowMA,
|
|
crossoverType: 'trend_long',
|
|
price: currentPrice,
|
|
quantity: positionSize,
|
|
},
|
|
};
|
|
|
|
this.lastSignalBar.set(symbol, currentBar);
|
|
this.totalSignals++;
|
|
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
|
return signal;
|
|
} else if (lastCrossover === 'death' && fastMA < slowMA) {
|
|
// Trend is still bearish after death cross - open short
|
|
logger.info(`🔴 Opening SHORT position - Bearish trend after death cross`);
|
|
logger.info(` Current position: 0 shares`);
|
|
|
|
const positionSize = await this.calculateCrossoverPositionSize(currentPrice);
|
|
logger.info(` Opening short position: ${positionSize} shares`);
|
|
|
|
const signal: Signal = {
|
|
type: 'sell',
|
|
symbol,
|
|
strength: 0.8,
|
|
reason: 'Bearish trend - Opening short position',
|
|
metadata: {
|
|
fastMA,
|
|
slowMA,
|
|
prevFastMA,
|
|
prevSlowMA,
|
|
crossoverType: 'trend_short',
|
|
price: currentPrice,
|
|
quantity: positionSize,
|
|
},
|
|
};
|
|
|
|
this.lastSignalBar.set(symbol, currentBar);
|
|
this.totalSignals++;
|
|
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
|
return signal;
|
|
}
|
|
}
|
|
|
|
// Handle crossovers for position changes
|
|
if (goldenCross) {
|
|
logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`);
|
|
logger.info(` Current position: ${currentPosition} shares`);
|
|
|
|
if (currentPosition < 0) {
|
|
// Close short position
|
|
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),
|
|
},
|
|
};
|
|
|
|
this.lastSignalBar.set(symbol, currentBar);
|
|
this.totalSignals++;
|
|
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
|
return signal;
|
|
}
|
|
} else if (deathCross) {
|
|
logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`);
|
|
logger.info(` Current position: ${currentPosition} shares`);
|
|
|
|
if (currentPosition > 0) {
|
|
// Close long position
|
|
logger.info(` Closing long position of ${currentPosition} shares`);
|
|
const signal: Signal = {
|
|
type: 'sell',
|
|
symbol,
|
|
strength: 0.8,
|
|
reason: 'Death cross - Closing long position',
|
|
metadata: {
|
|
fastMA,
|
|
slowMA,
|
|
prevFastMA,
|
|
prevSlowMA,
|
|
crossoverType: 'death',
|
|
price: currentPrice,
|
|
quantity: currentPosition,
|
|
},
|
|
};
|
|
|
|
this.lastSignalBar.set(symbol, currentBar);
|
|
this.totalSignals++;
|
|
logger.info(`👉 Total signals generated: ${this.totalSignals}`);
|
|
return signal;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
protected override validateConfig(config: StrategyConfig): StrategyConfig {
|
|
const validated = smaConfig(config);
|
|
this.settings = validated.parameters;
|
|
return validated;
|
|
}
|
|
|
|
private async calculateCrossoverPositionSize(price: number): Promise<number> {
|
|
if (this.settings.quantity !== undefined) {
|
|
return this.settings.quantity;
|
|
}
|
|
const accountBalance = (await this.executionService.getAccount()).equity;
|
|
const positionValue = accountBalance * this.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}`);
|
|
|
|
// Update our internal position tracking to match
|
|
// This is redundant with BaseStrategy but helps with debugging
|
|
const currentPosition = this.getPosition(symbol);
|
|
logger.info(` Position after fill: ${currentPosition} shares`);
|
|
}
|
|
}
|