| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- #!/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<void> {
- 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<void> {
- 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<void> {
- 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<void> {
- 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<void> {
- 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)
- }
|