/** * 统一对冲执行器演示 * 展示如何使用新的基于适配器的对冲系统 */ import 'dotenv/config' import { AdapterFactory } from '../src/exchanges/AdapterFactory' import { UnifiedHedgingExecutor } from '../src/core/hedging/UnifiedHedgingExecutor' import { PrecisionValidator } from '../src/utils/precision' import { HedgeRequest } from '../src/core/hedging/types' async function main() { console.log('🚀 统一对冲执行器演示') try { // 1. 创建适配器实例 console.log('\n📡 创建交易所适配器...') const binanceResult = await AdapterFactory.createFromEnv('binance') const pacificaResult = await AdapterFactory.createFromEnv('pacifica', 'demo-account') console.log(`✅ Binance 适配器: ${binanceResult.initialized ? '已初始化' : '初始化失败'}`) console.log(`✅ Pacifica 适配器: ${pacificaResult.initialized ? '已初始化' : '初始化失败'}`) // 2. 配置执行器 const executor = new UnifiedHedgingExecutor({ maxRetries: 3, timeoutMs: 30000, atomicTimeout: 5000, enableRollback: true, slippageTolerance: 0.005, positionSizeLimit: 1000, // $1000 限制 }) // 监听执行事件 executor.on('execution_started', exec => { console.log(`🎬 开始执行: ${exec.id}`) }) executor.on('execution_completed', exec => { console.log(`✅ 执行完成: ${exec.id}, 用时: ${exec.executionLatency}ms`) }) executor.on('execution_failed', exec => { console.log(`❌ 执行失败: ${exec.id}, 错误: ${exec.error?.message}`) }) executor.on('net_exposure_updated', ({ symbol, previous, current }) => { console.log(`📊 净敞口更新: ${symbol} ${previous} -> ${current}`) }) // 3. 获取符号信息并更新精度配置 console.log('\n🔍 获取交易所符号信息...') const binanceSymbols = await binanceResult.adapter.symbols() console.log(`📋 Binance 符号数量: ${binanceSymbols.length}`) // 模拟精度配置 (实际应从交易所获取) const mockPrecisionConfig = [ { symbol: 'BTCUSDT', status: 'TRADING', baseAsset: 'BTC', quoteAsset: 'USDT', precision: { tickSize: '0.01', stepSize: '0.00001', minQty: '0.00001', maxQty: '1000', minNotional: '10', precision: 5, }, }, ] PrecisionValidator.updateExchangeConfig('binance', mockPrecisionConfig) console.log('✅ 精度配置已更新') // 4. 准备模拟对冲请求 console.log('\n📊 准备对冲请求...') const hedgeRequest: HedgeRequest = { symbol: 'BTCUSDT', perpPosition: { symbol: 'BTCUSDT', size: 0.1, side: 'long', entryPrice: 50000, unrealizedPnl: 100, isOpen: true, } as any, prices: { perpPrice: 51000, hedgePrice: 50900, correlation: 0.98, }, funding: { fundingRate: 0.0001, // 0.01% 资金费率 }, config: { preferredMethod: 'spot', thresholds: { maxSlippage: 0.005, deltaDeviationPct: 0.02, minFundingRate: 0.00005, minNotionalUSD: 10, }, }, } // 5. 执行演示 (使用模拟模式) console.log('\n🎯 执行对冲演示 (模拟模式)...') const adapterPair = { primary: binanceResult.adapter, primaryId: 'binance', } try { // 注意:这是演示代码,实际执行会尝试下单 // 在生产环境中请确保有足够的资金和正确的配置 console.log('⚠️ 演示模式:不会执行真实交易') // 验证订单参数 const mockPrice = '51000' const mockQuantity = '0.001' const validation = PrecisionValidator.adjustOrderParams('binance', 'BTCUSDT', mockPrice, mockQuantity) console.log(`🔧 订单参数调整结果:`) console.log(` 价格: ${mockPrice} -> ${validation.price}`) console.log(` 数量: ${mockQuantity} -> ${validation.quantity}`) console.log(` 有效: ${validation.valid}`) console.log(` 警告: ${validation.warnings.join(', ')}`) // 如果在真实环境中,这里会执行: // const result = await executor.execute(hedgeRequest, adapterPair); } catch (error) { console.error('❌ 执行失败:', error) } // 6. 显示执行统计 console.log('\n📈 执行统计:') const stats = executor.getExecutionStats() console.log(`总执行次数: ${stats.totalExecutions}`) console.log(`成功率: ${(stats.successRate * 100).toFixed(2)}%`) console.log(`平均延迟: ${stats.averageLatency.toFixed(2)}ms`) // 7. 健康检查 console.log('\n🏥 适配器健康检查...') const healthCheck = await AdapterFactory.healthCheck() for (const [adapter, healthy] of Object.entries(healthCheck)) { console.log(`${healthy ? '✅' : '❌'} ${adapter}: ${healthy ? '健康' : '不健康'}`) } console.log('\n🎉 演示完成') } catch (error) { console.error('❌ 演示失败:', error) } } // 运行演示 if (require.main === module) { main().catch(console.error) }