unified_hedge_demo.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /**
  2. * 统一对冲执行器演示
  3. * 展示如何使用新的基于适配器的对冲系统
  4. */
  5. import 'dotenv/config'
  6. import { AdapterFactory } from '../src/exchanges/AdapterFactory'
  7. import { UnifiedHedgingExecutor } from '../src/core/hedging/UnifiedHedgingExecutor'
  8. import { PrecisionValidator } from '../src/utils/precision'
  9. import { HedgeRequest } from '../src/core/hedging/types'
  10. async function main() {
  11. console.log('🚀 统一对冲执行器演示')
  12. try {
  13. // 1. 创建适配器实例
  14. console.log('\n📡 创建交易所适配器...')
  15. const binanceResult = await AdapterFactory.createFromEnv('binance')
  16. const pacificaResult = await AdapterFactory.createFromEnv('pacifica', 'demo-account')
  17. console.log(`✅ Binance 适配器: ${binanceResult.initialized ? '已初始化' : '初始化失败'}`)
  18. console.log(`✅ Pacifica 适配器: ${pacificaResult.initialized ? '已初始化' : '初始化失败'}`)
  19. // 2. 配置执行器
  20. const executor = new UnifiedHedgingExecutor({
  21. maxRetries: 3,
  22. timeoutMs: 30000,
  23. atomicTimeout: 5000,
  24. enableRollback: true,
  25. slippageTolerance: 0.005,
  26. positionSizeLimit: 1000, // $1000 限制
  27. })
  28. // 监听执行事件
  29. executor.on('execution_started', exec => {
  30. console.log(`🎬 开始执行: ${exec.id}`)
  31. })
  32. executor.on('execution_completed', exec => {
  33. console.log(`✅ 执行完成: ${exec.id}, 用时: ${exec.executionLatency}ms`)
  34. })
  35. executor.on('execution_failed', exec => {
  36. console.log(`❌ 执行失败: ${exec.id}, 错误: ${exec.error?.message}`)
  37. })
  38. executor.on('net_exposure_updated', ({ symbol, previous, current }) => {
  39. console.log(`📊 净敞口更新: ${symbol} ${previous} -> ${current}`)
  40. })
  41. // 3. 获取符号信息并更新精度配置
  42. console.log('\n🔍 获取交易所符号信息...')
  43. const binanceSymbols = await binanceResult.adapter.symbols()
  44. console.log(`📋 Binance 符号数量: ${binanceSymbols.length}`)
  45. // 模拟精度配置 (实际应从交易所获取)
  46. const mockPrecisionConfig = [
  47. {
  48. symbol: 'BTCUSDT',
  49. status: 'TRADING',
  50. baseAsset: 'BTC',
  51. quoteAsset: 'USDT',
  52. precision: {
  53. tickSize: '0.01',
  54. stepSize: '0.00001',
  55. minQty: '0.00001',
  56. maxQty: '1000',
  57. minNotional: '10',
  58. precision: 5,
  59. },
  60. },
  61. ]
  62. PrecisionValidator.updateExchangeConfig('binance', mockPrecisionConfig)
  63. console.log('✅ 精度配置已更新')
  64. // 4. 准备模拟对冲请求
  65. console.log('\n📊 准备对冲请求...')
  66. const hedgeRequest: HedgeRequest = {
  67. symbol: 'BTCUSDT',
  68. perpPosition: {
  69. symbol: 'BTCUSDT',
  70. size: 0.1,
  71. side: 'long',
  72. entryPrice: 50000,
  73. unrealizedPnl: 100,
  74. isOpen: true,
  75. } as any,
  76. prices: {
  77. perpPrice: 51000,
  78. hedgePrice: 50900,
  79. correlation: 0.98,
  80. },
  81. funding: {
  82. fundingRate: 0.0001, // 0.01% 资金费率
  83. },
  84. config: {
  85. preferredMethod: 'spot',
  86. thresholds: {
  87. maxSlippage: 0.005,
  88. deltaDeviationPct: 0.02,
  89. minFundingRate: 0.00005,
  90. minNotionalUSD: 10,
  91. },
  92. },
  93. }
  94. // 5. 执行演示 (使用模拟模式)
  95. console.log('\n🎯 执行对冲演示 (模拟模式)...')
  96. const adapterPair = {
  97. primary: binanceResult.adapter,
  98. primaryId: 'binance',
  99. }
  100. try {
  101. // 注意:这是演示代码,实际执行会尝试下单
  102. // 在生产环境中请确保有足够的资金和正确的配置
  103. console.log('⚠️ 演示模式:不会执行真实交易')
  104. // 验证订单参数
  105. const mockPrice = '51000'
  106. const mockQuantity = '0.001'
  107. const validation = PrecisionValidator.adjustOrderParams('binance', 'BTCUSDT', mockPrice, mockQuantity)
  108. console.log(`🔧 订单参数调整结果:`)
  109. console.log(` 价格: ${mockPrice} -> ${validation.price}`)
  110. console.log(` 数量: ${mockQuantity} -> ${validation.quantity}`)
  111. console.log(` 有效: ${validation.valid}`)
  112. console.log(` 警告: ${validation.warnings.join(', ')}`)
  113. // 如果在真实环境中,这里会执行:
  114. // const result = await executor.execute(hedgeRequest, adapterPair);
  115. } catch (error) {
  116. console.error('❌ 执行失败:', error)
  117. }
  118. // 6. 显示执行统计
  119. console.log('\n📈 执行统计:')
  120. const stats = executor.getExecutionStats()
  121. console.log(`总执行次数: ${stats.totalExecutions}`)
  122. console.log(`成功率: ${(stats.successRate * 100).toFixed(2)}%`)
  123. console.log(`平均延迟: ${stats.averageLatency.toFixed(2)}ms`)
  124. // 7. 健康检查
  125. console.log('\n🏥 适配器健康检查...')
  126. const healthCheck = await AdapterFactory.healthCheck()
  127. for (const [adapter, healthy] of Object.entries(healthCheck)) {
  128. console.log(`${healthy ? '✅' : '❌'} ${adapter}: ${healthy ? '健康' : '不健康'}`)
  129. }
  130. console.log('\n🎉 演示完成')
  131. } catch (error) {
  132. console.error('❌ 演示失败:', error)
  133. }
  134. }
  135. // 运行演示
  136. if (require.main === module) {
  137. main().catch(console.error)
  138. }