#!/usr/bin/env tsx /** * 高级功能测试套件 * 测试4: WebSocket断线后REST API降级 * 测试5: RiskManager风险告警触发 * 测试6: Delta中性验证 (模拟账户配对交易) */ import { MarketDataManager } from '../src/services/MarketDataManager'; import { RiskManager, RiskManagerConfig } from '../src/core/RiskManager'; import { Account } from '../src/models/Account'; import { PacificaSigningClient } from '../src/services/PacificaSigningClient'; import { readFileSync } from 'fs'; console.log('🧪 开始高级功能测试...\n'); let testsPassed = 0; let testsFailed = 0; // 测试4: WebSocket降级测试 async function testWebSocketFailover(): Promise { console.log('🔌 测试4: WebSocket断线与REST API降级'); try { const marketDataManager = new MarketDataManager(); let priceFromWS = false; let priceValue = 0; marketDataManager.on('price_update', (priceData) => { if (priceData.symbol === 'BTC') { priceFromWS = true; priceValue = typeof priceData.mark === 'number' ? priceData.mark : parseFloat(priceData.mark); } }); await marketDataManager.initialize(); console.log(' ✅ MarketDataManager初始化成功'); // 等待WebSocket价格 await new Promise(resolve => setTimeout(resolve, 3000)); if (priceFromWS) { console.log(` ✅ WebSocket价格正常: $${priceValue.toFixed(2)}`); } else { console.log(' ⚠️ 未收到WebSocket价格'); } // 模拟WebSocket断开 console.log(' 🔌 模拟WebSocket断开...'); await marketDataManager.disconnect(); await new Promise(resolve => setTimeout(resolve, 1000)); // 测试REST API降级 console.log(' 🔄 测试REST API降级方案...'); const accountsData = JSON.parse(readFileSync('./config/accounts.json', 'utf-8')); if (accountsData.length === 0) { console.log(' ❌ 没有可用账户配置\n'); return false; } const privateKey = accountsData[0].privateKey; const pacificaClient = new PacificaSigningClient(privateKey); try { const prices = await pacificaClient.getPrices(); const btcPrice = prices.data.find((p: any) => p.symbol === 'BTC'); if (btcPrice && btcPrice.mark) { const restPrice = parseFloat(btcPrice.mark); console.log(` ✅ REST API价格: $${restPrice.toFixed(2)}`); if (priceFromWS) { const priceDiff = Math.abs(restPrice - priceValue); const priceDiffPercent = (priceDiff / priceValue) * 100; console.log(` 📊 价格差异: $${priceDiff.toFixed(2)} (${priceDiffPercent.toFixed(3)}%)`); } console.log(' ✅ 测试4通过: 降级机制正常\n'); return true; } else { console.log(' ❌ REST API未返回BTC价格\n'); return false; } } catch (error) { console.log(` ❌ REST API调用失败: ${error instanceof Error ? error.message : '未知错误'}\n`); return false; } } catch (error) { console.log(` ❌ 测试4失败: ${error instanceof Error ? error.message : '未知错误'}\n`); return false; } } // 测试5: RiskManager风险告警 async function testRiskManagerBreach(): Promise { console.log('⚠️ 测试5: RiskManager风险告警触发'); try { const riskConfig: RiskManagerConfig = { maxTotalVolume: 10, maxNetExposure: 0.01, maxDailyLoss: 1000, positionLimit: 0.1, // 设置很小的限制用于触发告警 stopLossThreshold: 500, monitoringInterval: 60000 }; const riskManager = new RiskManager(riskConfig); let breachDetected = false; let breachType = ''; riskManager.on('breach_detected', (breach) => { breachDetected = true; breachType = breach.type; console.log(` ⚠️ 检测到风险告警: ${breach.type} (严重程度: ${breach.severity})`); }); await riskManager.initialize(); const sessionId = 'test_risk_' + Date.now(); await riskManager.startMonitoring(sessionId); console.log(' ✅ RiskManager已启动'); // 测试1: 正常仓位 (应该通过) const normalBreach = await riskManager.checkPositionSizeRisk( sessionId, 'test_account_1', 0.05 // 小于0.1限制 ); if (normalBreach === null) { console.log(' ✅ 正常仓位检查通过 (0.05 < 0.1)'); } else { console.log(' ❌ 正常仓位被误判为风险'); } // 测试2: 超限仓位 (应该触发告警) const largeBreach = await riskManager.checkPositionSizeRisk( sessionId, 'test_account_2', 0.15 // 大于0.1限制 ); if (largeBreach !== null) { console.log(` ✅ 超限仓位被拦截 (0.15 > 0.1): ${largeBreach.type}`); breachDetected = true; breachType = largeBreach.type; } else { console.log(' ⚠️ 超限仓位未被检测到'); } await riskManager.stopMonitoring(sessionId); await riskManager.shutdown(); if (normalBreach === null && largeBreach !== null) { console.log(' ✅ 测试5通过: 风险控制正常工作\n'); return true; } else { console.log(' ❌ 测试5失败: 风险检查逻辑有误\n'); return false; } } catch (error) { console.log(` ❌ 测试5失败: ${error instanceof Error ? error.message : '未知错误'}\n`); return false; } } // 测试6: Delta中性验证 async function testDeltaNeutrality(): Promise { console.log('⚖️ 测试6: Delta中性验证 (模拟配对交易)'); try { // 加载账户配置 const accountsData = JSON.parse(readFileSync('./config/accounts.json', 'utf-8')); if (accountsData.length < 2) { console.log(' ❌ 需要至少2个账户进行测试\n'); return false; } // 创建账户实例 const accounts = accountsData.map((data: any) => new Account({ ...data, apiKey: data.apiKey || 'test_api_key', balance: { total: 1000, available: 1000, used: 0 }, positions: [] })); console.log(` 📊 使用${accounts.length}个账户进行测试`); // 创建账户配对 const accountPairs: Array<[Account, Account]> = []; for (let i = 0; i < accounts.length - 1; i += 2) { accountPairs.push([accounts[i], accounts[i + 1]]); } console.log(` 🔗 创建${accountPairs.length}对账户`); // 模拟配对交易 interface MockTrade { accountId: string; side: 'buy' | 'sell'; size: number; price: number; } const mockTrades: MockTrade[] = []; const tradeSize = 0.01; // 0.01 BTC const tradePrice = 100000; // $100,000 for (const [buyAccount, sellAccount] of accountPairs) { // 买方交易 mockTrades.push({ accountId: buyAccount.getId(), side: 'buy', size: tradeSize, price: tradePrice }); // 卖方交易 mockTrades.push({ accountId: sellAccount.getId(), side: 'sell', size: tradeSize, price: tradePrice }); console.log(` 📈 配对${accountPairs.indexOf([buyAccount, sellAccount]) + 1}: ` + `${buyAccount.getId().slice(0,8)} 买入 ${tradeSize} BTC / ` + `${sellAccount.getId().slice(0,8)} 卖出 ${tradeSize} BTC`); } // 计算净Delta let totalBuyVolume = 0; let totalSellVolume = 0; mockTrades.forEach(trade => { if (trade.side === 'buy') { totalBuyVolume += trade.size; } else { totalSellVolume += trade.size; } }); const netDelta = totalBuyVolume - totalSellVolume; const netDeltaPercent = Math.abs(netDelta / totalBuyVolume) * 100; console.log(` 📊 总买入: ${totalBuyVolume.toFixed(6)} BTC`); console.log(` 📊 总卖出: ${totalSellVolume.toFixed(6)} BTC`); console.log(` 📊 净Delta: ${netDelta.toFixed(6)} BTC (${netDeltaPercent.toFixed(4)}%)`); // 验证Delta中性 (容差0.0001%) if (Math.abs(netDeltaPercent) < 0.0001) { console.log(' ✅ Delta中性验证通过: 净仓位为零'); console.log(' ✅ 测试6通过: 配对交易逻辑正确\n'); return true; } else { console.log(` ❌ Delta不中性: ${netDeltaPercent.toFixed(4)}% 偏差`); console.log(' ❌ 测试6失败: 配对交易逻辑有误\n'); return false; } } catch (error) { console.log(` ❌ 测试6失败: ${error instanceof Error ? error.message : '未知错误'}\n`); return false; } } // 主测试流程 async function runAdvancedTests() { console.log('='.repeat(60)); console.log(' P0高级功能测试套件'); console.log('='.repeat(60) + '\n'); // 测试4: WebSocket降级 if (await testWebSocketFailover()) { testsPassed++; } else { testsFailed++; } // 测试5: 风险告警 if (await testRiskManagerBreach()) { testsPassed++; } else { testsFailed++; } // 测试6: Delta中性 if (await testDeltaNeutrality()) { testsPassed++; } else { testsFailed++; } // 输出结果 console.log('='.repeat(60)); console.log(' 测试结果'); console.log('='.repeat(60)); console.log(`✅ 通过: ${testsPassed}/3`); console.log(`❌ 失败: ${testsFailed}/3`); console.log(`📊 成功率: ${((testsPassed / 3) * 100).toFixed(1)}%`); console.log('='.repeat(60) + '\n'); if (testsPassed === 3) { console.log('🎉 所有高级测试通过! 系统功能完整。'); console.log('🚀 可以开始生产环境部署。\n'); process.exit(0); } else { console.log('⚠️ 部分测试失败,请检查上述错误信息。\n'); process.exit(1); } } // 运行测试 runAdvancedTests().catch((error) => { console.error('💥 测试执行失败:', error); process.exit(1); });