bidirectional_profit_trading_demo.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { BidirectionalProfitMakingStrategy } from '../modules/trading/BidirectionalProfitMakingStrategy.js'
  2. import { SuccessRateMonitor } from '../modules/trading/SuccessRateMonitor.js'
  3. import { PacificaProxyClient } from '../exchanges/pacifica/PacificaProxyClient.js'
  4. import { logger } from '../utils/logger.js'
  5. /**
  6. * 双向盈利挂单策略演示
  7. *
  8. * 这个示例展示如何使用双向盈利挂单策略来进行智能刷量交易
  9. * 并实时监控挂单成功率和盈利情况
  10. */
  11. class BidirectionalProfitTradingDemo {
  12. private strategy!: BidirectionalProfitMakingStrategy
  13. private monitor!: SuccessRateMonitor
  14. private clients = new Map<string, PacificaProxyClient>()
  15. async initialize(): Promise<void> {
  16. console.log('🚀 初始化双向盈利挂单策略演示...')
  17. // 设置账户客户端
  18. await this.setupClients()
  19. // 创建策略实例
  20. this.createStrategy()
  21. // 创建监控器
  22. this.createMonitor()
  23. // 设置信号处理
  24. this.setupSignalHandlers()
  25. console.log('✅ 初始化完成')
  26. }
  27. /**
  28. * 设置账户客户端
  29. */
  30. private async setupClients(): Promise<void> {
  31. const accounts = [
  32. {
  33. id: 'pacifica-1',
  34. account: process.env.PACIFICA_ACCOUNT_1 || '',
  35. privateKey: process.env.PACIFICA_PRIVATE_KEY_1 || '',
  36. },
  37. {
  38. id: 'pacifica-2',
  39. account: process.env.PACIFICA_ACCOUNT_2 || '',
  40. privateKey: process.env.PACIFICA_PRIVATE_KEY_2 || '',
  41. }
  42. ]
  43. for (const account of accounts) {
  44. if (!account.account || !account.privateKey) {
  45. console.log(`⚠️ 账户 ${account.id} 配置不完整,跳过`)
  46. continue
  47. }
  48. try {
  49. const client = new PacificaProxyClient({
  50. privateKey: account.privateKey,
  51. account: account.account,
  52. })
  53. this.clients.set(account.id, client)
  54. console.log(`✅ 账户客户端 ${account.id} 创建成功`)
  55. } catch (error: any) {
  56. console.error(`❌ 创建账户客户端 ${account.id} 失败:`, error.message)
  57. }
  58. }
  59. if (this.clients.size < 2) {
  60. throw new Error('需要至少2个有效账户来运行双向策略')
  61. }
  62. }
  63. /**
  64. * 创建策略实例
  65. */
  66. private createStrategy(): void {
  67. const config = {
  68. enabled: true,
  69. profitMargin: 0.002, // 0.2% 盈利margin
  70. orderTimeout: 45, // 45秒超时
  71. maxActiveOrders: 6, // 最大6个活跃订单
  72. orderAmount: 0.0001, // 0.0001 BTC per order
  73. spreadThreshold: 0.001, // 0.1% 最小价差
  74. volatilityLimit: 0.04, // 4% 波动率限制
  75. minProfitAmount: 0.001, // 临时降低到0.001 USDT用于测试
  76. }
  77. // 准备账户配置
  78. const accountConfigs = new Map<string, { account: string; privateKey: string }>()
  79. // 添加已配置的账户
  80. if (process.env.PACIFICA_ACCOUNT_1 && process.env.PACIFICA_PRIVATE_KEY_1) {
  81. accountConfigs.set('pacifica-1', {
  82. account: process.env.PACIFICA_ACCOUNT_1,
  83. privateKey: process.env.PACIFICA_PRIVATE_KEY_1
  84. })
  85. }
  86. if (process.env.PACIFICA_ACCOUNT_2 && process.env.PACIFICA_PRIVATE_KEY_2) {
  87. accountConfigs.set('pacifica-2', {
  88. account: process.env.PACIFICA_ACCOUNT_2,
  89. privateKey: process.env.PACIFICA_PRIVATE_KEY_2
  90. })
  91. }
  92. this.strategy = new BidirectionalProfitMakingStrategy(this.clients, config, accountConfigs)
  93. console.log('📊 双向盈利策略配置:', config)
  94. console.log(`📋 已配置 ${accountConfigs.size} 个账户`)
  95. }
  96. /**
  97. * 创建监控器
  98. */
  99. private createMonitor(): void {
  100. this.monitor = new SuccessRateMonitor(this.strategy)
  101. // 监听关键事件
  102. this.monitor.on('alert', (message: string) => {
  103. console.log(`🚨 警报: ${message}`)
  104. })
  105. }
  106. /**
  107. * 设置信号处理
  108. */
  109. private setupSignalHandlers(): void {
  110. // 优雅关闭
  111. process.on('SIGINT', async () => {
  112. console.log('\n📡 收到停止信号,正在优雅关闭...')
  113. await this.stop()
  114. process.exit(0)
  115. })
  116. process.on('SIGTERM', async () => {
  117. console.log('\n📡 收到终止信号,正在优雅关闭...')
  118. await this.stop()
  119. process.exit(0)
  120. })
  121. }
  122. /**
  123. * 启动演示
  124. */
  125. async start(): Promise<void> {
  126. console.log('\n🎯 启动双向盈利挂单策略演示')
  127. console.log('─'.repeat(60))
  128. try {
  129. // 启动策略
  130. this.strategy.start()
  131. // 启动监控
  132. this.monitor.start()
  133. // 定期显示摘要
  134. setInterval(() => {
  135. const summary = this.monitor.generateSummaryReport()
  136. logger.info(`策略摘要: ${summary}`)
  137. }, 30000) // 每30秒
  138. console.log('✅ 双向盈利策略已启动')
  139. console.log('💡 系统将自动执行双向挂单并监控成功率')
  140. console.log('📊 实时统计将每10秒更新一次')
  141. console.log('\n按 Ctrl+C 停止策略')
  142. } catch (error: any) {
  143. console.error('❌ 启动失败:', error.message)
  144. throw error
  145. }
  146. }
  147. /**
  148. * 停止演示
  149. */
  150. async stop(): Promise<void> {
  151. console.log('\n🛑 停止双向盈利策略...')
  152. try {
  153. // 停止策略
  154. if (this.strategy) {
  155. this.strategy.stop()
  156. }
  157. // 停止监控
  158. if (this.monitor) {
  159. this.monitor.stop()
  160. }
  161. // 显示最终报告
  162. await this.generateFinalReport()
  163. console.log('✅ 策略已安全停止')
  164. } catch (error: any) {
  165. console.error('❌ 停止时出错:', error.message)
  166. }
  167. }
  168. /**
  169. * 生成最终报告
  170. */
  171. private async generateFinalReport(): Promise<void> {
  172. if (!this.strategy) return
  173. const report = this.strategy.getDetailedReport()
  174. const stats = report.stats
  175. console.log('\n╔══════════════════════════════════════════════════════════════════════════════╗')
  176. console.log('║ 📊 最终报告 ║')
  177. console.log('╚══════════════════════════════════════════════════════════════════════════════╝')
  178. console.log('\n📈 总体统计:')
  179. console.log(` ▶ 总订单数: ${stats.totalOrders}`)
  180. console.log(` ▶ 成交订单: ${stats.filledOrders} (${(stats.successRate * 100).toFixed(1)}%)`)
  181. console.log(` ▶ 取消订单: ${stats.cancelledOrders}`)
  182. console.log(` ▶ 超时订单: ${stats.timeoutOrders}`)
  183. console.log('\n💰 盈利统计:')
  184. console.log(` ▶ 总盈利: $${stats.totalProfit.toFixed(4)}`)
  185. console.log(` ▶ 盈利率: ${(stats.profitRate * 100).toFixed(1)}%`)
  186. console.log(` ▶ 平均成交时间: ${(stats.averageFillTime / 1000).toFixed(1)}秒`)
  187. console.log('\n🎯 性能指标:')
  188. const efficiency = stats.totalOrders > 0 ? ((stats.filledOrders + stats.cancelledOrders + stats.timeoutOrders) / stats.totalOrders * 100) : 0
  189. const avgProfit = stats.filledOrders > 0 ? (stats.totalProfit / stats.filledOrders) : 0
  190. console.log(` ▶ 执行效率: ${efficiency.toFixed(1)}%`)
  191. console.log(` ▶ 单笔平均盈利: $${avgProfit.toFixed(4)}`)
  192. console.log('\n💡 策略建议:')
  193. this.generateStrategyRecommendations(stats)
  194. }
  195. /**
  196. * 生成策略建议
  197. */
  198. private generateStrategyRecommendations(stats: any): void {
  199. const recommendations: string[] = []
  200. // 基于成功率的建议
  201. if (stats.successRate < 0.5) {
  202. recommendations.push(' • 成功率偏低,建议减少价格偏移或增加超时时间')
  203. } else if (stats.successRate > 0.9) {
  204. recommendations.push(' • 成功率很高,可以尝试增加盈利margin获得更多收益')
  205. }
  206. // 基于盈利的建议
  207. if (stats.totalProfit < 0) {
  208. recommendations.push(' • 总体亏损,建议调整盈利margin或暂停策略优化参数')
  209. } else if (stats.profitRate < 0.6) {
  210. recommendations.push(' • 盈利率偏低,建议提高最小盈利阈值')
  211. }
  212. // 基于超时的建议
  213. if (stats.timeoutOrders / Math.max(stats.totalOrders, 1) > 0.3) {
  214. recommendations.push(' • 超时订单较多,建议增加超时时间或减少价格偏移')
  215. }
  216. // 输出建议
  217. if (recommendations.length > 0) {
  218. recommendations.forEach(rec => console.log(rec))
  219. } else {
  220. console.log(' • 策略运行良好,继续保持当前参数')
  221. }
  222. }
  223. /**
  224. * 动态调整策略 (可选功能)
  225. */
  226. adjustStrategy(): void {
  227. const stats = this.strategy.getStats()
  228. // 基于统计数据动态调整参数
  229. let adjustments: any = {}
  230. if (stats.successRate < 0.6) {
  231. // 成功率低,增加超时时间,减少价格偏移
  232. adjustments.orderTimeout = Math.min(120, 60)
  233. adjustments.profitMargin = Math.max(0.001, 0.0015)
  234. console.log('📊 自动调整: 降低要求以提高成功率')
  235. } else if (stats.successRate > 0.9 && stats.totalProfit > 1) {
  236. // 成功率高且有盈利,可以提高要求
  237. adjustments.profitMargin = Math.min(0.005, 0.0025)
  238. console.log('📊 自动调整: 提高盈利要求')
  239. }
  240. if (Object.keys(adjustments).length > 0) {
  241. this.strategy.adjustStrategy(adjustments)
  242. }
  243. }
  244. }
  245. /**
  246. * 主函数
  247. */
  248. async function main(): Promise<void> {
  249. const demo = new BidirectionalProfitTradingDemo()
  250. try {
  251. await demo.initialize()
  252. await demo.start()
  253. // 演示自动调整 (可选)
  254. setInterval(() => {
  255. demo.adjustStrategy()
  256. }, 300000) // 每5分钟检查一次
  257. } catch (error: any) {
  258. console.error('❌ 演示失败:', error.message)
  259. process.exit(1)
  260. }
  261. }
  262. // 检查是否直接运行此文件
  263. if (import.meta.url === `file://${process.argv[1]}`) {
  264. console.log('🎯 双向盈利挂单策略演示')
  265. console.log('─'.repeat(40))
  266. console.log('这个演示将展示如何使用挂单策略进行盈利刷量')
  267. console.log('请确保你已经配置了正确的环境变量')
  268. console.log()
  269. main().catch(error => {
  270. console.error('🚨 演示运行失败:', error)
  271. process.exit(1)
  272. })
  273. }
  274. export { BidirectionalProfitTradingDemo }