messy work. backtests / mock-data
This commit is contained in:
parent
4e4a048988
commit
fa70ada2bb
51 changed files with 2576 additions and 887 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import axios from 'axios';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { PerformanceMetrics, RiskMetrics } from '../types';
|
||||
import { StorageService } from './StorageService';
|
||||
|
||||
interface OptimizationParams {
|
||||
returns: number[][];
|
||||
|
|
@ -24,8 +25,12 @@ export class AnalyticsService {
|
|||
private analyticsUrl: string;
|
||||
private cache = new Map<string, { data: any; timestamp: number }>();
|
||||
private readonly CACHE_TTL_MS = 60000; // 1 minute cache
|
||||
private container: IServiceContainer;
|
||||
private storageService: StorageService;
|
||||
|
||||
constructor() {
|
||||
constructor(container: IServiceContainer, storageService: StorageService) {
|
||||
this.container = container;
|
||||
this.storageService = storageService;
|
||||
this.analyticsUrl = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003';
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +55,7 @@ export class AnalyticsService {
|
|||
this.setCache(cacheKey, metrics);
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
logger.error('Error fetching performance metrics:', error);
|
||||
this.container.logger.error('Error fetching performance metrics:', error);
|
||||
// Return default metrics if analytics service is unavailable
|
||||
return this.getDefaultPerformanceMetrics();
|
||||
}
|
||||
|
|
@ -61,7 +66,7 @@ export class AnalyticsService {
|
|||
const response = await axios.post(`${this.analyticsUrl}/optimize/portfolio`, params);
|
||||
return response.data as PortfolioWeights;
|
||||
} catch (error) {
|
||||
logger.error('Error optimizing portfolio:', error);
|
||||
this.container.logger.error('Error optimizing portfolio:', error);
|
||||
// Return equal weights as fallback
|
||||
return this.getEqualWeights(params.returns[0].length);
|
||||
}
|
||||
|
|
@ -78,7 +83,7 @@ export class AnalyticsService {
|
|||
this.setCache(cacheKey, metrics);
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
logger.error('Error fetching risk metrics:', error);
|
||||
this.container.logger.error('Error fetching risk metrics:', error);
|
||||
return this.getDefaultRiskMetrics();
|
||||
}
|
||||
}
|
||||
|
|
@ -94,7 +99,7 @@ export class AnalyticsService {
|
|||
this.setCache(cacheKey, regime, 300000); // Cache for 5 minutes
|
||||
return regime;
|
||||
} catch (error) {
|
||||
logger.error('Error detecting market regime:', error);
|
||||
this.container.logger.error('Error detecting market regime:', error);
|
||||
return 'normal'; // Default regime
|
||||
}
|
||||
}
|
||||
|
|
@ -104,7 +109,7 @@ export class AnalyticsService {
|
|||
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);
|
||||
this.container.logger.error('Error calculating correlation matrix:', error);
|
||||
// Return identity matrix as fallback
|
||||
return this.getIdentityMatrix(symbols.length);
|
||||
}
|
||||
|
|
@ -115,7 +120,7 @@ export class AnalyticsService {
|
|||
const response = await axios.get(`${this.analyticsUrl}/analytics/backtest/${backtestId}`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
logger.error('Error running backtest analysis:', error);
|
||||
this.container.logger.error('Error running backtest analysis:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -128,7 +133,7 @@ export class AnalyticsService {
|
|||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
logger.error('Error getting model prediction:', error);
|
||||
this.container.logger.error('Error getting model prediction:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { EventEmitter } from 'events';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { ModeConfig, OrderRequest, OrderRequestSchema } from '../types';
|
||||
import { TradingEngine } from '../../core';
|
||||
import { TradingEngine } from '@stock-bot/core';
|
||||
import axios from 'axios';
|
||||
import { StorageService } from './StorageService';
|
||||
|
||||
interface ExecutionReport {
|
||||
orderId: string;
|
||||
|
|
@ -29,9 +30,13 @@ export class ExecutionService extends EventEmitter {
|
|||
private tradingEngine: TradingEngine | null = null;
|
||||
private brokerClient: any = null; // Would be specific broker API client
|
||||
private pendingOrders = new Map<string, OrderRequest>();
|
||||
private container: IServiceContainer;
|
||||
private storageService: StorageService;
|
||||
|
||||
constructor(private modeManager: any) {
|
||||
constructor(container: IServiceContainer, storageService: StorageService) {
|
||||
super();
|
||||
this.container = container;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig, tradingEngine: TradingEngine): Promise<void> {
|
||||
|
|
@ -47,7 +52,7 @@ export class ExecutionService extends EventEmitter {
|
|||
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}`);
|
||||
this.container.logger.info(`Initializing ${broker} broker connection for account ${accountId}`);
|
||||
}
|
||||
|
||||
async submitOrder(orderRequest: OrderRequest): Promise<ExecutionReport> {
|
||||
|
|
@ -97,7 +102,7 @@ export class ExecutionService extends EventEmitter {
|
|||
return result;
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error submitting order:', error);
|
||||
this.container.logger.error('Error submitting order:', error);
|
||||
return this.createRejectionReport(
|
||||
orderId,
|
||||
clientOrderId,
|
||||
|
|
@ -171,7 +176,7 @@ export class ExecutionService extends EventEmitter {
|
|||
): Promise<ExecutionReport> {
|
||||
// In real implementation, would submit to actual broker
|
||||
// This is a placeholder
|
||||
logger.info(`Submitting order ${orderId} to broker`);
|
||||
this.container.logger.info(`Submitting order ${orderId} to broker`);
|
||||
|
||||
// Simulate broker response
|
||||
return {
|
||||
|
|
@ -189,7 +194,7 @@ export class ExecutionService extends EventEmitter {
|
|||
async cancelOrder(orderId: string): Promise<boolean> {
|
||||
const order = this.pendingOrders.get(orderId);
|
||||
if (!order) {
|
||||
logger.warn(`Order ${orderId} not found`);
|
||||
this.container.logger.warn(`Order ${orderId} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -222,7 +227,7 @@ export class ExecutionService extends EventEmitter {
|
|||
return true;
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error cancelling order ${orderId}:`, error);
|
||||
this.container.logger.error(`Error cancelling order ${orderId}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -286,7 +291,7 @@ export class ExecutionService extends EventEmitter {
|
|||
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);
|
||||
this.container.logger.info(`Routing order to ${exchange}:`, order);
|
||||
}
|
||||
|
||||
async getOrderStatus(orderId: string): Promise<ExecutionReport | null> {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { EventEmitter } from 'events';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { ModeConfig, MarketData, QuoteSchema, TradeSchema, BarSchema } from '../types';
|
||||
import { QuestDBClient } from '@stock-bot/questdb';
|
||||
|
||||
|
|
@ -13,6 +13,12 @@ export class MarketDataService extends EventEmitter {
|
|||
private batchTimer: NodeJS.Timeout | null = null;
|
||||
private readonly BATCH_SIZE = 100;
|
||||
private readonly BATCH_INTERVAL_MS = 50;
|
||||
private container: IServiceContainer;
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
super();
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
|
|
@ -41,7 +47,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('connect', () => {
|
||||
logger.info('Connected to data-ingestion service');
|
||||
this.container.logger.info('Connected to data-ingestion service');
|
||||
// Re-subscribe to symbols
|
||||
this.subscriptions.forEach(symbol => {
|
||||
this.dataIngestionSocket!.emit('subscribe', { symbol });
|
||||
|
|
@ -49,7 +55,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('disconnect', () => {
|
||||
logger.warn('Disconnected from data-ingestion service');
|
||||
this.container.logger.warn('Disconnected from data-ingestion service');
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('marketData', (data: any) => {
|
||||
|
|
@ -57,7 +63,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('error', (error: any) => {
|
||||
logger.error('Data ingestion socket error:', error);
|
||||
this.container.logger.error('Data ingestion socket error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -68,7 +74,7 @@ export class MarketDataService extends EventEmitter {
|
|||
this.dataIngestionSocket.emit('subscribe', { symbol });
|
||||
}
|
||||
|
||||
logger.debug(`Subscribed to ${symbol}`);
|
||||
this.container.logger.debug(`Subscribed to ${symbol}`);
|
||||
}
|
||||
|
||||
async unsubscribeFromSymbol(symbol: string): Promise<void> {
|
||||
|
|
@ -78,7 +84,7 @@ export class MarketDataService extends EventEmitter {
|
|||
this.dataIngestionSocket.emit('unsubscribe', { symbol });
|
||||
}
|
||||
|
||||
logger.debug(`Unsubscribed from ${symbol}`);
|
||||
this.container.logger.debug(`Unsubscribed from ${symbol}`);
|
||||
}
|
||||
|
||||
private handleMarketData(data: any): void {
|
||||
|
|
@ -118,7 +124,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
marketData = { type: 'bar', data: bar };
|
||||
} else {
|
||||
logger.warn('Unknown market data format:', data);
|
||||
this.container.logger.warn('Unknown market data format:', data);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -134,7 +140,7 @@ export class MarketDataService extends EventEmitter {
|
|||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error handling market data:', error);
|
||||
this.container.logger.error('Error handling market data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -270,7 +276,7 @@ export class MarketDataService extends EventEmitter {
|
|||
|
||||
// Close QuestDB connection
|
||||
if (this.questdbClient) {
|
||||
await this.questdbClient.close();
|
||||
await this.questdbClient.disconnect();
|
||||
this.questdbClient = null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,32 +1,31 @@
|
|||
import { logger } from '@stock-bot/logger';
|
||||
import { IServiceContainer } from '@stock-bot/di';
|
||||
import { QuestDBClient } from '@stock-bot/questdb';
|
||||
import { PostgresClient } from '@stock-bot/postgres';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { ModeConfig, MarketData, Position } from '../types';
|
||||
|
||||
export class StorageService {
|
||||
private questdb: QuestDBClient | null = null;
|
||||
private postgres: PostgresClient | null = null;
|
||||
private mongodb: MongoDBClient | null = null;
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
private container: IServiceContainer;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
mongoClient: MongoDBClient,
|
||||
postgresClient: PostgresClient,
|
||||
questdbClient: QuestDBClient | null
|
||||
) {
|
||||
this.container = container;
|
||||
this.mongodb = mongoClient;
|
||||
this.postgres = postgresClient;
|
||||
this.questdb = questdbClient;
|
||||
}
|
||||
|
||||
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'
|
||||
});
|
||||
|
||||
// Clients are already injected via DI
|
||||
await this.createTables();
|
||||
}
|
||||
|
||||
|
|
@ -281,12 +280,12 @@ export class StorageService {
|
|||
|
||||
async shutdown(): Promise<void> {
|
||||
if (this.questdb) {
|
||||
await this.questdb.close();
|
||||
await this.questdb.disconnect();
|
||||
this.questdb = null;
|
||||
}
|
||||
|
||||
if (this.postgres) {
|
||||
await this.postgres.close();
|
||||
await this.postgres.disconnect();
|
||||
this.postgres = null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue