#!/usr/bin/env tsx /** * 生产环境主入口 * 对冲刷量交易系统 - 多平台多账户 Delta 中性策略 */ import { fileURLToPath } from 'url' import { dirname, join } from 'path' import process from 'process' // 生产环境日志和健康检查 import { ProductionLogger } from './utils/ProductionLogger.js' import { HealthChecker, HealthAPI } from './infrastructure/health/index.js' // 核心系统组件 import { UnifiedAccountManager } from './accounts/UnifiedAccountManager.js' import { AccountConfigLoader } from './accounts/AccountConfigLoader.js' import { AdapterFactory } from './exchanges/AdapterFactory.js' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) class HedgeTradingSystem { private logger: ProductionLogger private healthChecker: HealthChecker private healthAPI: HealthAPI | null = null private accountManager: UnifiedAccountManager | null = null private configLoader: AccountConfigLoader | null = null private isShuttingDown = false constructor() { // 初始化生产日志器 this.logger = ProductionLogger.getInstance({ level: 'info', enableConsole: true, enableFile: true, logDir: process.env.LOG_DIR || './logs', enableAudit: true, }) // 初始化健康检查系统 this.healthChecker = new HealthChecker() if (process.env.ENABLE_HEALTH_API === 'true') { this.healthAPI = new HealthAPI(this.healthChecker, { port: parseInt(process.env.HEALTH_CHECK_PORT || '3001'), host: process.env.HEALTH_CHECK_HOST || 'localhost', enableDetailedResponse: true, }) } this.setupSignalHandlers() } /** * 启动对冲交易系统 */ async start(): Promise { try { this.logger.info( '🚀 启动对冲刷量交易系统', { nodeEnv: process.env.NODE_ENV, processId: process.pid, version: process.env.npm_package_version || '1.0.0', runtime: 'tsx', }, 'STARTUP', ) // 启动健康检查 API if (this.healthAPI) { await this.healthAPI.start() this.logger.info( '✅ 健康检查 API 已启动', { port: this.healthAPI.getServerInfo().port, }, 'HEALTH', ) } // 初始化账户管理系统 await this.initializeAccountManager() // 加载账户配置 (如果存在配置文件) await this.loadAccountConfig() // 启动定期健康检查 await this.healthChecker.performHealthCheck() this.logger.info('✅ 系统健康检查已启动', {}, 'HEALTH') // 注册系统健康事件监听 this.setupHealthEventListeners() // 系统就绪信号 (用于PM2) if (process.send) { process.send('ready') } this.logger.info( '🎯 对冲交易系统启动完成', { features: ['多平台多账户管理', '全局Delta中性策略', '实时仓位监控', '自动对冲执行', '配置文件热更新'], }, 'STARTUP', ) } catch (error: any) { this.logger.critical('❌ 系统启动失败', error, {}, 'STARTUP') process.exit(1) } } /** * 初始化账户管理系统 */ private async initializeAccountManager(): Promise { this.logger.info('🏦 初始化多平台账户管理系统...', {}, 'ACCOUNT') try { // 创建统一账户管理器 this.accountManager = new UnifiedAccountManager() // 注册账户管理器到健康检查 this.healthChecker.registerAccountManager('unified', this.accountManager) // 启动账户状态监控 this.setupAccountMonitoring() this.logger.info('✅ 账户管理系统初始化完成', {}, 'ACCOUNT') } catch (error: any) { this.logger.error('❌ 账户管理系统初始化失败', error, {}, 'ACCOUNT') throw error } } /** * 加载账户配置 */ private async loadAccountConfig(): Promise { const configFile = process.env.ACCOUNTS_CONFIG_FILE || './accounts.config.json' try { this.configLoader = new AccountConfigLoader(configFile) if (!this.configLoader.exists()) { this.logger.warn( '⚠️ 账户配置文件不存在,将使用环境变量注册', { configFile, }, 'CONFIG', ) // 尝试从环境变量注册默认支持的交易所 await this.registerFromEnvironment() return } // 加载配置文件 const config = this.configLoader.load() this.logger.info( '📁 账户配置文件加载成功', { totalAccounts: config.accounts.length, enabledAccounts: config.accounts.filter(a => a.enabled).length, hedgingGroups: config.hedgingGroups?.length || 0, tradingRules: config.tradingRules?.length || 0, }, 'CONFIG', ) // 批量注册账户 const enabledAccounts = this.configLoader.getEnabledAccounts() if (enabledAccounts.length > 0) { const accountConfigs = this.configLoader.convertToAccountConfigs(enabledAccounts) await this.accountManager!.registerAccountsFromConfig(accountConfigs) } // 启用配置文件热更新监听 if (process.env.ENABLE_CONFIG_WATCHING === 'true') { this.setupConfigWatching() } } catch (error: any) { this.logger.error( '❌ 账户配置加载失败', error, { configFile, }, 'CONFIG', ) // 配置文件加载失败时,尝试环境变量方式 this.logger.info('🔄 尝试使用环境变量方式注册账户...', {}, 'CONFIG') await this.registerFromEnvironment() } } /** * 从环境变量注册默认账户 */ private async registerFromEnvironment(): Promise { const exchanges = ['pacifica', 'aster'] for (const exchange of exchanges) { try { const result = await AdapterFactory.createFromEnv(exchange as any) const adapter = result.adapter // 注册到健康检查系统 this.healthChecker.registerExchange(exchange, adapter as any) this.logger.info( `✅ ${exchange.toUpperCase()} 交易所适配器已注册`, { exchange, source: 'environment', }, 'EXCHANGE', ) } catch (error: any) { this.logger.warn( `⚠️ ${exchange.toUpperCase()} 交易所初始化失败`, { exchange, error: error.message, source: 'environment', }, 'EXCHANGE', ) } } } /** * 设置配置文件监听 */ private setupConfigWatching(): void { if (!this.configLoader) return this.configLoader.on('config_changed', async (newConfig, oldConfig) => { this.logger.info( '📄 检测到配置文件更新', { newAccounts: newConfig.accounts.length, oldAccounts: oldConfig?.accounts.length || 0, }, 'CONFIG', ) try { // 重新加载账户配置 (简化实现) const enabledAccounts = this.configLoader!.getEnabledAccounts() const accountConfigs = this.configLoader!.convertToAccountConfigs(enabledAccounts) this.logger.info( '🔄 应用新的账户配置...', { accounts: accountConfigs.length, }, 'CONFIG', ) // 实际环境中这里会做更复杂的差异对比和增量更新 } catch (error: any) { this.logger.error('❌ 配置文件热更新失败', error, {}, 'CONFIG') } }) this.configLoader.on('config_error', error => { this.logger.error('❌ 配置文件监听错误', error, {}, 'CONFIG') }) this.configLoader.startWatching() this.logger.info('👁️ 配置文件热更新监听已启用', {}, 'CONFIG') } /** * 设置账户监控 */ private setupAccountMonitoring(): void { if (!this.accountManager) return // 监听账户事件 this.accountManager.on('account_registered', data => { this.logger.account('账户注册成功', { exchange: data.exchange, accountId: data.accountId, }) }) this.accountManager.on('balance_update', data => { this.logger.account('余额更新', { exchange: data.exchange, accountId: data.accountId, balances: data.balances, }) }) this.accountManager.on('position_update', data => { this.logger.account('仓位更新', { exchange: data.exchange, accountId: data.accountId, positions: data.positions, }) // 计算全局 Delta (简化版本) this.calculateAndLogGlobalDelta(data) }) } /** * 计算并记录全局 Delta */ private calculateAndLogGlobalDelta(data: any): void { try { // 这里应该实现真正的 Delta 计算逻辑 // 暂时使用简化版本 const totalValue = data.positions?.reduce((sum: number, pos: any) => { return sum + parseFloat(pos.notional || '0') }, 0) || 0 this.logger.performance('GlobalDelta', Math.abs(totalValue), { exchange: data.exchange, accountId: data.accountId, positionCount: data.positions?.length || 0, category: 'delta_neutral', }) // 如果 Delta 超过阈值,记录警告 const deltaThreshold = parseFloat(process.env.DELTA_THRESHOLD || '100') if (Math.abs(totalValue) > deltaThreshold) { this.logger.warn( '⚠️ 全局Delta超出阈值', { currentDelta: totalValue, threshold: deltaThreshold, exchange: data.exchange, }, 'RISK', ) } } catch (error: any) { this.logger.error('Delta计算失败', error, {}, 'CALCULATION') } } /** * 设置健康检查事件监听 */ private setupHealthEventListeners(): void { this.healthChecker.on('system_unhealthy', health => { this.logger.critical( '🚨 系统不健康', { status: health.status, exchanges: Object.keys(health.exchanges), accounts: Object.keys(health.accounts), errors: health.errors.total, }, 'HEALTH', ) }) this.healthChecker.on('exchange_disconnected', data => { this.logger.error( '🔌 交易所连接断开', { exchange: data.exchange, }, 'EXCHANGE', ) }) this.healthChecker.on('exchange_connected', data => { this.logger.info( '✅ 交易所重新连接', { exchange: data.exchange, }, 'EXCHANGE', ) }) } /** * 设置信号处理器 - 优雅关闭 */ private setupSignalHandlers(): void { const signals = ['SIGTERM', 'SIGINT', 'SIGUSR2'] // SIGUSR2 是 PM2 重启信号 signals.forEach(signal => { process.on(signal, async () => { if (this.isShuttingDown) return this.logger.info(`📡 接收到 ${signal} 信号,开始优雅关闭...`, {}, 'SHUTDOWN') await this.gracefulShutdown() }) }) // 处理未捕获的错误 process.on('uncaughtException', error => { this.logger.critical('💥 未捕获异常', error, {}, 'ERROR') this.gracefulShutdown().then(() => process.exit(1)) }) process.on('unhandledRejection', (reason, promise) => { this.logger.critical( '💥 未处理的Promise拒绝', reason as Error, { promise: promise.toString(), }, 'ERROR', ) }) } /** * 优雅关闭系统 */ private async gracefulShutdown(): Promise { if (this.isShuttingDown) return this.isShuttingDown = true try { this.logger.info('🛑 开始系统优雅关闭...', {}, 'SHUTDOWN') // 停止配置文件监听 if (this.configLoader) { this.configLoader.stopWatching() this.logger.info('✅ 配置文件监听已停止', {}, 'SHUTDOWN') } // 关闭健康检查 API if (this.healthAPI) { await this.healthAPI.stop() this.logger.info('✅ 健康检查API已关闭', {}, 'SHUTDOWN') } // 关闭账户管理器连接 if (this.accountManager) { // 这里应该添加账户管理器的清理逻辑 this.logger.info('✅ 账户管理器已清理', {}, 'SHUTDOWN') } // 关闭日志系统 this.logger.info('✅ 对冲交易系统优雅关闭完成', {}, 'SHUTDOWN') this.logger.close() process.exit(0) } catch (error: any) { console.error('关闭过程中发生错误:', error) process.exit(1) } } } // 启动系统 if (import.meta.url === `file://${process.argv[1]}`) { const system = new HedgeTradingSystem() system.start().catch(console.error) }