optimizedHedgingSystem.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import { EventEmitter } from 'events'
  2. import { logger } from '../../utils/logger.js'
  3. import { PacificaProxyClient } from '../../exchanges/pacifica/PacificaProxyClient.js'
  4. import { SamePlatformHedgingManager } from './SamePlatformHedgingManager.js'
  5. /**
  6. * 优化的统一对冲系统
  7. * 整合基差管理、价格收敛、止盈止损等功能到现有架构中
  8. */
  9. export class OptimizedHedgingSystem extends EventEmitter {
  10. private platformManager: SamePlatformHedgingManager
  11. private dataCache: Map<string, CacheEntry> = new Map()
  12. private config: OptimizedConfig
  13. private mainInterval?: NodeJS.Timeout
  14. private cycleCount: number = 0
  15. // 整合的状态管理
  16. private accountStates: Map<string, EnhancedAccountState> = new Map()
  17. private basisData: Map<string, BasisDataPoint[]> = new Map()
  18. private performanceMetrics: PerformanceMetrics
  19. constructor(config?: Partial<OptimizedConfig>) {
  20. super()
  21. this.config = {
  22. mainCycleIntervalMs: config?.mainCycleIntervalMs || 5000, // 统一5秒间隔
  23. cacheTimeoutMs: config?.cacheTimeoutMs || 2000, // 2秒缓存
  24. basisConfig: {
  25. maxDeviation: config?.basisConfig?.maxDeviation || 200,
  26. alertThreshold: config?.basisConfig?.alertThreshold || 100,
  27. historyRetentionHours: config?.basisConfig?.historyRetentionHours || 24,
  28. },
  29. convergenceConfig: {
  30. maxPriceDeviation: config?.convergenceConfig?.maxPriceDeviation || 0.005,
  31. convergenceStepPercent: config?.convergenceConfig?.convergenceStepPercent || 0.001,
  32. maxDailyAdjustments: config?.convergenceConfig?.maxDailyAdjustments || 20,
  33. },
  34. stopLossConfig: {
  35. defaultStopLoss: config?.stopLossConfig?.defaultStopLoss || 0.015,
  36. defaultTakeProfit: config?.stopLossConfig?.defaultTakeProfit || 0.025,
  37. enableTrailing: config?.stopLossConfig?.enableTrailing || true,
  38. },
  39. riskLimits: {
  40. maxPositionSize: config?.riskLimits?.maxPositionSize || 0.01,
  41. maxTotalExposure: config?.riskLimits?.maxTotalExposure || 0.05,
  42. emergencyStopThreshold: config?.riskLimits?.emergencyStopThreshold || -0.03,
  43. ...config?.riskLimits,
  44. },
  45. }
  46. this.platformManager = new SamePlatformHedgingManager('pacifica', this.config.riskLimits)
  47. this.performanceMetrics = this.initializeMetrics()
  48. }
  49. /**
  50. * 启动优化的对冲系统
  51. */
  52. async start(): Promise<void> {
  53. logger.info('启动优化对冲系统')
  54. // 单一主循环定时器
  55. this.mainInterval = setInterval(() => {
  56. this.executeMainCycle()
  57. }, this.config.mainCycleIntervalMs)
  58. logger.info('优化对冲系统已启动', {
  59. interval: this.config.mainCycleIntervalMs,
  60. cacheTimeout: this.config.cacheTimeoutMs,
  61. })
  62. this.emit('systemStarted')
  63. }
  64. /**
  65. * 停止系统
  66. */
  67. async stop(): Promise<void> {
  68. if (this.mainInterval) {
  69. clearInterval(this.mainInterval)
  70. this.mainInterval = undefined
  71. }
  72. logger.info('优化对冲系统已停止')
  73. this.emit('systemStopped')
  74. }
  75. /**
  76. * 添加交易对
  77. */
  78. async addTradingPair(
  79. pairId: string,
  80. account1Config: AccountConfig,
  81. account2Config: AccountConfig,
  82. symbol: string,
  83. ): Promise<void> {
  84. // 使用现有平台管理器添加账户
  85. this.platformManager.addAccount(account1Config.account, account1Config)
  86. this.platformManager.addAccount(account2Config.account, account2Config)
  87. this.platformManager.createHedgePair(pairId, account1Config.account, account2Config.account, symbol)
  88. // 初始化增强状态跟踪
  89. this.accountStates.set(account1Config.account, this.createEnhancedAccountState(account1Config.account))
  90. this.accountStates.set(account2Config.account, this.createEnhancedAccountState(account2Config.account))
  91. logger.info('添加交易对到优化系统', { pairId, symbol })
  92. }
  93. /**
  94. * 主执行循环 - 替代多个定时器
  95. */
  96. private async executeMainCycle(): Promise<void> {
  97. try {
  98. this.cycleCount++
  99. // 每个周期都执行的核心功能
  100. await this.updateCachedData()
  101. await this.performIntegratedRiskCheck()
  102. await this.checkAndExecuteStrategies()
  103. // 基于周期数执行不同频率的任务
  104. if (this.cycleCount % 3 === 0) {
  105. // 每15秒:生成交易信号和检查收敛
  106. await this.executeConvergenceCheck()
  107. }
  108. if (this.cycleCount % 6 === 0) {
  109. // 每30秒:基差分析和预警
  110. await this.executeBasisAnalysis()
  111. }
  112. if (this.cycleCount % 12 === 0) {
  113. // 每60秒:系统健康检查和性能统计
  114. await this.performSystemHealthCheck()
  115. await this.updatePerformanceMetrics()
  116. }
  117. // 每100个周期重置计数器
  118. if (this.cycleCount >= 100) {
  119. this.cycleCount = 0
  120. }
  121. } catch (error: any) {
  122. logger.error('主循环执行失败', { error: error.message, cycle: this.cycleCount })
  123. this.emit('systemError', { error, cycle: this.cycleCount })
  124. }
  125. }
  126. /**
  127. * 智能缓存数据更新
  128. */
  129. private async updateCachedData(): Promise<void> {
  130. const tasks = []
  131. // 并行更新所有账户数据
  132. for (const accountId of this.accountStates.keys()) {
  133. tasks.push(this.updateAccountData(accountId))
  134. }
  135. // 更新市场数据
  136. tasks.push(this.updateMarketData())
  137. await Promise.allSettled(tasks)
  138. }
  139. /**
  140. * 更新单个账户数据(带缓存)
  141. */
  142. private async updateAccountData(accountId: string): Promise<void> {
  143. const cacheKey = `account_${accountId}`
  144. const cached = this.getFromCache(cacheKey)
  145. if (cached) {
  146. return cached
  147. }
  148. try {
  149. // 使用平台管理器更新仓位
  150. await this.platformManager.updateAccountPositions(accountId)
  151. // 更新增强状态
  152. const accountState = this.accountStates.get(accountId)
  153. if (accountState) {
  154. // 获取最新仓位和余额信息
  155. accountState.lastUpdate = Date.now()
  156. // 这里可以添加更多状态更新逻辑
  157. }
  158. this.setCache(cacheKey, true)
  159. } catch (error: any) {
  160. logger.warn('更新账户数据失败', { accountId, error: error.message })
  161. }
  162. }
  163. /**
  164. * 更新市场数据(带缓存)
  165. */
  166. private async updateMarketData(): Promise<void> {
  167. const cacheKey = 'market_data'
  168. const cached = this.getFromCache(cacheKey)
  169. if (cached) {
  170. return cached
  171. }
  172. try {
  173. // 获取市场价格数据
  174. // 这里可以调用现有的价格获取逻辑
  175. this.setCache(cacheKey, true)
  176. } catch (error: any) {
  177. logger.warn('更新市场数据失败', { error: error.message })
  178. }
  179. }
  180. /**
  181. * 集成的风险检查
  182. */
  183. private async performIntegratedRiskCheck(): Promise<void> {
  184. try {
  185. // 1. 基础风险检查(复用现有逻辑)
  186. const hedgeStatuses = this.platformManager.getHedgePairStatuses()
  187. // 2. 基差风险检查
  188. const basisRisk = await this.checkBasisRisk()
  189. // 3. 收敛风险检查
  190. const convergenceRisk = await this.checkConvergenceRisk()
  191. // 4. 综合风险评估
  192. const overallRisk = this.calculateOverallRisk(hedgeStatuses, basisRisk, convergenceRisk)
  193. if (overallRisk.level === 'HIGH' || overallRisk.level === 'CRITICAL') {
  194. this.emit('riskAlert', overallRisk)
  195. if (overallRisk.level === 'CRITICAL') {
  196. await this.triggerEmergencyStop()
  197. }
  198. }
  199. } catch (error: any) {
  200. logger.error('集成风险检查失败', { error: error.message })
  201. }
  202. }
  203. /**
  204. * 基差风险检查
  205. */
  206. private async checkBasisRisk(): Promise<BasisRiskAssessment> {
  207. const symbols = this.getMonitoredSymbols()
  208. const riskEvents: BasisRiskEvent[] = []
  209. for (const symbol of symbols) {
  210. const basisHistory = this.basisData.get(symbol) || []
  211. if (basisHistory.length > 0) {
  212. const latest = basisHistory[basisHistory.length - 1]
  213. const basis = Math.abs(latest.basis)
  214. if (basis > this.config.basisConfig.maxDeviation) {
  215. riskEvents.push({
  216. symbol,
  217. basis: latest.basis,
  218. threshold: this.config.basisConfig.maxDeviation,
  219. severity: 'HIGH',
  220. timestamp: Date.now(),
  221. })
  222. } else if (basis > this.config.basisConfig.alertThreshold) {
  223. riskEvents.push({
  224. symbol,
  225. basis: latest.basis,
  226. threshold: this.config.basisConfig.alertThreshold,
  227. severity: 'MEDIUM',
  228. timestamp: Date.now(),
  229. })
  230. }
  231. }
  232. }
  233. return {
  234. overallRisk: riskEvents.length > 0 ? 'HIGH' : 'LOW',
  235. events: riskEvents,
  236. timestamp: Date.now(),
  237. }
  238. }
  239. /**
  240. * 收敛风险检查
  241. */
  242. private async checkConvergenceRisk(): Promise<ConvergenceRiskAssessment> {
  243. const hedgeStatuses = this.platformManager.getHedgePairStatuses()
  244. const riskEvents: ConvergenceRiskEvent[] = []
  245. for (const status of hedgeStatuses) {
  246. const priceDeviation = Math.abs(status.netExposure) // 简化的偏差计算
  247. if (priceDeviation > this.config.convergenceConfig.maxPriceDeviation) {
  248. riskEvents.push({
  249. pairId: status.pairId,
  250. deviation: priceDeviation,
  251. threshold: this.config.convergenceConfig.maxPriceDeviation,
  252. severity: 'HIGH',
  253. timestamp: Date.now(),
  254. })
  255. }
  256. }
  257. return {
  258. overallRisk: riskEvents.length > 0 ? 'HIGH' : 'LOW',
  259. events: riskEvents,
  260. timestamp: Date.now(),
  261. }
  262. }
  263. /**
  264. * 综合风险评估
  265. */
  266. private calculateOverallRisk(
  267. hedgeStatuses: any[],
  268. basisRisk: BasisRiskAssessment,
  269. convergenceRisk: ConvergenceRiskAssessment,
  270. ): OverallRiskAssessment {
  271. let riskScore = 0
  272. const factors: string[] = []
  273. // 基差风险权重 40%
  274. if (basisRisk.overallRisk === 'HIGH') {
  275. riskScore += 40
  276. factors.push(`基差风险高:${basisRisk.events.length}个事件`)
  277. }
  278. // 收敛风险权重 35%
  279. if (convergenceRisk.overallRisk === 'HIGH') {
  280. riskScore += 35
  281. factors.push(`收敛风险高:${convergenceRisk.events.length}个事件`)
  282. }
  283. // 对冲状态风险权重 25%
  284. const inactiveHedges = hedgeStatuses.filter(h => !h.isActive).length
  285. if (inactiveHedges > 0) {
  286. riskScore += 25
  287. factors.push(`${inactiveHedges}个对冲对未激活`)
  288. }
  289. // 确定风险等级
  290. let level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
  291. if (riskScore >= 80) {
  292. level = 'CRITICAL'
  293. } else if (riskScore >= 60) {
  294. level = 'HIGH'
  295. } else if (riskScore >= 30) {
  296. level = 'MEDIUM'
  297. } else {
  298. level = 'LOW'
  299. }
  300. return {
  301. level,
  302. score: riskScore,
  303. factors,
  304. basisRisk,
  305. convergenceRisk,
  306. timestamp: Date.now(),
  307. }
  308. }
  309. /**
  310. * 执行收敛检查
  311. */
  312. private async executeConvergenceCheck(): Promise<void> {
  313. try {
  314. const hedgeStatuses = this.platformManager.getHedgePairStatuses()
  315. for (const status of hedgeStatuses) {
  316. const needsAdjustment = Math.abs(status.netExposure) > this.config.convergenceConfig.maxPriceDeviation
  317. if (needsAdjustment) {
  318. await this.platformManager.rebalanceHedgePair(status.pairId, 0.01)
  319. this.emit('convergenceAdjustment', {
  320. pairId: status.pairId,
  321. netExposure: status.netExposure,
  322. timestamp: Date.now(),
  323. })
  324. }
  325. }
  326. } catch (error: any) {
  327. logger.error('收敛检查失败', { error: error.message })
  328. }
  329. }
  330. /**
  331. * 执行基差分析
  332. */
  333. private async executeBasisAnalysis(): Promise<void> {
  334. try {
  335. const symbols = this.getMonitoredSymbols()
  336. for (const symbol of symbols) {
  337. // 模拟基差数据更新
  338. const spotPrice = await this.getSpotPrice(symbol)
  339. const futuresPrice = await this.getFuturesPrice(symbol)
  340. if (spotPrice && futuresPrice) {
  341. this.updateBasisData(symbol, spotPrice, futuresPrice)
  342. }
  343. }
  344. } catch (error: any) {
  345. logger.error('基差分析失败', { error: error.message })
  346. }
  347. }
  348. /**
  349. * 更新基差数据
  350. */
  351. private updateBasisData(symbol: string, spotPrice: number, futuresPrice: number): void {
  352. if (!this.basisData.has(symbol)) {
  353. this.basisData.set(symbol, [])
  354. }
  355. const history = this.basisData.get(symbol)!
  356. const basis = futuresPrice - spotPrice
  357. const basisPercent = (basis / spotPrice) * 100
  358. const dataPoint: BasisDataPoint = {
  359. spotPrice,
  360. futuresPrice,
  361. basis,
  362. basisPercent,
  363. timestamp: Date.now(),
  364. }
  365. history.push(dataPoint)
  366. // 限制历史数据长度
  367. const maxPoints = (this.config.basisConfig.historyRetentionHours * 3600 * 1000) / this.config.mainCycleIntervalMs
  368. if (history.length > maxPoints) {
  369. history.splice(0, history.length - maxPoints)
  370. }
  371. // 检查是否需要发出基差预警
  372. if (Math.abs(basis) > this.config.basisConfig.alertThreshold) {
  373. this.emit('basisAlert', {
  374. symbol,
  375. basis,
  376. basisPercent,
  377. threshold: this.config.basisConfig.alertThreshold,
  378. timestamp: Date.now(),
  379. })
  380. }
  381. }
  382. /**
  383. * 缓存管理
  384. */
  385. private getFromCache(key: string): any {
  386. const entry = this.dataCache.get(key)
  387. if (entry && Date.now() - entry.timestamp < this.config.cacheTimeoutMs) {
  388. return entry.data
  389. }
  390. return null
  391. }
  392. private setCache(key: string, data: any): void {
  393. this.dataCache.set(key, {
  394. data,
  395. timestamp: Date.now(),
  396. })
  397. }
  398. /**
  399. * 辅助方法
  400. */
  401. private createEnhancedAccountState(accountId: string): EnhancedAccountState {
  402. return {
  403. accountId,
  404. lastUpdate: Date.now(),
  405. convergenceHistory: [],
  406. stopLossOrders: [],
  407. riskScore: 0,
  408. }
  409. }
  410. private initializeMetrics(): PerformanceMetrics {
  411. return {
  412. totalAdjustments: 0,
  413. successfulAdjustments: 0,
  414. basisAlerts: 0,
  415. convergenceEvents: 0,
  416. systemUptime: Date.now(),
  417. }
  418. }
  419. private getMonitoredSymbols(): string[] {
  420. const hedgeStatuses = this.platformManager.getHedgePairStatuses()
  421. return hedgeStatuses.map(status => status.symbol)
  422. }
  423. private async getSpotPrice(symbol: string): Promise<number | null> {
  424. // 实现现货价格获取逻辑
  425. return 50000 // 模拟价格
  426. }
  427. private async getFuturesPrice(symbol: string): Promise<number | null> {
  428. // 实现期货价格获取逻辑
  429. return 50100 // 模拟价格
  430. }
  431. private async performSystemHealthCheck(): Promise<void> {
  432. // 实现系统健康检查
  433. logger.debug('系统健康检查完成')
  434. }
  435. private async updatePerformanceMetrics(): Promise<void> {
  436. // 更新性能指标
  437. this.performanceMetrics.systemUptime = Date.now()
  438. }
  439. private async checkAndExecuteStrategies(): Promise<void> {
  440. // 实现策略检查和执行
  441. }
  442. private async triggerEmergencyStop(): Promise<void> {
  443. logger.warn('触发紧急停止')
  444. await this.stop()
  445. this.emit('emergencyStop', { timestamp: Date.now() })
  446. }
  447. /**
  448. * 获取系统状态
  449. */
  450. getSystemStatus(): OptimizedSystemStatus {
  451. return {
  452. isRunning: !!this.mainInterval,
  453. activePairs: this.platformManager.getHedgePairStatuses().length,
  454. accountCount: this.accountStates.size,
  455. performanceMetrics: this.performanceMetrics,
  456. cacheEntries: this.dataCache.size,
  457. cycleCount: this.cycleCount,
  458. }
  459. }
  460. }
  461. // 类型定义
  462. export interface AccountConfig {
  463. account: string
  464. privateKey: string
  465. agentWallet?: string
  466. agentPrivateKey?: string
  467. }
  468. export interface OptimizedConfig {
  469. mainCycleIntervalMs: number
  470. cacheTimeoutMs: number
  471. basisConfig: {
  472. maxDeviation: number
  473. alertThreshold: number
  474. historyRetentionHours: number
  475. }
  476. convergenceConfig: {
  477. maxPriceDeviation: number
  478. convergenceStepPercent: number
  479. maxDailyAdjustments: number
  480. }
  481. stopLossConfig: {
  482. defaultStopLoss: number
  483. defaultTakeProfit: number
  484. enableTrailing: boolean
  485. }
  486. riskLimits: {
  487. maxPositionSize: number
  488. maxTotalExposure: number
  489. emergencyStopThreshold: number
  490. }
  491. }
  492. export interface CacheEntry {
  493. data: any
  494. timestamp: number
  495. }
  496. export interface EnhancedAccountState {
  497. accountId: string
  498. lastUpdate: number
  499. convergenceHistory: any[]
  500. stopLossOrders: any[]
  501. riskScore: number
  502. }
  503. export interface BasisDataPoint {
  504. spotPrice: number
  505. futuresPrice: number
  506. basis: number
  507. basisPercent: number
  508. timestamp: number
  509. }
  510. export interface BasisRiskEvent {
  511. symbol: string
  512. basis: number
  513. threshold: number
  514. severity: 'LOW' | 'MEDIUM' | 'HIGH'
  515. timestamp: number
  516. }
  517. export interface ConvergenceRiskEvent {
  518. pairId: string
  519. deviation: number
  520. threshold: number
  521. severity: 'LOW' | 'MEDIUM' | 'HIGH'
  522. timestamp: number
  523. }
  524. export interface BasisRiskAssessment {
  525. overallRisk: 'LOW' | 'HIGH'
  526. events: BasisRiskEvent[]
  527. timestamp: number
  528. }
  529. export interface ConvergenceRiskAssessment {
  530. overallRisk: 'LOW' | 'HIGH'
  531. events: ConvergenceRiskEvent[]
  532. timestamp: number
  533. }
  534. export interface OverallRiskAssessment {
  535. level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
  536. score: number
  537. factors: string[]
  538. basisRisk: BasisRiskAssessment
  539. convergenceRisk: ConvergenceRiskAssessment
  540. timestamp: number
  541. }
  542. export interface PerformanceMetrics {
  543. totalAdjustments: number
  544. successfulAdjustments: number
  545. basisAlerts: number
  546. convergenceEvents: number
  547. systemUptime: number
  548. }
  549. export interface OptimizedSystemStatus {
  550. isRunning: boolean
  551. activePairs: number
  552. accountCount: number
  553. performanceMetrics: PerformanceMetrics
  554. cacheEntries: number
  555. cycleCount: number
  556. }