| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- import { BidirectionalProfitMakingStrategy } from '../modules/trading/BidirectionalProfitMakingStrategy.js'
- import { SuccessRateMonitor } from '../modules/trading/SuccessRateMonitor.js'
- import { PacificaProxyClient } from '../exchanges/pacifica/PacificaProxyClient.js'
- import { logger } from '../utils/logger.js'
- /**
- * 双向盈利挂单策略演示
- *
- * 这个示例展示如何使用双向盈利挂单策略来进行智能刷量交易
- * 并实时监控挂单成功率和盈利情况
- */
- class BidirectionalProfitTradingDemo {
- private strategy!: BidirectionalProfitMakingStrategy
- private monitor!: SuccessRateMonitor
- private clients = new Map<string, PacificaProxyClient>()
- async initialize(): Promise<void> {
- console.log('🚀 初始化双向盈利挂单策略演示...')
- // 设置账户客户端
- await this.setupClients()
- // 创建策略实例
- this.createStrategy()
- // 创建监控器
- this.createMonitor()
- // 设置信号处理
- this.setupSignalHandlers()
- console.log('✅ 初始化完成')
- }
- /**
- * 设置账户客户端
- */
- private async setupClients(): Promise<void> {
- const accounts = [
- {
- id: 'pacifica-1',
- account: process.env.PACIFICA_ACCOUNT_1 || '',
- privateKey: process.env.PACIFICA_PRIVATE_KEY_1 || '',
- },
- {
- id: 'pacifica-2',
- account: process.env.PACIFICA_ACCOUNT_2 || '',
- privateKey: process.env.PACIFICA_PRIVATE_KEY_2 || '',
- }
- ]
- for (const account of accounts) {
- if (!account.account || !account.privateKey) {
- console.log(`⚠️ 账户 ${account.id} 配置不完整,跳过`)
- continue
- }
- try {
- const client = new PacificaProxyClient({
- privateKey: account.privateKey,
- account: account.account,
- })
- this.clients.set(account.id, client)
- console.log(`✅ 账户客户端 ${account.id} 创建成功`)
- } catch (error: any) {
- console.error(`❌ 创建账户客户端 ${account.id} 失败:`, error.message)
- }
- }
- if (this.clients.size < 2) {
- throw new Error('需要至少2个有效账户来运行双向策略')
- }
- }
- /**
- * 创建策略实例
- */
- private createStrategy(): void {
- const config = {
- enabled: true,
- profitMargin: 0.002, // 0.2% 盈利margin
- orderTimeout: 45, // 45秒超时
- maxActiveOrders: 6, // 最大6个活跃订单
- orderAmount: 0.0001, // 0.0001 BTC per order
- spreadThreshold: 0.001, // 0.1% 最小价差
- volatilityLimit: 0.04, // 4% 波动率限制
- minProfitAmount: 0.001, // 临时降低到0.001 USDT用于测试
- }
- // 准备账户配置
- const accountConfigs = new Map<string, { account: string; privateKey: string }>()
- // 添加已配置的账户
- if (process.env.PACIFICA_ACCOUNT_1 && process.env.PACIFICA_PRIVATE_KEY_1) {
- accountConfigs.set('pacifica-1', {
- account: process.env.PACIFICA_ACCOUNT_1,
- privateKey: process.env.PACIFICA_PRIVATE_KEY_1
- })
- }
- if (process.env.PACIFICA_ACCOUNT_2 && process.env.PACIFICA_PRIVATE_KEY_2) {
- accountConfigs.set('pacifica-2', {
- account: process.env.PACIFICA_ACCOUNT_2,
- privateKey: process.env.PACIFICA_PRIVATE_KEY_2
- })
- }
- this.strategy = new BidirectionalProfitMakingStrategy(this.clients, config, accountConfigs)
- console.log('📊 双向盈利策略配置:', config)
- console.log(`📋 已配置 ${accountConfigs.size} 个账户`)
- }
- /**
- * 创建监控器
- */
- private createMonitor(): void {
- this.monitor = new SuccessRateMonitor(this.strategy)
- // 监听关键事件
- this.monitor.on('alert', (message: string) => {
- console.log(`🚨 警报: ${message}`)
- })
- }
- /**
- * 设置信号处理
- */
- private setupSignalHandlers(): void {
- // 优雅关闭
- process.on('SIGINT', async () => {
- console.log('\n📡 收到停止信号,正在优雅关闭...')
- await this.stop()
- process.exit(0)
- })
- process.on('SIGTERM', async () => {
- console.log('\n📡 收到终止信号,正在优雅关闭...')
- await this.stop()
- process.exit(0)
- })
- }
- /**
- * 启动演示
- */
- async start(): Promise<void> {
- console.log('\n🎯 启动双向盈利挂单策略演示')
- console.log('─'.repeat(60))
- try {
- // 启动策略
- this.strategy.start()
- // 启动监控
- this.monitor.start()
- // 定期显示摘要
- setInterval(() => {
- const summary = this.monitor.generateSummaryReport()
- logger.info(`策略摘要: ${summary}`)
- }, 30000) // 每30秒
- console.log('✅ 双向盈利策略已启动')
- console.log('💡 系统将自动执行双向挂单并监控成功率')
- console.log('📊 实时统计将每10秒更新一次')
- console.log('\n按 Ctrl+C 停止策略')
- } catch (error: any) {
- console.error('❌ 启动失败:', error.message)
- throw error
- }
- }
- /**
- * 停止演示
- */
- async stop(): Promise<void> {
- console.log('\n🛑 停止双向盈利策略...')
- try {
- // 停止策略
- if (this.strategy) {
- this.strategy.stop()
- }
- // 停止监控
- if (this.monitor) {
- this.monitor.stop()
- }
- // 显示最终报告
- await this.generateFinalReport()
- console.log('✅ 策略已安全停止')
- } catch (error: any) {
- console.error('❌ 停止时出错:', error.message)
- }
- }
- /**
- * 生成最终报告
- */
- private async generateFinalReport(): Promise<void> {
- if (!this.strategy) return
- const report = this.strategy.getDetailedReport()
- const stats = report.stats
- console.log('\n╔══════════════════════════════════════════════════════════════════════════════╗')
- console.log('║ 📊 最终报告 ║')
- console.log('╚══════════════════════════════════════════════════════════════════════════════╝')
- console.log('\n📈 总体统计:')
- console.log(` ▶ 总订单数: ${stats.totalOrders}`)
- console.log(` ▶ 成交订单: ${stats.filledOrders} (${(stats.successRate * 100).toFixed(1)}%)`)
- console.log(` ▶ 取消订单: ${stats.cancelledOrders}`)
- console.log(` ▶ 超时订单: ${stats.timeoutOrders}`)
- console.log('\n💰 盈利统计:')
- console.log(` ▶ 总盈利: $${stats.totalProfit.toFixed(4)}`)
- console.log(` ▶ 盈利率: ${(stats.profitRate * 100).toFixed(1)}%`)
- console.log(` ▶ 平均成交时间: ${(stats.averageFillTime / 1000).toFixed(1)}秒`)
- console.log('\n🎯 性能指标:')
- const efficiency = stats.totalOrders > 0 ? ((stats.filledOrders + stats.cancelledOrders + stats.timeoutOrders) / stats.totalOrders * 100) : 0
- const avgProfit = stats.filledOrders > 0 ? (stats.totalProfit / stats.filledOrders) : 0
- console.log(` ▶ 执行效率: ${efficiency.toFixed(1)}%`)
- console.log(` ▶ 单笔平均盈利: $${avgProfit.toFixed(4)}`)
- console.log('\n💡 策略建议:')
- this.generateStrategyRecommendations(stats)
- }
- /**
- * 生成策略建议
- */
- private generateStrategyRecommendations(stats: any): void {
- const recommendations: string[] = []
- // 基于成功率的建议
- if (stats.successRate < 0.5) {
- recommendations.push(' • 成功率偏低,建议减少价格偏移或增加超时时间')
- } else if (stats.successRate > 0.9) {
- recommendations.push(' • 成功率很高,可以尝试增加盈利margin获得更多收益')
- }
- // 基于盈利的建议
- if (stats.totalProfit < 0) {
- recommendations.push(' • 总体亏损,建议调整盈利margin或暂停策略优化参数')
- } else if (stats.profitRate < 0.6) {
- recommendations.push(' • 盈利率偏低,建议提高最小盈利阈值')
- }
- // 基于超时的建议
- if (stats.timeoutOrders / Math.max(stats.totalOrders, 1) > 0.3) {
- recommendations.push(' • 超时订单较多,建议增加超时时间或减少价格偏移')
- }
- // 输出建议
- if (recommendations.length > 0) {
- recommendations.forEach(rec => console.log(rec))
- } else {
- console.log(' • 策略运行良好,继续保持当前参数')
- }
- }
- /**
- * 动态调整策略 (可选功能)
- */
- adjustStrategy(): void {
- const stats = this.strategy.getStats()
- // 基于统计数据动态调整参数
- let adjustments: any = {}
- if (stats.successRate < 0.6) {
- // 成功率低,增加超时时间,减少价格偏移
- adjustments.orderTimeout = Math.min(120, 60)
- adjustments.profitMargin = Math.max(0.001, 0.0015)
- console.log('📊 自动调整: 降低要求以提高成功率')
- } else if (stats.successRate > 0.9 && stats.totalProfit > 1) {
- // 成功率高且有盈利,可以提高要求
- adjustments.profitMargin = Math.min(0.005, 0.0025)
- console.log('📊 自动调整: 提高盈利要求')
- }
- if (Object.keys(adjustments).length > 0) {
- this.strategy.adjustStrategy(adjustments)
- }
- }
- }
- /**
- * 主函数
- */
- async function main(): Promise<void> {
- const demo = new BidirectionalProfitTradingDemo()
- try {
- await demo.initialize()
- await demo.start()
- // 演示自动调整 (可选)
- setInterval(() => {
- demo.adjustStrategy()
- }, 300000) // 每5分钟检查一次
- } catch (error: any) {
- console.error('❌ 演示失败:', error.message)
- process.exit(1)
- }
- }
- // 检查是否直接运行此文件
- if (import.meta.url === `file://${process.argv[1]}`) {
- console.log('🎯 双向盈利挂单策略演示')
- console.log('─'.repeat(40))
- console.log('这个演示将展示如何使用挂单策略进行盈利刷量')
- console.log('请确保你已经配置了正确的环境变量')
- console.log()
- main().catch(error => {
- console.error('🚨 演示运行失败:', error)
- process.exit(1)
- })
- }
- export { BidirectionalProfitTradingDemo }
|