added initial py analytics / rust core / ts orchestrator services
This commit is contained in:
parent
680b5fd2ae
commit
c862ed496b
62 changed files with 13459 additions and 0 deletions
209
apps/stock/orchestrator/src/services/AnalyticsService.ts
Normal file
209
apps/stock/orchestrator/src/services/AnalyticsService.ts
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import axios from 'axios';
|
||||
import { PerformanceMetrics, RiskMetrics } from '../types';
|
||||
|
||||
interface OptimizationParams {
|
||||
returns: number[][];
|
||||
constraints?: {
|
||||
minWeight?: number;
|
||||
maxWeight?: number;
|
||||
targetReturn?: number;
|
||||
maxRisk?: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PortfolioWeights {
|
||||
symbols: string[];
|
||||
weights: number[];
|
||||
expectedReturn: number;
|
||||
expectedRisk: number;
|
||||
sharpeRatio: number;
|
||||
}
|
||||
|
||||
export class AnalyticsService {
|
||||
private analyticsUrl: string;
|
||||
private cache = new Map<string, { data: any; timestamp: number }>();
|
||||
private readonly CACHE_TTL_MS = 60000; // 1 minute cache
|
||||
|
||||
constructor() {
|
||||
this.analyticsUrl = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003';
|
||||
}
|
||||
|
||||
async getPerformanceMetrics(
|
||||
portfolioId: string,
|
||||
startDate: Date,
|
||||
endDate: Date
|
||||
): Promise<PerformanceMetrics> {
|
||||
const cacheKey = `perf_${portfolioId}_${startDate.toISOString()}_${endDate.toISOString()}`;
|
||||
const cached = this.getFromCache(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${this.analyticsUrl}/analytics/performance/${portfolioId}`, {
|
||||
params: {
|
||||
start_date: startDate.toISOString(),
|
||||
end_date: endDate.toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
const metrics = response.data as PerformanceMetrics;
|
||||
this.setCache(cacheKey, metrics);
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
logger.error('Error fetching performance metrics:', error);
|
||||
// Return default metrics if analytics service is unavailable
|
||||
return this.getDefaultPerformanceMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
async optimizePortfolio(params: OptimizationParams): Promise<PortfolioWeights> {
|
||||
try {
|
||||
const response = await axios.post(`${this.analyticsUrl}/optimize/portfolio`, params);
|
||||
return response.data as PortfolioWeights;
|
||||
} catch (error) {
|
||||
logger.error('Error optimizing portfolio:', error);
|
||||
// Return equal weights as fallback
|
||||
return this.getEqualWeights(params.returns[0].length);
|
||||
}
|
||||
}
|
||||
|
||||
async getRiskMetrics(portfolioId: string): Promise<RiskMetrics> {
|
||||
const cacheKey = `risk_${portfolioId}`;
|
||||
const cached = this.getFromCache(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${this.analyticsUrl}/analytics/risk/${portfolioId}`);
|
||||
const metrics = response.data as RiskMetrics;
|
||||
this.setCache(cacheKey, metrics);
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
logger.error('Error fetching risk metrics:', error);
|
||||
return this.getDefaultRiskMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
async detectMarketRegime(): Promise<string> {
|
||||
const cacheKey = 'market_regime';
|
||||
const cached = this.getFromCache(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${this.analyticsUrl}/analytics/regime`);
|
||||
const regime = response.data.regime as string;
|
||||
this.setCache(cacheKey, regime, 300000); // Cache for 5 minutes
|
||||
return regime;
|
||||
} catch (error) {
|
||||
logger.error('Error detecting market regime:', error);
|
||||
return 'normal'; // Default regime
|
||||
}
|
||||
}
|
||||
|
||||
async calculateCorrelationMatrix(symbols: string[]): Promise<number[][]> {
|
||||
try {
|
||||
const response = await axios.post(`${this.analyticsUrl}/analytics/correlation`, { symbols });
|
||||
return response.data.matrix as number[][];
|
||||
} catch (error) {
|
||||
logger.error('Error calculating correlation matrix:', error);
|
||||
// Return identity matrix as fallback
|
||||
return this.getIdentityMatrix(symbols.length);
|
||||
}
|
||||
}
|
||||
|
||||
async runBacktestAnalysis(backtestId: string): Promise<any> {
|
||||
try {
|
||||
const response = await axios.get(`${this.analyticsUrl}/analytics/backtest/${backtestId}`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
logger.error('Error running backtest analysis:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async predictWithModel(modelId: string, features: Record<string, number>): Promise<any> {
|
||||
try {
|
||||
const response = await axios.post(`${this.analyticsUrl}/models/predict`, {
|
||||
model_id: modelId,
|
||||
features
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
logger.error('Error getting model prediction:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Cache management
|
||||
private getFromCache(key: string): any | null {
|
||||
const cached = this.cache.get(key);
|
||||
if (!cached) return null;
|
||||
|
||||
const now = Date.now();
|
||||
if (now - cached.timestamp > this.CACHE_TTL_MS) {
|
||||
this.cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cached.data;
|
||||
}
|
||||
|
||||
private setCache(key: string, data: any, ttl?: number): void {
|
||||
this.cache.set(key, {
|
||||
data,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
// Auto-cleanup after TTL
|
||||
setTimeout(() => {
|
||||
this.cache.delete(key);
|
||||
}, ttl || this.CACHE_TTL_MS);
|
||||
}
|
||||
|
||||
// Fallback methods when analytics service is unavailable
|
||||
private getDefaultPerformanceMetrics(): PerformanceMetrics {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: 0,
|
||||
sortinoRatio: 0,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
profitFactor: 0,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
totalTrades: 0
|
||||
};
|
||||
}
|
||||
|
||||
private getDefaultRiskMetrics(): RiskMetrics {
|
||||
return {
|
||||
currentExposure: 0,
|
||||
dailyPnl: 0,
|
||||
positionCount: 0,
|
||||
grossExposure: 0,
|
||||
var95: 0,
|
||||
cvar95: 0
|
||||
};
|
||||
}
|
||||
|
||||
private getEqualWeights(n: number): PortfolioWeights {
|
||||
const weight = 1 / n;
|
||||
return {
|
||||
symbols: Array(n).fill('').map((_, i) => `Asset${i + 1}`),
|
||||
weights: Array(n).fill(weight),
|
||||
expectedReturn: 0,
|
||||
expectedRisk: 0,
|
||||
sharpeRatio: 0
|
||||
};
|
||||
}
|
||||
|
||||
private getIdentityMatrix(n: number): number[][] {
|
||||
const matrix: number[][] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
matrix[i] = [];
|
||||
for (let j = 0; j < n; j++) {
|
||||
matrix[i][j] = i === j ? 1 : 0;
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
}
|
||||
312
apps/stock/orchestrator/src/services/ExecutionService.ts
Normal file
312
apps/stock/orchestrator/src/services/ExecutionService.ts
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { EventEmitter } from 'events';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { ModeConfig, OrderRequest, OrderRequestSchema } from '../types';
|
||||
import { TradingEngine } from '../../core';
|
||||
import axios from 'axios';
|
||||
|
||||
interface ExecutionReport {
|
||||
orderId: string;
|
||||
clientOrderId: string;
|
||||
symbol: string;
|
||||
side: 'buy' | 'sell';
|
||||
quantity: number;
|
||||
status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected';
|
||||
fills: Fill[];
|
||||
rejectionReason?: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface Fill {
|
||||
price: number;
|
||||
quantity: number;
|
||||
commission: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export class ExecutionService extends EventEmitter {
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
private tradingEngine: TradingEngine | null = null;
|
||||
private brokerClient: any = null; // Would be specific broker API client
|
||||
private pendingOrders = new Map<string, OrderRequest>();
|
||||
|
||||
constructor(private modeManager: any) {
|
||||
super();
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig, tradingEngine: TradingEngine): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
this.tradingEngine = tradingEngine;
|
||||
|
||||
if (config.mode === 'live') {
|
||||
// Initialize broker connection
|
||||
await this.initializeBroker(config.broker, config.accountId);
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeBroker(broker: string, accountId: string): Promise<void> {
|
||||
// In real implementation, would initialize specific broker API
|
||||
// For example: Alpaca, Interactive Brokers, etc.
|
||||
logger.info(`Initializing ${broker} broker connection for account ${accountId}`);
|
||||
}
|
||||
|
||||
async submitOrder(orderRequest: OrderRequest): Promise<ExecutionReport> {
|
||||
// Validate order request
|
||||
const validatedOrder = OrderRequestSchema.parse(orderRequest);
|
||||
|
||||
// Generate order ID
|
||||
const orderId = uuidv4();
|
||||
const clientOrderId = validatedOrder.clientOrderId || orderId;
|
||||
|
||||
// Store pending order
|
||||
this.pendingOrders.set(orderId, validatedOrder);
|
||||
|
||||
try {
|
||||
// Check risk before submitting
|
||||
const riskResult = await this.checkRisk(validatedOrder);
|
||||
if (!riskResult.passed) {
|
||||
return this.createRejectionReport(
|
||||
orderId,
|
||||
clientOrderId,
|
||||
validatedOrder,
|
||||
`Risk check failed: ${riskResult.violations.join(', ')}`
|
||||
);
|
||||
}
|
||||
|
||||
// Submit based on mode
|
||||
let result: ExecutionReport;
|
||||
|
||||
switch (this.mode) {
|
||||
case 'backtest':
|
||||
case 'paper':
|
||||
result = await this.submitToSimulation(orderId, clientOrderId, validatedOrder);
|
||||
break;
|
||||
case 'live':
|
||||
result = await this.submitToBroker(orderId, clientOrderId, validatedOrder);
|
||||
break;
|
||||
}
|
||||
|
||||
// Emit order event
|
||||
this.emit('orderUpdate', result);
|
||||
|
||||
// If filled, update positions
|
||||
if (result.fills.length > 0) {
|
||||
await this.processFills(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error submitting order:', error);
|
||||
return this.createRejectionReport(
|
||||
orderId,
|
||||
clientOrderId,
|
||||
validatedOrder,
|
||||
error instanceof Error ? error.message : 'Unknown error'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async checkRisk(order: OrderRequest): Promise<any> {
|
||||
if (!this.tradingEngine) {
|
||||
throw new Error('Trading engine not initialized');
|
||||
}
|
||||
|
||||
// Convert to engine format
|
||||
const engineOrder = {
|
||||
id: uuidv4(),
|
||||
symbol: order.symbol,
|
||||
side: order.side,
|
||||
quantity: order.quantity,
|
||||
orderType: order.orderType,
|
||||
limitPrice: order.limitPrice,
|
||||
timeInForce: order.timeInForce
|
||||
};
|
||||
|
||||
const result = this.tradingEngine.checkRisk(engineOrder);
|
||||
return JSON.parse(result);
|
||||
}
|
||||
|
||||
private async submitToSimulation(
|
||||
orderId: string,
|
||||
clientOrderId: string,
|
||||
order: OrderRequest
|
||||
): Promise<ExecutionReport> {
|
||||
if (!this.tradingEngine) {
|
||||
throw new Error('Trading engine not initialized');
|
||||
}
|
||||
|
||||
// Convert to engine format
|
||||
const engineOrder = {
|
||||
id: orderId,
|
||||
symbol: order.symbol,
|
||||
side: order.side,
|
||||
quantity: order.quantity,
|
||||
orderType: order.orderType,
|
||||
limitPrice: order.limitPrice,
|
||||
timeInForce: order.timeInForce
|
||||
};
|
||||
|
||||
// Submit to engine
|
||||
const result = await this.tradingEngine.submitOrder(engineOrder);
|
||||
const engineResult = JSON.parse(result);
|
||||
|
||||
// Convert back to our format
|
||||
return {
|
||||
orderId,
|
||||
clientOrderId,
|
||||
symbol: order.symbol,
|
||||
side: order.side,
|
||||
quantity: order.quantity,
|
||||
status: this.mapEngineStatus(engineResult.status),
|
||||
fills: engineResult.fills || [],
|
||||
timestamp: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
private async submitToBroker(
|
||||
orderId: string,
|
||||
clientOrderId: string,
|
||||
order: OrderRequest
|
||||
): Promise<ExecutionReport> {
|
||||
// In real implementation, would submit to actual broker
|
||||
// This is a placeholder
|
||||
logger.info(`Submitting order ${orderId} to broker`);
|
||||
|
||||
// Simulate broker response
|
||||
return {
|
||||
orderId,
|
||||
clientOrderId,
|
||||
symbol: order.symbol,
|
||||
side: order.side,
|
||||
quantity: order.quantity,
|
||||
status: 'pending',
|
||||
fills: [],
|
||||
timestamp: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
async cancelOrder(orderId: string): Promise<boolean> {
|
||||
const order = this.pendingOrders.get(orderId);
|
||||
if (!order) {
|
||||
logger.warn(`Order ${orderId} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (this.mode) {
|
||||
case 'backtest':
|
||||
case 'paper':
|
||||
// Cancel in simulation
|
||||
if (this.tradingEngine) {
|
||||
await this.tradingEngine.cancelOrder(orderId);
|
||||
}
|
||||
break;
|
||||
case 'live':
|
||||
// Cancel with broker
|
||||
if (this.brokerClient) {
|
||||
await this.brokerClient.cancelOrder(orderId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
this.pendingOrders.delete(orderId);
|
||||
|
||||
// Emit cancellation event
|
||||
this.emit('orderUpdate', {
|
||||
orderId,
|
||||
status: 'cancelled',
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error cancelling order ${orderId}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async processFills(executionReport: ExecutionReport): Promise<void> {
|
||||
if (!this.tradingEngine) return;
|
||||
|
||||
for (const fill of executionReport.fills) {
|
||||
// Update position in engine
|
||||
const result = this.tradingEngine.processFill(
|
||||
executionReport.symbol,
|
||||
fill.price,
|
||||
fill.quantity,
|
||||
executionReport.side,
|
||||
fill.commission
|
||||
);
|
||||
|
||||
// Emit fill event
|
||||
this.emit('fill', {
|
||||
orderId: executionReport.orderId,
|
||||
symbol: executionReport.symbol,
|
||||
side: executionReport.side,
|
||||
...fill,
|
||||
positionUpdate: JSON.parse(result)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private createRejectionReport(
|
||||
orderId: string,
|
||||
clientOrderId: string,
|
||||
order: OrderRequest,
|
||||
reason: string
|
||||
): ExecutionReport {
|
||||
return {
|
||||
orderId,
|
||||
clientOrderId,
|
||||
symbol: order.symbol,
|
||||
side: order.side,
|
||||
quantity: order.quantity,
|
||||
status: 'rejected',
|
||||
fills: [],
|
||||
rejectionReason: reason,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
private mapEngineStatus(engineStatus: string): ExecutionReport['status'] {
|
||||
const statusMap: Record<string, ExecutionReport['status']> = {
|
||||
'Pending': 'pending',
|
||||
'Accepted': 'accepted',
|
||||
'PartiallyFilled': 'partiallyFilled',
|
||||
'Filled': 'filled',
|
||||
'Cancelled': 'cancelled',
|
||||
'Rejected': 'rejected'
|
||||
};
|
||||
|
||||
return statusMap[engineStatus] || 'rejected';
|
||||
}
|
||||
|
||||
async routeOrderToExchange(order: OrderRequest, exchange: string): Promise<void> {
|
||||
// This would route orders to specific exchanges in live mode
|
||||
// For now, just a placeholder
|
||||
logger.info(`Routing order to ${exchange}:`, order);
|
||||
}
|
||||
|
||||
async getOrderStatus(orderId: string): Promise<ExecutionReport | null> {
|
||||
// In real implementation, would query broker or internal state
|
||||
return null;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
// Cancel all pending orders
|
||||
for (const orderId of this.pendingOrders.keys()) {
|
||||
await this.cancelOrder(orderId);
|
||||
}
|
||||
|
||||
// Disconnect from broker
|
||||
if (this.brokerClient) {
|
||||
// await this.brokerClient.disconnect();
|
||||
this.brokerClient = null;
|
||||
}
|
||||
|
||||
this.tradingEngine = null;
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
280
apps/stock/orchestrator/src/services/MarketDataService.ts
Normal file
280
apps/stock/orchestrator/src/services/MarketDataService.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { EventEmitter } from 'events';
|
||||
import { ModeConfig, MarketData, QuoteSchema, TradeSchema, BarSchema } from '../types';
|
||||
import { QuestDBClient } from '@stock-bot/questdb';
|
||||
|
||||
export class MarketDataService extends EventEmitter {
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
private dataIngestionSocket: Socket | null = null;
|
||||
private questdbClient: QuestDBClient | null = null;
|
||||
private subscriptions = new Set<string>();
|
||||
private batchBuffer: MarketData[] = [];
|
||||
private batchTimer: NodeJS.Timeout | null = null;
|
||||
private readonly BATCH_SIZE = 100;
|
||||
private readonly BATCH_INTERVAL_MS = 50;
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
|
||||
if (config.mode === 'backtest') {
|
||||
// Initialize QuestDB client for historical data
|
||||
this.questdbClient = new QuestDBClient({
|
||||
host: process.env.QUESTDB_HOST || 'localhost',
|
||||
port: parseInt(process.env.QUESTDB_PORT || '9000'),
|
||||
database: process.env.QUESTDB_DATABASE || 'trading'
|
||||
});
|
||||
} else {
|
||||
// Connect to data-ingestion service for real-time data
|
||||
await this.connectToDataIngestion();
|
||||
}
|
||||
}
|
||||
|
||||
private async connectToDataIngestion(): Promise<void> {
|
||||
const dataIngestionUrl = process.env.DATA_INGESTION_URL || 'http://localhost:3001';
|
||||
|
||||
this.dataIngestionSocket = io(dataIngestionUrl, {
|
||||
transports: ['websocket'],
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('connect', () => {
|
||||
logger.info('Connected to data-ingestion service');
|
||||
// Re-subscribe to symbols
|
||||
this.subscriptions.forEach(symbol => {
|
||||
this.dataIngestionSocket!.emit('subscribe', { symbol });
|
||||
});
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('disconnect', () => {
|
||||
logger.warn('Disconnected from data-ingestion service');
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('marketData', (data: any) => {
|
||||
this.handleMarketData(data);
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('error', (error: any) => {
|
||||
logger.error('Data ingestion socket error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
async subscribeToSymbol(symbol: string): Promise<void> {
|
||||
this.subscriptions.add(symbol);
|
||||
|
||||
if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) {
|
||||
this.dataIngestionSocket.emit('subscribe', { symbol });
|
||||
}
|
||||
|
||||
logger.debug(`Subscribed to ${symbol}`);
|
||||
}
|
||||
|
||||
async unsubscribeFromSymbol(symbol: string): Promise<void> {
|
||||
this.subscriptions.delete(symbol);
|
||||
|
||||
if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) {
|
||||
this.dataIngestionSocket.emit('unsubscribe', { symbol });
|
||||
}
|
||||
|
||||
logger.debug(`Unsubscribed from ${symbol}`);
|
||||
}
|
||||
|
||||
private handleMarketData(data: any): void {
|
||||
try {
|
||||
// Validate and transform data
|
||||
let marketData: MarketData;
|
||||
|
||||
if (data.bid !== undefined && data.ask !== undefined) {
|
||||
const quote = QuoteSchema.parse({
|
||||
symbol: data.symbol,
|
||||
bid: data.bid,
|
||||
ask: data.ask,
|
||||
bidSize: data.bidSize || data.bid_size || 0,
|
||||
askSize: data.askSize || data.ask_size || 0,
|
||||
timestamp: data.timestamp || Date.now()
|
||||
});
|
||||
marketData = { type: 'quote', data: quote };
|
||||
} else if (data.price !== undefined && data.size !== undefined) {
|
||||
const trade = TradeSchema.parse({
|
||||
symbol: data.symbol,
|
||||
price: data.price,
|
||||
size: data.size,
|
||||
side: data.side || 'buy',
|
||||
timestamp: data.timestamp || Date.now()
|
||||
});
|
||||
marketData = { type: 'trade', data: trade };
|
||||
} else if (data.open !== undefined && data.close !== undefined) {
|
||||
const bar = BarSchema.parse({
|
||||
symbol: data.symbol,
|
||||
open: data.open,
|
||||
high: data.high,
|
||||
low: data.low,
|
||||
close: data.close,
|
||||
volume: data.volume,
|
||||
vwap: data.vwap,
|
||||
timestamp: data.timestamp || Date.now()
|
||||
});
|
||||
marketData = { type: 'bar', data: bar };
|
||||
} else {
|
||||
logger.warn('Unknown market data format:', data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add to batch buffer
|
||||
this.batchBuffer.push(marketData);
|
||||
|
||||
// Process batch if size threshold reached
|
||||
if (this.batchBuffer.length >= this.BATCH_SIZE) {
|
||||
this.processBatch();
|
||||
} else if (!this.batchTimer) {
|
||||
// Set timer for time-based batching
|
||||
this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error handling market data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private processBatch(): void {
|
||||
if (this.batchBuffer.length === 0) return;
|
||||
|
||||
// Clear timer
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer);
|
||||
this.batchTimer = null;
|
||||
}
|
||||
|
||||
// Emit batch
|
||||
const batch = [...this.batchBuffer];
|
||||
this.batchBuffer = [];
|
||||
|
||||
this.emit('marketDataBatch', batch);
|
||||
|
||||
// Also emit individual events for strategies that need them
|
||||
batch.forEach(data => {
|
||||
this.emit('marketData', data);
|
||||
});
|
||||
}
|
||||
|
||||
async loadHistoricalData(
|
||||
symbols: string[],
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
interval: string = '1m'
|
||||
): Promise<MarketData[]> {
|
||||
if (!this.questdbClient) {
|
||||
throw new Error('QuestDB client not initialized');
|
||||
}
|
||||
|
||||
const data: MarketData[] = [];
|
||||
|
||||
for (const symbol of symbols) {
|
||||
// Query for bars
|
||||
const bars = await this.questdbClient.query(`
|
||||
SELECT
|
||||
timestamp,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
vwap
|
||||
FROM bars_${interval}
|
||||
WHERE symbol = '${symbol}'
|
||||
AND timestamp >= '${startTime.toISOString()}'
|
||||
AND timestamp < '${endTime.toISOString()}'
|
||||
ORDER BY timestamp
|
||||
`);
|
||||
|
||||
// Convert to MarketData format
|
||||
bars.forEach((row: any) => {
|
||||
data.push({
|
||||
type: 'bar',
|
||||
data: {
|
||||
symbol,
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
volume: row.volume,
|
||||
vwap: row.vwap,
|
||||
timestamp: new Date(row.timestamp).getTime()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Also query for trades if needed for more granular simulation
|
||||
if (interval === '1m' || interval === 'tick') {
|
||||
const trades = await this.questdbClient.query(`
|
||||
SELECT
|
||||
timestamp,
|
||||
price,
|
||||
size,
|
||||
side
|
||||
FROM trades
|
||||
WHERE symbol = '${symbol}'
|
||||
AND timestamp >= '${startTime.toISOString()}'
|
||||
AND timestamp < '${endTime.toISOString()}'
|
||||
ORDER BY timestamp
|
||||
`);
|
||||
|
||||
trades.forEach((row: any) => {
|
||||
data.push({
|
||||
type: 'trade',
|
||||
data: {
|
||||
symbol,
|
||||
price: row.price,
|
||||
size: row.size,
|
||||
side: row.side,
|
||||
timestamp: new Date(row.timestamp).getTime()
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort all data by timestamp
|
||||
data.sort((a, b) => {
|
||||
const timeA = a.type === 'bar' ? a.data.timestamp :
|
||||
a.type === 'trade' ? a.data.timestamp :
|
||||
a.data.timestamp;
|
||||
const timeB = b.type === 'bar' ? b.data.timestamp :
|
||||
b.type === 'trade' ? b.data.timestamp :
|
||||
b.data.timestamp;
|
||||
return timeA - timeB;
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
// Clear batch timer
|
||||
if (this.batchTimer) {
|
||||
clearTimeout(this.batchTimer);
|
||||
this.batchTimer = null;
|
||||
}
|
||||
|
||||
// Process any remaining data
|
||||
if (this.batchBuffer.length > 0) {
|
||||
this.processBatch();
|
||||
}
|
||||
|
||||
// Disconnect from data ingestion
|
||||
if (this.dataIngestionSocket) {
|
||||
this.dataIngestionSocket.disconnect();
|
||||
this.dataIngestionSocket = null;
|
||||
}
|
||||
|
||||
// Close QuestDB connection
|
||||
if (this.questdbClient) {
|
||||
await this.questdbClient.close();
|
||||
this.questdbClient = null;
|
||||
}
|
||||
|
||||
this.subscriptions.clear();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
293
apps/stock/orchestrator/src/services/StorageService.ts
Normal file
293
apps/stock/orchestrator/src/services/StorageService.ts
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { QuestDBClient } from '@stock-bot/questdb';
|
||||
import { PostgresClient } from '@stock-bot/postgres';
|
||||
import { ModeConfig, MarketData, Position } from '../types';
|
||||
|
||||
export class StorageService {
|
||||
private questdb: QuestDBClient | null = null;
|
||||
private postgres: PostgresClient | null = null;
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
|
||||
// Initialize QuestDB for time-series data
|
||||
this.questdb = new QuestDBClient({
|
||||
host: process.env.QUESTDB_HOST || 'localhost',
|
||||
port: parseInt(process.env.QUESTDB_PORT || '9000'),
|
||||
database: process.env.QUESTDB_DATABASE || 'trading'
|
||||
});
|
||||
|
||||
// Initialize PostgreSQL for relational data
|
||||
this.postgres = new PostgresClient({
|
||||
host: process.env.POSTGRES_HOST || 'localhost',
|
||||
port: parseInt(process.env.POSTGRES_PORT || '5432'),
|
||||
database: process.env.POSTGRES_DATABASE || 'trading',
|
||||
user: process.env.POSTGRES_USER || 'postgres',
|
||||
password: process.env.POSTGRES_PASSWORD || 'postgres'
|
||||
});
|
||||
|
||||
await this.createTables();
|
||||
}
|
||||
|
||||
private async createTables(): Promise<void> {
|
||||
// Create tables if they don't exist
|
||||
if (this.postgres) {
|
||||
// Orders table
|
||||
await this.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id UUID PRIMARY KEY,
|
||||
client_order_id VARCHAR(255),
|
||||
symbol VARCHAR(50) NOT NULL,
|
||||
side VARCHAR(10) NOT NULL,
|
||||
quantity DECIMAL(20, 8) NOT NULL,
|
||||
order_type VARCHAR(20) NOT NULL,
|
||||
limit_price DECIMAL(20, 8),
|
||||
stop_price DECIMAL(20, 8),
|
||||
time_in_force VARCHAR(10) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
mode VARCHAR(10) NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
// Fills table
|
||||
await this.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS fills (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
order_id UUID NOT NULL REFERENCES orders(id),
|
||||
symbol VARCHAR(50) NOT NULL,
|
||||
price DECIMAL(20, 8) NOT NULL,
|
||||
quantity DECIMAL(20, 8) NOT NULL,
|
||||
commission DECIMAL(20, 8) NOT NULL,
|
||||
side VARCHAR(10) NOT NULL,
|
||||
timestamp TIMESTAMP NOT NULL,
|
||||
mode VARCHAR(10) NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
// Positions table
|
||||
await this.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS positions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
symbol VARCHAR(50) NOT NULL,
|
||||
quantity DECIMAL(20, 8) NOT NULL,
|
||||
average_price DECIMAL(20, 8) NOT NULL,
|
||||
realized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0,
|
||||
unrealized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
mode VARCHAR(10) NOT NULL,
|
||||
UNIQUE(symbol, mode)
|
||||
)
|
||||
`);
|
||||
|
||||
// Strategy performance table
|
||||
await this.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS strategy_performance (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
strategy_id VARCHAR(255) NOT NULL,
|
||||
timestamp TIMESTAMP NOT NULL,
|
||||
total_return DECIMAL(20, 8),
|
||||
sharpe_ratio DECIMAL(20, 8),
|
||||
max_drawdown DECIMAL(20, 8),
|
||||
win_rate DECIMAL(20, 8),
|
||||
total_trades INTEGER,
|
||||
mode VARCHAR(10) NOT NULL
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
|
||||
async storeMarketData(data: MarketData[]): Promise<void> {
|
||||
if (!this.questdb) return;
|
||||
|
||||
for (const item of data) {
|
||||
try {
|
||||
switch (item.type) {
|
||||
case 'quote':
|
||||
await this.questdb.insert('quotes', {
|
||||
symbol: item.data.symbol,
|
||||
bid: item.data.bid,
|
||||
ask: item.data.ask,
|
||||
bid_size: item.data.bidSize,
|
||||
ask_size: item.data.askSize,
|
||||
timestamp: new Date(item.data.timestamp)
|
||||
});
|
||||
break;
|
||||
|
||||
case 'trade':
|
||||
await this.questdb.insert('trades', {
|
||||
symbol: item.data.symbol,
|
||||
price: item.data.price,
|
||||
size: item.data.size,
|
||||
side: item.data.side,
|
||||
timestamp: new Date(item.data.timestamp)
|
||||
});
|
||||
break;
|
||||
|
||||
case 'bar':
|
||||
const interval = '1m'; // Would be determined from context
|
||||
await this.questdb.insert(`bars_${interval}`, {
|
||||
symbol: item.data.symbol,
|
||||
open: item.data.open,
|
||||
high: item.data.high,
|
||||
low: item.data.low,
|
||||
close: item.data.close,
|
||||
volume: item.data.volume,
|
||||
vwap: item.data.vwap || null,
|
||||
timestamp: new Date(item.data.timestamp)
|
||||
});
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error storing market data:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async storeOrder(order: any): Promise<void> {
|
||||
if (!this.postgres) return;
|
||||
|
||||
await this.postgres.query(`
|
||||
INSERT INTO orders (
|
||||
id, client_order_id, symbol, side, quantity,
|
||||
order_type, limit_price, stop_price, time_in_force,
|
||||
status, mode
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`, [
|
||||
order.id,
|
||||
order.clientOrderId,
|
||||
order.symbol,
|
||||
order.side,
|
||||
order.quantity,
|
||||
order.orderType,
|
||||
order.limitPrice || null,
|
||||
order.stopPrice || null,
|
||||
order.timeInForce,
|
||||
order.status,
|
||||
this.mode
|
||||
]);
|
||||
}
|
||||
|
||||
async updateOrderStatus(orderId: string, status: string): Promise<void> {
|
||||
if (!this.postgres) return;
|
||||
|
||||
await this.postgres.query(`
|
||||
UPDATE orders
|
||||
SET status = $1, updated_at = NOW()
|
||||
WHERE id = $2
|
||||
`, [status, orderId]);
|
||||
}
|
||||
|
||||
async storeFill(fill: any): Promise<void> {
|
||||
if (!this.postgres) return;
|
||||
|
||||
await this.postgres.query(`
|
||||
INSERT INTO fills (
|
||||
order_id, symbol, price, quantity, commission, side, timestamp, mode
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
`, [
|
||||
fill.orderId,
|
||||
fill.symbol,
|
||||
fill.price,
|
||||
fill.quantity,
|
||||
fill.commission,
|
||||
fill.side,
|
||||
new Date(fill.timestamp),
|
||||
this.mode
|
||||
]);
|
||||
}
|
||||
|
||||
async updatePosition(position: Position): Promise<void> {
|
||||
if (!this.postgres) return;
|
||||
|
||||
await this.postgres.query(`
|
||||
INSERT INTO positions (
|
||||
symbol, quantity, average_price, realized_pnl, unrealized_pnl, mode
|
||||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT (symbol, mode) DO UPDATE SET
|
||||
quantity = $2,
|
||||
average_price = $3,
|
||||
realized_pnl = $4,
|
||||
unrealized_pnl = $5,
|
||||
updated_at = NOW()
|
||||
`, [
|
||||
position.symbol,
|
||||
position.quantity,
|
||||
position.averagePrice,
|
||||
position.realizedPnl,
|
||||
position.unrealizedPnl,
|
||||
this.mode
|
||||
]);
|
||||
}
|
||||
|
||||
async getPositions(): Promise<Position[]> {
|
||||
if (!this.postgres) return [];
|
||||
|
||||
const result = await this.postgres.query(`
|
||||
SELECT * FROM positions WHERE mode = $1
|
||||
`, [this.mode]);
|
||||
|
||||
return result.rows.map((row: any) => ({
|
||||
symbol: row.symbol,
|
||||
quantity: parseFloat(row.quantity),
|
||||
averagePrice: parseFloat(row.average_price),
|
||||
realizedPnl: parseFloat(row.realized_pnl),
|
||||
unrealizedPnl: parseFloat(row.unrealized_pnl),
|
||||
totalCost: parseFloat(row.quantity) * parseFloat(row.average_price),
|
||||
lastUpdate: row.updated_at
|
||||
}));
|
||||
}
|
||||
|
||||
async storeStrategyPerformance(strategyId: string, metrics: any): Promise<void> {
|
||||
if (!this.postgres) return;
|
||||
|
||||
await this.postgres.query(`
|
||||
INSERT INTO strategy_performance (
|
||||
strategy_id, timestamp, total_return, sharpe_ratio,
|
||||
max_drawdown, win_rate, total_trades, mode
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
`, [
|
||||
strategyId,
|
||||
new Date(),
|
||||
metrics.totalReturn,
|
||||
metrics.sharpeRatio,
|
||||
metrics.maxDrawdown,
|
||||
metrics.winRate,
|
||||
metrics.totalTrades,
|
||||
this.mode
|
||||
]);
|
||||
}
|
||||
|
||||
async getHistoricalBars(
|
||||
symbol: string,
|
||||
startTime: Date,
|
||||
endTime: Date,
|
||||
interval: string = '1m'
|
||||
): Promise<any[]> {
|
||||
if (!this.questdb) return [];
|
||||
|
||||
const result = await this.questdb.query(`
|
||||
SELECT * FROM bars_${interval}
|
||||
WHERE symbol = '${symbol}'
|
||||
AND timestamp >= '${startTime.toISOString()}'
|
||||
AND timestamp < '${endTime.toISOString()}'
|
||||
ORDER BY timestamp
|
||||
`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
if (this.questdb) {
|
||||
await this.questdb.close();
|
||||
this.questdb = null;
|
||||
}
|
||||
|
||||
if (this.postgres) {
|
||||
await this.postgres.close();
|
||||
this.postgres = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue