main-production.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #!/usr/bin/env tsx
  2. /**
  3. * 生产环境主入口
  4. * 对冲刷量交易系统 - 多平台多账户 Delta 中性策略
  5. */
  6. import { fileURLToPath } from 'url'
  7. import { dirname, join } from 'path'
  8. import process from 'process'
  9. // 生产环境日志和健康检查
  10. import { ProductionLogger } from './utils/ProductionLogger.js'
  11. import { HealthChecker, HealthAPI } from './infrastructure/health/index.js'
  12. // 核心系统组件
  13. import { UnifiedAccountManager } from './accounts/UnifiedAccountManager.js'
  14. import { AccountConfigLoader } from './accounts/AccountConfigLoader.js'
  15. import { AdapterFactory } from './exchanges/AdapterFactory.js'
  16. const __filename = fileURLToPath(import.meta.url)
  17. const __dirname = dirname(__filename)
  18. class HedgeTradingSystem {
  19. private logger: ProductionLogger
  20. private healthChecker: HealthChecker
  21. private healthAPI: HealthAPI | null = null
  22. private accountManager: UnifiedAccountManager | null = null
  23. private configLoader: AccountConfigLoader | null = null
  24. private isShuttingDown = false
  25. constructor() {
  26. // 初始化生产日志器
  27. this.logger = ProductionLogger.getInstance({
  28. level: 'info',
  29. enableConsole: true,
  30. enableFile: true,
  31. logDir: process.env.LOG_DIR || './logs',
  32. enableAudit: true,
  33. })
  34. // 初始化健康检查系统
  35. this.healthChecker = new HealthChecker()
  36. if (process.env.ENABLE_HEALTH_API === 'true') {
  37. this.healthAPI = new HealthAPI(this.healthChecker, {
  38. port: parseInt(process.env.HEALTH_CHECK_PORT || '3001'),
  39. host: process.env.HEALTH_CHECK_HOST || 'localhost',
  40. enableDetailedResponse: true,
  41. })
  42. }
  43. this.setupSignalHandlers()
  44. }
  45. /**
  46. * 启动对冲交易系统
  47. */
  48. async start(): Promise<void> {
  49. try {
  50. this.logger.info(
  51. '🚀 启动对冲刷量交易系统',
  52. {
  53. nodeEnv: process.env.NODE_ENV,
  54. processId: process.pid,
  55. version: process.env.npm_package_version || '1.0.0',
  56. runtime: 'tsx',
  57. },
  58. 'STARTUP',
  59. )
  60. // 启动健康检查 API
  61. if (this.healthAPI) {
  62. await this.healthAPI.start()
  63. this.logger.info(
  64. '✅ 健康检查 API 已启动',
  65. {
  66. port: this.healthAPI.getServerInfo().port,
  67. },
  68. 'HEALTH',
  69. )
  70. }
  71. // 初始化账户管理系统
  72. await this.initializeAccountManager()
  73. // 加载账户配置 (如果存在配置文件)
  74. await this.loadAccountConfig()
  75. // 启动定期健康检查
  76. await this.healthChecker.performHealthCheck()
  77. this.logger.info('✅ 系统健康检查已启动', {}, 'HEALTH')
  78. // 注册系统健康事件监听
  79. this.setupHealthEventListeners()
  80. // 系统就绪信号 (用于PM2)
  81. if (process.send) {
  82. process.send('ready')
  83. }
  84. this.logger.info(
  85. '🎯 对冲交易系统启动完成',
  86. {
  87. features: ['多平台多账户管理', '全局Delta中性策略', '实时仓位监控', '自动对冲执行', '配置文件热更新'],
  88. },
  89. 'STARTUP',
  90. )
  91. } catch (error: any) {
  92. this.logger.critical('❌ 系统启动失败', error, {}, 'STARTUP')
  93. process.exit(1)
  94. }
  95. }
  96. /**
  97. * 初始化账户管理系统
  98. */
  99. private async initializeAccountManager(): Promise<void> {
  100. this.logger.info('🏦 初始化多平台账户管理系统...', {}, 'ACCOUNT')
  101. try {
  102. // 创建统一账户管理器
  103. this.accountManager = new UnifiedAccountManager()
  104. // 注册账户管理器到健康检查
  105. this.healthChecker.registerAccountManager('unified', this.accountManager)
  106. // 启动账户状态监控
  107. this.setupAccountMonitoring()
  108. this.logger.info('✅ 账户管理系统初始化完成', {}, 'ACCOUNT')
  109. } catch (error: any) {
  110. this.logger.error('❌ 账户管理系统初始化失败', error, {}, 'ACCOUNT')
  111. throw error
  112. }
  113. }
  114. /**
  115. * 加载账户配置
  116. */
  117. private async loadAccountConfig(): Promise<void> {
  118. const configFile = process.env.ACCOUNTS_CONFIG_FILE || './accounts.config.json'
  119. try {
  120. this.configLoader = new AccountConfigLoader(configFile)
  121. if (!this.configLoader.exists()) {
  122. this.logger.warn(
  123. '⚠️ 账户配置文件不存在,将使用环境变量注册',
  124. {
  125. configFile,
  126. },
  127. 'CONFIG',
  128. )
  129. // 尝试从环境变量注册默认支持的交易所
  130. await this.registerFromEnvironment()
  131. return
  132. }
  133. // 加载配置文件
  134. const config = this.configLoader.load()
  135. this.logger.info(
  136. '📁 账户配置文件加载成功',
  137. {
  138. totalAccounts: config.accounts.length,
  139. enabledAccounts: config.accounts.filter(a => a.enabled).length,
  140. hedgingGroups: config.hedgingGroups?.length || 0,
  141. tradingRules: config.tradingRules?.length || 0,
  142. },
  143. 'CONFIG',
  144. )
  145. // 批量注册账户
  146. const enabledAccounts = this.configLoader.getEnabledAccounts()
  147. if (enabledAccounts.length > 0) {
  148. const accountConfigs = this.configLoader.convertToAccountConfigs(enabledAccounts)
  149. await this.accountManager!.registerAccountsFromConfig(accountConfigs)
  150. }
  151. // 启用配置文件热更新监听
  152. if (process.env.ENABLE_CONFIG_WATCHING === 'true') {
  153. this.setupConfigWatching()
  154. }
  155. } catch (error: any) {
  156. this.logger.error(
  157. '❌ 账户配置加载失败',
  158. error,
  159. {
  160. configFile,
  161. },
  162. 'CONFIG',
  163. )
  164. // 配置文件加载失败时,尝试环境变量方式
  165. this.logger.info('🔄 尝试使用环境变量方式注册账户...', {}, 'CONFIG')
  166. await this.registerFromEnvironment()
  167. }
  168. }
  169. /**
  170. * 从环境变量注册默认账户
  171. */
  172. private async registerFromEnvironment(): Promise<void> {
  173. const exchanges = ['pacifica', 'aster']
  174. for (const exchange of exchanges) {
  175. try {
  176. const result = await AdapterFactory.createFromEnv(exchange as any)
  177. const adapter = result.adapter
  178. // 注册到健康检查系统
  179. this.healthChecker.registerExchange(exchange, adapter as any)
  180. this.logger.info(
  181. `✅ ${exchange.toUpperCase()} 交易所适配器已注册`,
  182. {
  183. exchange,
  184. source: 'environment',
  185. },
  186. 'EXCHANGE',
  187. )
  188. } catch (error: any) {
  189. this.logger.warn(
  190. `⚠️ ${exchange.toUpperCase()} 交易所初始化失败`,
  191. {
  192. exchange,
  193. error: error.message,
  194. source: 'environment',
  195. },
  196. 'EXCHANGE',
  197. )
  198. }
  199. }
  200. }
  201. /**
  202. * 设置配置文件监听
  203. */
  204. private setupConfigWatching(): void {
  205. if (!this.configLoader) return
  206. this.configLoader.on('config_changed', async (newConfig, oldConfig) => {
  207. this.logger.info(
  208. '📄 检测到配置文件更新',
  209. {
  210. newAccounts: newConfig.accounts.length,
  211. oldAccounts: oldConfig?.accounts.length || 0,
  212. },
  213. 'CONFIG',
  214. )
  215. try {
  216. // 重新加载账户配置 (简化实现)
  217. const enabledAccounts = this.configLoader!.getEnabledAccounts()
  218. const accountConfigs = this.configLoader!.convertToAccountConfigs(enabledAccounts)
  219. this.logger.info(
  220. '🔄 应用新的账户配置...',
  221. {
  222. accounts: accountConfigs.length,
  223. },
  224. 'CONFIG',
  225. )
  226. // 实际环境中这里会做更复杂的差异对比和增量更新
  227. } catch (error: any) {
  228. this.logger.error('❌ 配置文件热更新失败', error, {}, 'CONFIG')
  229. }
  230. })
  231. this.configLoader.on('config_error', error => {
  232. this.logger.error('❌ 配置文件监听错误', error, {}, 'CONFIG')
  233. })
  234. this.configLoader.startWatching()
  235. this.logger.info('👁️ 配置文件热更新监听已启用', {}, 'CONFIG')
  236. }
  237. /**
  238. * 设置账户监控
  239. */
  240. private setupAccountMonitoring(): void {
  241. if (!this.accountManager) return
  242. // 监听账户事件
  243. this.accountManager.on('account_registered', data => {
  244. this.logger.account('账户注册成功', {
  245. exchange: data.exchange,
  246. accountId: data.accountId,
  247. })
  248. })
  249. this.accountManager.on('balance_update', data => {
  250. this.logger.account('余额更新', {
  251. exchange: data.exchange,
  252. accountId: data.accountId,
  253. balances: data.balances,
  254. })
  255. })
  256. this.accountManager.on('position_update', data => {
  257. this.logger.account('仓位更新', {
  258. exchange: data.exchange,
  259. accountId: data.accountId,
  260. positions: data.positions,
  261. })
  262. // 计算全局 Delta (简化版本)
  263. this.calculateAndLogGlobalDelta(data)
  264. })
  265. }
  266. /**
  267. * 计算并记录全局 Delta
  268. */
  269. private calculateAndLogGlobalDelta(data: any): void {
  270. try {
  271. // 这里应该实现真正的 Delta 计算逻辑
  272. // 暂时使用简化版本
  273. const totalValue =
  274. data.positions?.reduce((sum: number, pos: any) => {
  275. return sum + parseFloat(pos.notional || '0')
  276. }, 0) || 0
  277. this.logger.performance('GlobalDelta', Math.abs(totalValue), {
  278. exchange: data.exchange,
  279. accountId: data.accountId,
  280. positionCount: data.positions?.length || 0,
  281. category: 'delta_neutral',
  282. })
  283. // 如果 Delta 超过阈值,记录警告
  284. const deltaThreshold = parseFloat(process.env.DELTA_THRESHOLD || '100')
  285. if (Math.abs(totalValue) > deltaThreshold) {
  286. this.logger.warn(
  287. '⚠️ 全局Delta超出阈值',
  288. {
  289. currentDelta: totalValue,
  290. threshold: deltaThreshold,
  291. exchange: data.exchange,
  292. },
  293. 'RISK',
  294. )
  295. }
  296. } catch (error: any) {
  297. this.logger.error('Delta计算失败', error, {}, 'CALCULATION')
  298. }
  299. }
  300. /**
  301. * 设置健康检查事件监听
  302. */
  303. private setupHealthEventListeners(): void {
  304. this.healthChecker.on('system_unhealthy', health => {
  305. this.logger.critical(
  306. '🚨 系统不健康',
  307. {
  308. status: health.status,
  309. exchanges: Object.keys(health.exchanges),
  310. accounts: Object.keys(health.accounts),
  311. errors: health.errors.total,
  312. },
  313. 'HEALTH',
  314. )
  315. })
  316. this.healthChecker.on('exchange_disconnected', data => {
  317. this.logger.error(
  318. '🔌 交易所连接断开',
  319. {
  320. exchange: data.exchange,
  321. },
  322. 'EXCHANGE',
  323. )
  324. })
  325. this.healthChecker.on('exchange_connected', data => {
  326. this.logger.info(
  327. '✅ 交易所重新连接',
  328. {
  329. exchange: data.exchange,
  330. },
  331. 'EXCHANGE',
  332. )
  333. })
  334. }
  335. /**
  336. * 设置信号处理器 - 优雅关闭
  337. */
  338. private setupSignalHandlers(): void {
  339. const signals = ['SIGTERM', 'SIGINT', 'SIGUSR2'] // SIGUSR2 是 PM2 重启信号
  340. signals.forEach(signal => {
  341. process.on(signal, async () => {
  342. if (this.isShuttingDown) return
  343. this.logger.info(`📡 接收到 ${signal} 信号,开始优雅关闭...`, {}, 'SHUTDOWN')
  344. await this.gracefulShutdown()
  345. })
  346. })
  347. // 处理未捕获的错误
  348. process.on('uncaughtException', error => {
  349. this.logger.critical('💥 未捕获异常', error, {}, 'ERROR')
  350. this.gracefulShutdown().then(() => process.exit(1))
  351. })
  352. process.on('unhandledRejection', (reason, promise) => {
  353. this.logger.critical(
  354. '💥 未处理的Promise拒绝',
  355. reason as Error,
  356. {
  357. promise: promise.toString(),
  358. },
  359. 'ERROR',
  360. )
  361. })
  362. }
  363. /**
  364. * 优雅关闭系统
  365. */
  366. private async gracefulShutdown(): Promise<void> {
  367. if (this.isShuttingDown) return
  368. this.isShuttingDown = true
  369. try {
  370. this.logger.info('🛑 开始系统优雅关闭...', {}, 'SHUTDOWN')
  371. // 停止配置文件监听
  372. if (this.configLoader) {
  373. this.configLoader.stopWatching()
  374. this.logger.info('✅ 配置文件监听已停止', {}, 'SHUTDOWN')
  375. }
  376. // 关闭健康检查 API
  377. if (this.healthAPI) {
  378. await this.healthAPI.stop()
  379. this.logger.info('✅ 健康检查API已关闭', {}, 'SHUTDOWN')
  380. }
  381. // 关闭账户管理器连接
  382. if (this.accountManager) {
  383. // 这里应该添加账户管理器的清理逻辑
  384. this.logger.info('✅ 账户管理器已清理', {}, 'SHUTDOWN')
  385. }
  386. // 关闭日志系统
  387. this.logger.info('✅ 对冲交易系统优雅关闭完成', {}, 'SHUTDOWN')
  388. this.logger.close()
  389. process.exit(0)
  390. } catch (error: any) {
  391. console.error('关闭过程中发生错误:', error)
  392. process.exit(1)
  393. }
  394. }
  395. }
  396. // 启动系统
  397. if (import.meta.url === `file://${process.argv[1]}`) {
  398. const system = new HedgeTradingSystem()
  399. system.start().catch(console.error)
  400. }