test_optimized_pricing.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #!/usr/bin/env npx tsx
  2. import { OptimizedLimitOrderPricingStrategy } from './src/modules/trading/OptimizedLimitOrderPricingStrategy.js'
  3. import { PacificaProxyClient } from './src/exchanges/pacifica/PacificaProxyClient.js'
  4. import { logger } from './src/utils/logger.js'
  5. /**
  6. * 测试优化的限价单定价策略
  7. */
  8. async function testOptimizedPricing() {
  9. console.log('🎯 开始测试优化的限价单定价策略')
  10. console.log('=' * 60)
  11. try {
  12. // 1. 创建 Pacifica 客户端
  13. const client = new PacificaProxyClient({
  14. privateKey: process.env.PACIFICA_PRIVATE_KEY_1 || '',
  15. account: process.env.PACIFICA_ACCOUNT_1 || '3v2fE8y6uPVu5pmNCpmygpGNgdP3kGL3SMoVa86uvLLu',
  16. })
  17. // 禁用WebSocket,使用HTTP
  18. client.setWebSocketEnabled(false)
  19. // 2. 创建优化定价策略实例(多种配置用于对比)
  20. const strategies = {
  21. conservative: new OptimizedLimitOrderPricingStrategy({
  22. targetFillProbability: 0.9, // 保守策略:90%成交率
  23. aggressiveness: 0.3, // 低激进度
  24. minProfitMargin: 0.002, // 较高盈利要求
  25. }),
  26. balanced: new OptimizedLimitOrderPricingStrategy({
  27. targetFillProbability: 0.75, // 平衡策略:75%成交率
  28. aggressiveness: 0.6, // 中等激进度
  29. minProfitMargin: 0.001, // 中等盈利要求
  30. }),
  31. aggressive: new OptimizedLimitOrderPricingStrategy({
  32. targetFillProbability: 0.6, // 激进策略:60%成交率
  33. aggressiveness: 0.8, // 高激进度
  34. minProfitMargin: 0.0005, // 较低盈利要求
  35. })
  36. }
  37. console.log('📊 测试三种不同的定价策略配置:')
  38. console.log(' • 保守策略: 高成交率(90%) + 低激进度(30%) + 高盈利要求(0.2%)')
  39. console.log(' • 平衡策略: 中成交率(75%) + 中激进度(60%) + 中盈利要求(0.1%)')
  40. console.log(' • 激进策略: 低成交率(60%) + 高激进度(80%) + 低盈利要求(0.05%)')
  41. console.log()
  42. // 3. 测试不同订单大小
  43. const testAmounts = [0.0001, 0.0005, 0.001] // BTC
  44. const symbol = 'BTC'
  45. for (const amount of testAmounts) {
  46. console.log(`\n📏 测试订单大小: ${amount} BTC`)
  47. console.log('-'.repeat(50))
  48. for (const [strategyName, strategy] of Object.entries(strategies)) {
  49. try {
  50. console.log(`\n🎯 ${strategyName.toUpperCase()} 策略:`)
  51. const pricing = await strategy.calculateOptimizedPricing(client, symbol, amount)
  52. if (pricing) {
  53. const spread = ((pricing.sellPrice - pricing.buyPrice) / pricing.midPrice * 100).toFixed(3)
  54. const potentialProfit = (pricing.sellPrice - pricing.buyPrice) * amount
  55. console.log(` 💰 买单价格: $${pricing.buyPrice.toFixed(2)}`)
  56. console.log(` 💰 卖单价格: $${pricing.sellPrice.toFixed(2)}`)
  57. console.log(` 📊 中位价格: $${pricing.midPrice.toFixed(2)}`)
  58. console.log(` 📈 价差: ${spread}%`)
  59. console.log(` 🎯 成交概率: ${(pricing.confidence * 100).toFixed(1)}%`)
  60. console.log(` ⏱️ 预期成交时间: ${pricing.expectedFillTime}秒`)
  61. console.log(` 💵 预期盈利: $${potentialProfit.toFixed(4)}`)
  62. console.log(` 📝 策略说明: ${pricing.reasoning}`)
  63. // 与传统定价比较
  64. const traditionalBuyPrice = pricing.midPrice * 0.999 // 传统: 中位价-0.1%
  65. const traditionalSellPrice = pricing.midPrice * 1.001 // 传统: 中位价+0.1%
  66. const traditionalProfit = (traditionalSellPrice - traditionalBuyPrice) * amount
  67. const improvement = ((potentialProfit - traditionalProfit) / traditionalProfit * 100).toFixed(1)
  68. console.log(` 🔄 vs传统定价: ${improvement}% 盈利提升`)
  69. } else {
  70. console.log(` ❌ ${strategyName} 策略: 无法获取定价 (市场条件不适合)`)
  71. }
  72. } catch (error: any) {
  73. console.log(` ❌ ${strategyName} 策略测试失败: ${error.message}`)
  74. }
  75. }
  76. }
  77. // 4. 测试策略统计和性能
  78. console.log('\n📈 策略统计和性能分析:')
  79. console.log('=' * 60)
  80. for (const [strategyName, strategy] of Object.entries(strategies)) {
  81. const stats = strategy.getStats()
  82. console.log(`\n📊 ${strategyName.toUpperCase()} 策略统计:`)
  83. console.log(` • 平均价差: ${(stats.averageSpread * 100).toFixed(3)}%`)
  84. console.log(` • 波动率: ${(stats.volatility * 100).toFixed(2)}%`)
  85. console.log(` • 最近价差范围: ${stats.recentSpreads.map(s => (s * 100).toFixed(3)).join('%, ')}%`)
  86. const bestPrices = strategy.getCurrentBestPrices()
  87. if (bestPrices) {
  88. console.log(` • 当前最佳买价: $${bestPrices.bestBid.toFixed(2)}`)
  89. console.log(` • 当前最佳卖价: $${bestPrices.bestAsk.toFixed(2)}`)
  90. console.log(` • 当前价差: ${(bestPrices.spread * 100).toFixed(3)}%`)
  91. }
  92. }
  93. // 5. 实时价格对比演示
  94. console.log('\n🔄 实时价格策略对比 (每5秒更新):')
  95. console.log('=' * 60)
  96. let iterations = 0
  97. const maxIterations = 3 // 运行3次演示
  98. const priceMonitor = setInterval(async () => {
  99. iterations++
  100. if (iterations > maxIterations) {
  101. clearInterval(priceMonitor)
  102. console.log('\n✅ 优化定价策略测试完成!')
  103. console.log('\n📋 总结:')
  104. console.log(' • 智能定价策略可根据实时市场条件动态调整价格')
  105. console.log(' • 平衡成交概率和盈利margin,提高整体交易效率')
  106. console.log(' • 不同策略配置适合不同的市场环境和风险偏好')
  107. console.log(' • 相比固定价差策略,智能定价能显著提升成交率')
  108. process.exit(0)
  109. return
  110. }
  111. console.log(`\n🕐 实时监控 #${iterations}:`)
  112. try {
  113. const balancedPricing = await strategies.balanced.calculateOptimizedPricing(client, symbol, 0.0001)
  114. if (balancedPricing) {
  115. console.log(` 时间: ${new Date().toLocaleTimeString()}`)
  116. console.log(` 最优买价: $${balancedPricing.buyPrice.toFixed(2)} | 最优卖价: $${balancedPricing.sellPrice.toFixed(2)}`)
  117. console.log(` 成交概率: ${(balancedPricing.confidence * 100).toFixed(1)}% | 预期时间: ${balancedPricing.expectedFillTime}s`)
  118. }
  119. } catch (error: any) {
  120. console.log(` ⚠️ 实时监控 #${iterations} 失败: ${error.message}`)
  121. }
  122. }, 5000)
  123. } catch (error: any) {
  124. console.error('❌ 测试失败:', error.message)
  125. console.error(error.stack)
  126. }
  127. }
  128. // 运行测试
  129. testOptimizedPricing().catch(error => {
  130. console.error('🚨 测试脚本执行失败:', error)
  131. process.exit(1)
  132. })