123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336 |
- #!/usr/bin/env tsx
- /**
- * Delta 对冲诊断工具
- *
- * 用途:
- * 1. 检查 Delta 检测是否生效
- * 2. 验证对冲信号执行情况
- * 3. 核对配置与阈值
- * 4. 确认镜像减仓有效性
- * 5. 实时输出净敞口
- */
- import Logger from '../src/utils/Logger';
- import { ConfigurationManager } from '../src/modules/ConfigurationManager';
- import { AccountManager } from '../src/modules/AccountManager';
- import { DataAggregator } from '../src/services/DataAggregator';
- import { EnhancedDeltaController, PositionData } from '../src/services/EnhancedDeltaController';
- import { SignalExecutor } from '../src/services/SignalExecutor';
- import { PacificaSigningClient } from '../src/services/PacificaSigningClient';
- const logger = Logger.getInstance();
- interface DiagnosticResult {
- timestamp: string;
- deltaDetection: {
- enabled: boolean;
- threshold: number;
- currentDelta: number;
- exceeded: boolean;
- };
- hedgingSignals: {
- generated: boolean;
- count: number;
- details: any[];
- };
- execution: {
- attempted: boolean;
- successful: number;
- failed: number;
- errors: string[];
- };
- netExposure: {
- totalBTC: number;
- totalUSDC: number;
- byAccount: Record<string, { btc: number; usdc: number }>;
- };
- recommendations: string[];
- }
- class DeltaDiagnostic {
- private configManager: ConfigurationManager;
- private accountManager: AccountManager;
- private deltaController: EnhancedDeltaController;
- private signalExecutor: SignalExecutor;
- constructor() {
- this.configManager = ConfigurationManager.getInstance();
- this.accountManager = new AccountManager();
- this.deltaController = new EnhancedDeltaController();
- this.signalExecutor = new SignalExecutor({ enableDryRun: true });
- }
- async initialize(): Promise<void> {
- console.log('🔍 初始化诊断工具...\n');
- // Load configurations
- this.configManager.loadConfigurations();
- const accountsConfig = this.configManager.getAccountsConfig();
- const deltaConfig = this.configManager.getDeltaConfig();
- // Initialize accounts
- this.accountManager.initializeAccounts(accountsConfig);
- // Register clients with SignalExecutor
- const accounts = this.accountManager.getAccounts();
- for (const [accountId, accountInfo] of accounts) {
- const client = this.accountManager.getAccountClient(accountId);
- if (client) {
- this.signalExecutor.registerClient(accountId, client);
- }
- }
- console.log('✅ 诊断工具初始化完成\n');
- }
- async runDiagnostic(): Promise<DiagnosticResult> {
- console.log('📊 开始 Delta 对冲诊断...\n');
- const result: DiagnosticResult = {
- timestamp: new Date().toISOString(),
- deltaDetection: {
- enabled: false,
- threshold: 0,
- currentDelta: 0,
- exceeded: false
- },
- hedgingSignals: {
- generated: false,
- count: 0,
- details: []
- },
- execution: {
- attempted: false,
- successful: 0,
- failed: 0,
- errors: []
- },
- netExposure: {
- totalBTC: 0,
- totalUSDC: 0,
- byAccount: {}
- },
- recommendations: []
- };
- try {
- // 1. 检查配置
- await this.checkConfiguration(result);
- // 2. 获取账户数据
- await this.fetchAccountData(result);
- // 3. 评估 Delta
- await this.assessDelta(result);
- // 4. 检查对冲信号
- await this.checkHedgingSignals(result);
- // 5. 生成建议
- this.generateRecommendations(result);
- } catch (error) {
- logger.error('诊断过程出错', { error });
- result.recommendations.push(`❌ 诊断失败: ${error instanceof Error ? error.message : '未知错误'}`);
- }
- return result;
- }
- private async checkConfiguration(result: DiagnosticResult): Promise<void> {
- console.log('1️⃣ 检查配置...');
- const deltaConfig = this.configManager.getDeltaConfig();
- const strategyConfig = this.configManager.getStrategyConfig();
- // Delta 再平衡配置
- const rebalanceEnabled = strategyConfig.deltaRebalancing?.enabled || false;
- const rebalanceThreshold = strategyConfig.deltaRebalancing?.rebalanceThreshold || 0.05;
- const maxDeltaDeviation = strategyConfig.deltaRebalancing?.maxDeltaDeviation || 0.001;
- result.deltaDetection.enabled = rebalanceEnabled;
- result.deltaDetection.threshold = rebalanceThreshold;
- console.log(` ✓ Delta 再平衡: ${rebalanceEnabled ? '已启用' : '已禁用'}`);
- console.log(` ✓ 触发阈值: ${(rebalanceThreshold * 100).toFixed(2)}%`);
- console.log(` ✓ 目标偏差: ${(maxDeltaDeviation * 100).toFixed(2)}%`);
- // EnhancedDeltaController 配置
- const deltaControllerConfig = this.deltaController.getConfig();
- console.log(` ✓ 基础容忍度: ${(deltaControllerConfig.baseDeltaTolerance * 100).toFixed(2)}%`);
- console.log(` ✓ 平稳容忍度: ${(deltaControllerConfig.stableDeltaTolerance * 100).toFixed(2)}%`);
- console.log(` ✓ 波动容忍度: ${(deltaControllerConfig.volatileDeltaTolerance * 100).toFixed(2)}%`);
- console.log('');
- }
- private async fetchAccountData(result: DiagnosticResult): Promise<void> {
- console.log('2️⃣ 获取账户数据...');
- const accountInfos = await this.accountManager.getAllAccountInfo();
- const tradingSymbol = this.configManager.getTradingSymbol();
- let totalBTC = 0;
- let totalUSDC = 0;
- for (const [accountId, info] of accountInfos) {
- const positions = info.positions || [];
- const btcPosition = positions.find((p: any) => p.symbol === tradingSymbol);
- const btcSize = btcPosition ? parseFloat(btcPosition.size) : 0;
- const accountEquity = parseFloat(info.account_equity || '0');
- totalBTC += btcSize;
- totalUSDC += accountEquity;
- result.netExposure.byAccount[accountId] = {
- btc: btcSize,
- usdc: accountEquity
- };
- console.log(` Account ${accountId}:`);
- console.log(` BTC Position: ${btcSize.toFixed(5)} BTC`);
- console.log(` Equity: ${accountEquity.toFixed(2)} USDC`);
- }
- result.netExposure.totalBTC = totalBTC;
- result.netExposure.totalUSDC = totalUSDC;
- console.log(`\n 📊 总净敞口: ${totalBTC.toFixed(5)} BTC`);
- console.log(` 💰 总权益: ${totalUSDC.toFixed(2)} USDC\n`);
- }
- private async assessDelta(result: DiagnosticResult): Promise<void> {
- console.log('3️⃣ 评估 Delta...');
- const tradingSymbol = this.configManager.getTradingSymbol();
- const totalBTC = result.netExposure.totalBTC;
- // Get current price from first account's market data
- const accountInfos = await this.accountManager.getAllAccountInfo();
- const firstAccount = Array.from(accountInfos.values())[0];
- const positions = firstAccount?.positions || [];
- const btcPosition = positions.find((p: any) => p.symbol === tradingSymbol);
- const currentPrice = btcPosition ? parseFloat(btcPosition.mark_price || '0') : 0;
- // Create position data
- const positionData: PositionData = {
- symbol: tradingSymbol,
- size: totalBTC,
- value: totalBTC * currentPrice,
- timestamp: Date.now()
- };
- // Record price
- this.deltaController.recordPrice(tradingSymbol, currentPrice);
- // Assess delta
- const assessment = this.deltaController.assessDelta(tradingSymbol, positionData);
- result.deltaDetection.currentDelta = assessment.weightedDelta;
- result.deltaDetection.exceeded = assessment.exceedsTolerance;
- console.log(` 当前价格: ${currentPrice.toFixed(2)} USDC`);
- console.log(` 仓位价值: ${positionData.value.toFixed(2)} USDC`);
- console.log(` 加权 Delta: ${(assessment.weightedDelta * 100).toFixed(4)}%`);
- console.log(` 当前容忍度: ${(assessment.currentTolerance * 100).toFixed(4)}%`);
- console.log(` 是否超限: ${assessment.exceedsTolerance ? '是 ⚠️' : '否 ✅'}`);
- console.log(` 建议操作: ${assessment.recommendation}`);
- if (assessment.predictedDirection) {
- console.log(` 预测方向: ${assessment.predictedDirection} (置信度: ${((assessment.confidenceScore || 0) * 100).toFixed(2)}%)`);
- }
- console.log('');
- }
- private async checkHedgingSignals(result: DiagnosticResult): Promise<void> {
- console.log('4️⃣ 检查对冲信号...');
- // 这里需要访问策略引擎生成的信号
- // 由于策略引擎是在主循环中运行的,我们无法直接获取
- // 建议:在实际运行中监听 SignalExecutor 的事件
- console.log(' ℹ️ 对冲信号检查需要在实际运行中通过日志监听');
- console.log(' 建议查找日志关键字: "Delta exceeds tolerance", "Hedging signal"\n');
- }
- private generateRecommendations(result: DiagnosticResult): void {
- console.log('5️⃣ 生成建议...\n');
- const recommendations: string[] = [];
- // 检查配置
- if (!result.deltaDetection.enabled) {
- recommendations.push('⚠️ Delta 再平衡未启用,建议在配置中启用 deltaRebalancing.enabled');
- }
- // 检查阈值
- if (result.deltaDetection.threshold > 0.1) {
- recommendations.push('⚠️ Delta 阈值过高 (>10%),建议降低到 0.01-0.05 之间');
- }
- // 检查净敞口
- const totalBTC = Math.abs(result.netExposure.totalBTC);
- if (totalBTC > 0.01) {
- const exposurePercent = (totalBTC / 1) * 100; // 假设基准为 1 BTC
- recommendations.push(`⚠️ 当前净敞口: ${totalBTC.toFixed(5)} BTC,建议检查对冲机制`);
- }
- // 检查 Delta 超限
- if (result.deltaDetection.exceeded) {
- recommendations.push('🚨 Delta 超限!应生成对冲信号,请检查日志中是否有 "Delta exceeds tolerance"');
- }
- // 配置优化建议
- recommendations.push('💡 建议启用详细日志: 在策略引擎中添加 Delta 评估日志');
- recommendations.push('💡 建议监控对冲执行: 在 SignalExecutor 中监听执行事件');
- result.recommendations = recommendations;
- recommendations.forEach(rec => console.log(` ${rec}`));
- }
- printReport(result: DiagnosticResult): void {
- console.log('\n' + '='.repeat(80));
- console.log('📋 诊断报告');
- console.log('='.repeat(80));
- console.log(`时间: ${result.timestamp}\n`);
- console.log('【Delta 检测】');
- console.log(` 启用状态: ${result.deltaDetection.enabled ? '✅ 已启用' : '❌ 未启用'}`);
- console.log(` 触发阈值: ${(result.deltaDetection.threshold * 100).toFixed(2)}%`);
- console.log(` 当前 Delta: ${(result.deltaDetection.currentDelta * 100).toFixed(4)}%`);
- console.log(` 是否超限: ${result.deltaDetection.exceeded ? '⚠️ 是' : '✅ 否'}\n`);
- console.log('【净敞口】');
- console.log(` 总 BTC: ${result.netExposure.totalBTC.toFixed(5)} BTC`);
- console.log(` 总 USDC: ${result.netExposure.totalUSDC.toFixed(2)} USDC`);
- console.log(' 分账户:');
- for (const [accountId, exposure] of Object.entries(result.netExposure.byAccount)) {
- console.log(` ${accountId}: ${exposure.btc.toFixed(5)} BTC, ${exposure.usdc.toFixed(2)} USDC`);
- }
- console.log('');
- console.log('【建议】');
- result.recommendations.forEach(rec => console.log(` ${rec}`));
- console.log('\n' + '='.repeat(80));
- }
- }
- // Main execution
- async function main() {
- const diagnostic = new DeltaDiagnostic();
- try {
- await diagnostic.initialize();
- const result = await diagnostic.runDiagnostic();
- diagnostic.printReport(result);
- process.exit(0);
- } catch (error) {
- console.error('❌ 诊断失败:', error);
- process.exit(1);
- }
- }
- main();
|