stock-bot/apps/stock/orchestrator/src/strategies/BaseStrategy.ts

384 lines
12 KiB
TypeScript

import { EventEmitter } from 'events';
import { createHash } from 'node:crypto';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { ModeManager } from '../core/ModeManager';
import { identity } from '../execution/model';
import type {
ExecutionService,
StrategyFill,
StrategyOrderUpdate,
} from '../services/ExecutionService';
import {
OrderRequestSchema,
type MarketData,
type OrderRequest,
type StrategyConfig,
} from '../types';
const logger = getLogger('BaseStrategy');
const finite = z.number().finite();
const checkpointSchema = z.object({
version: z.literal(1),
positions: z.array(z.tuple([z.string(), finite])),
pendingOrders: z.array(z.tuple([z.string(), OrderRequestSchema])),
seenFills: z.array(z.string()).max(2048),
performance: z.object({
trades: finite.nonnegative(),
wins: finite.nonnegative(),
losses: finite.nonnegative(),
totalPnl: finite,
maxDrawdown: finite,
currentDrawdown: finite,
peakEquity: finite,
}),
indicators: z.unknown(),
});
export interface Signal {
type: 'buy' | 'sell' | 'close';
symbol: string;
strength: number; // -1 to 1
reason?: string;
metadata?: Record<string, unknown>;
}
export abstract class BaseStrategy extends EventEmitter {
protected config: StrategyConfig;
protected isActive = false;
private eventIdentity?: string;
private readonly seenFills = new Set<string>();
setMarketEvent(eventId: string) {
this.eventIdentity = eventId;
}
protected positions = new Map<string, number>();
protected pendingOrders = new Map<string, OrderRequest>();
protected performance = {
trades: 0,
wins: 0,
losses: 0,
totalPnl: 0,
maxDrawdown: 0,
currentDrawdown: 0,
peakEquity: 0,
};
constructor(
config: StrategyConfig,
protected modeManager: ModeManager,
protected executionService: ExecutionService
) {
super();
this.config = structuredClone(config);
}
async initialize(): Promise<void> {
logger.info(`Initializing strategy: ${this.config.name}`);
const snapshot = await this.executionService.getStrategySnapshot(this.config.id);
this.positions = new Map(
Object.entries(snapshot.positions).filter(([, quantity]) => quantity !== 0)
);
this.pendingOrders = new Map(
snapshot.orders.map(order => [order.report.orderId, order.request])
);
// Subscribe to symbols
for (const symbol of this.config.symbols) {
// Note: In real implementation, would subscribe through market data service
logger.debug(`Strategy ${this.config.id} subscribed to ${symbol}`);
}
}
async start(): Promise<void> {
this.isActive = true;
logger.info(`Started strategy: ${this.config.name}`);
await this.onStart();
}
async stop(): Promise<void> {
this.isActive = false;
await this.executionService.pauseStrategy(this.config.id);
// Cancel pending orders
for (const [orderId, _order] of this.pendingOrders) {
await this.executionService.cancelOrder(orderId);
}
this.pendingOrders.clear();
logger.info(`Stopped strategy: ${this.config.name}`);
await this.onStop();
}
async shutdown(): Promise<void> {
await this.suspend();
this.removeAllListeners();
logger.info(`Shutdown strategy: ${this.config.name}`);
}
/** Process shutdown is not an instruction to cancel durable orders or erase indicators. */
async suspend(): Promise<void> {
this.isActive = false;
}
getCheckpointVersion(): string | undefined {
return undefined;
}
protected captureIndicators(): unknown {
return null;
}
protected restoreIndicators(state: unknown): void {
if (state !== null) {
throw new Error('Unexpected checkpoint state for a stateless strategy');
}
}
captureCheckpoint(): unknown {
return {
version: 1,
positions: [...this.positions],
pendingOrders: [...this.pendingOrders],
seenFills: [...this.seenFills].slice(-2048),
performance: { ...this.performance },
indicators: this.captureIndicators(),
};
}
restoreCheckpoint(input: unknown): void {
const state = checkpointSchema.parse(input);
this.restoreIndicators(state.indicators);
this.positions = new Map(state.positions);
this.pendingOrders = new Map(state.pendingOrders);
this.seenFills.clear();
for (const id of state.seenFills) {
this.seenFills.add(id);
}
this.performance = state.performance;
}
// Market data handling
async onMarketData(data: MarketData): Promise<void> {
if (!this.isActive) {
logger.info(
`[BaseStrategy] Strategy ${this.config.id} received market data but is not active`
);
return;
}
this.eventIdentity = identity(data);
// Update any indicators or state
this.updateIndicators(data);
// Generate signals
const signal = await this.generateSignal(data);
if (signal) {
this.executionService.afterStrategyCommit(() => {
this.emit('signal', signal);
});
// Convert signal to order if strong enough
const order = await this.signalToOrder(signal);
if (order) {
const clientOrderId = createHash('sha256')
.update(JSON.stringify([this.config.id, this.eventIdentity, order]))
.digest('hex');
this.executionService.captureStrategyOrder({ ...order, clientOrderId }, this.config.id);
}
}
}
async onMarketDataBatch(batch: MarketData[]): Promise<void> {
// Default implementation processes individually
// Strategies can override for more efficient batch processing
for (const data of batch) {
await this.onMarketData(data);
}
}
getConfig(): Readonly<StrategyConfig> {
return structuredClone(this.config);
}
hasOrder(orderId: string): boolean {
return this.pendingOrders.has(orderId);
}
// Order and fill handling
async onOrderUpdate(update: StrategyOrderUpdate): Promise<void> {
logger.debug(`Strategy ${this.config.id} order update:`, update);
if (['filled', 'rejected', 'cancelled'].includes(update.status)) {
this.pendingOrders.delete(update.orderId);
} else {
this.pendingOrders.set(update.orderId, {
symbol: update.symbol,
side: update.side,
quantity: update.quantity,
orderType: 'market',
timeInForce: 'DAY',
});
}
}
async onOrderError(order: OrderRequest, error: unknown): Promise<void> {
logger.error(`Strategy ${this.config.id} order error:`, error);
// Strategies can override to handle errors
}
async onFill(fill: StrategyFill): Promise<void> {
if (this.seenFills.has(fill.id)) {
return;
}
this.seenFills.add(fill.id);
if (this.seenFills.size > 2048) {
this.seenFills.delete(defined(this.seenFills.values().next().value));
}
const quantity =
(this.positions.get(fill.symbol) ?? 0) +
(fill.side === 'buy' ? fill.quantity : -fill.quantity);
if (Math.abs(quantity) < 1e-8) {
this.positions.delete(fill.symbol);
} else {
this.positions.set(fill.symbol, quantity);
}
// Update performance metrics
this.performance.trades++;
if ((fill.pnl ?? 0) > 0) {
this.performance.wins++;
} else if ((fill.pnl ?? 0) < 0) {
this.performance.losses++;
}
this.performance.totalPnl += fill.pnl ?? 0;
// Update drawdown
const currentEquity = this.getEquity();
if (currentEquity > this.performance.peakEquity) {
this.performance.peakEquity = currentEquity;
this.performance.currentDrawdown = 0;
} else {
this.performance.currentDrawdown =
this.performance.peakEquity > 0
? (this.performance.peakEquity - currentEquity) / this.performance.peakEquity
: 0;
this.performance.maxDrawdown = Math.max(
this.performance.maxDrawdown,
this.performance.currentDrawdown
);
}
}
// Configuration
async updateConfig(updates: Partial<StrategyConfig>): Promise<void> {
if (this.isActive) {
throw new Error(
'Active strategy configuration is immutable; use an explicit new strategy ID'
);
}
this.config = this.validateConfig(structuredClone({ ...this.config, ...updates }));
logger.info(`Updated config for strategy ${this.config.id}`);
// Strategies can override to handle specific config changes
this.onConfigUpdate(updates);
}
// Helper methods
isInterestedInSymbol(symbol: string): boolean {
return this.config.symbols.includes(symbol);
}
hasPosition(symbol: string): boolean {
return this.positions.has(symbol) && Math.abs(defined(this.positions.get(symbol))) > 0.0001;
}
getPosition(symbol: string): number {
return this.positions.get(symbol) || 0;
}
getPerformance() {
const winRate =
this.performance.trades > 0 ? (this.performance.wins / this.performance.trades) * 100 : 0;
return {
...this.performance,
winRate,
averagePnl:
this.performance.trades > 0 ? this.performance.totalPnl / this.performance.trades : 0,
};
}
protected getEquity(): number {
// Get initial capital from config parameters or default
const initialCapital = Number(this.config.parameters?.initialCapital ?? 100000);
return initialCapital + this.performance.totalPnl;
}
protected async signalToOrder(signal: Signal): Promise<OrderRequest | null> {
// Only act on strong signals
if (Math.abs(signal.strength) < 0.7) {
return null;
}
// Check if we already have a position
const currentPosition = this.getPosition(signal.symbol);
// Use quantity from signal metadata if provided
const quantity =
typeof signal.metadata?.quantity === 'number'
? signal.metadata.quantity
: this.calculatePositionSize(signal);
logger.info(
`[BaseStrategy] Converting signal to order: ${signal.type} ${quantity} ${signal.symbol}, current position: ${currentPosition}`
);
// Simple logic - can be overridden by specific strategies
if (signal.type === 'buy') {
// Allow buying to open long or close short
return {
symbol: signal.symbol,
side: 'buy',
quantity: quantity,
orderType: 'market',
timeInForce: 'DAY',
};
} else if (signal.type === 'sell') {
// Allow selling to close long or open short
return {
symbol: signal.symbol,
side: 'sell',
quantity: quantity,
orderType: 'market',
timeInForce: 'DAY',
};
} else if (signal.type === 'close' && currentPosition !== 0) {
return {
symbol: signal.symbol,
side: currentPosition > 0 ? 'sell' : 'buy',
quantity: Math.abs(currentPosition),
orderType: 'market',
timeInForce: 'DAY',
};
}
return null;
}
protected calculatePositionSize(signal: Signal): number {
// Simple fixed size - strategies should override with proper position sizing
const baseSize = 100; // 100 shares
const allocation = this.config.allocation || 1.0;
return Math.floor(baseSize * allocation * Math.abs(signal.strength));
}
// Abstract methods that strategies must implement
protected abstract updateIndicators(data: MarketData): void;
protected abstract generateSignal(data: MarketData): Promise<Signal | null>;
// Optional hooks for strategies to override
protected onStart(): void | Promise<void> {}
protected onStop(): void | Promise<void> {}
protected onConfigUpdate(_updates: Partial<StrategyConfig>): void {}
/** Validate before assignment, so a rejected inactive edit cannot poison the current definition. */
protected validateConfig(config: StrategyConfig): StrategyConfig {
return config;
}
}