"use strict"; /** * AI-Driven Dynamic Leverage Calculator * * Calculates optimal leverage to maximize profits while maintaining safe liquidation distance * Strategy: Use maximum leverage possible without liquidation price being too close to stop loss */ Object.defineProperty(exports, "__esModule", { value: true }); exports.AILeverageCalculator = void 0; class AILeverageCalculator { /** * Calculate optimal leverage for maximum profit with safe liquidation distance */ static calculateOptimalLeverage(params) { const { accountValue, availableBalance, entryPrice, stopLossPrice, side, maxLeverageAllowed, safetyBuffer = 0.10 // 10% safety buffer by default } = params; console.log('🧮 AI Leverage Calculation:', { accountValue: accountValue.toFixed(2), availableBalance: availableBalance.toFixed(2), entryPrice, stopLossPrice, side, maxLeverageAllowed }); // Strategy 1: Under $1k - Use 100% of available balance const useFullBalance = accountValue < 1000; const baseAmount = useFullBalance ? availableBalance : availableBalance * 0.5; // 50% for accounts over $1k console.log(`💰 Balance Strategy: ${useFullBalance ? 'AGGRESSIVE (100%)' : 'CONSERVATIVE (50%)'} - Using $${baseAmount.toFixed(2)}`); // Calculate stop loss distance as percentage const stopLossDistance = Math.abs(entryPrice - stopLossPrice) / entryPrice; console.log(`📊 Stop Loss Distance: ${(stopLossDistance * 100).toFixed(2)}%`); // Calculate maximum safe leverage based on liquidation distance const maxSafeLeverage = this.calculateMaxSafeLeverage(entryPrice, stopLossPrice, side, safetyBuffer); // Determine final leverage (limited by platform max and safety calculations) const finalLeverage = Math.min(maxSafeLeverage, maxLeverageAllowed); // Calculate position size and margin const positionSize = baseAmount * finalLeverage; const marginRequired = positionSize / finalLeverage; // Calculate liquidation price for verification const liquidationPrice = this.calculateLiquidationPrice(entryPrice, finalLeverage, side, marginRequired, positionSize); // Risk assessment const riskAssessment = this.assessRisk(finalLeverage, stopLossDistance, useFullBalance); // Generate AI reasoning const reasoning = this.generateLeverageReasoning(finalLeverage, maxSafeLeverage, maxLeverageAllowed, liquidationPrice, stopLossPrice, useFullBalance, side); const result = { recommendedLeverage: finalLeverage, positionSize, liquidationPrice, marginRequired, maxPossibleLeverage: maxSafeLeverage, riskAssessment, reasoning }; console.log('🎯 AI Leverage Result:', { recommendedLeverage: `${finalLeverage.toFixed(1)}x`, positionSize: `$${positionSize.toFixed(2)}`, liquidationPrice: `$${liquidationPrice.toFixed(4)}`, riskAssessment, reasoning }); return result; } /** * Calculate maximum safe leverage where liquidation price maintains safety buffer from stop loss */ static calculateMaxSafeLeverage(entryPrice, stopLossPrice, side, safetyBuffer) { // Calculate where liquidation should be (beyond stop loss + safety buffer) let maxLiquidationPrice; if (side === 'long') { // For longs: liquidation should be below stop loss maxLiquidationPrice = stopLossPrice * (1 - safetyBuffer); } else { // For shorts: liquidation should be above stop loss maxLiquidationPrice = stopLossPrice * (1 + safetyBuffer); } console.log(`🛡️ Max Safe Liquidation Price: $${maxLiquidationPrice.toFixed(4)} (${side} position)`); // Calculate max leverage that keeps liquidation at safe distance // Simplified liquidation formula: For longs: liq = entry * (1 - 1/leverage) let maxLeverage; if (side === 'long') { // entry * (1 - 1/leverage) = maxLiquidationPrice // 1 - 1/leverage = maxLiquidationPrice / entry // 1/leverage = 1 - maxLiquidationPrice / entry // leverage = 1 / (1 - maxLiquidationPrice / entry) maxLeverage = 1 / (1 - maxLiquidationPrice / entryPrice); } else { // For shorts: liq = entry * (1 + 1/leverage) // entry * (1 + 1/leverage) = maxLiquidationPrice // 1 + 1/leverage = maxLiquidationPrice / entry // 1/leverage = maxLiquidationPrice / entry - 1 // leverage = 1 / (maxLiquidationPrice / entry - 1) maxLeverage = 1 / (maxLiquidationPrice / entryPrice - 1); } // Ensure reasonable bounds maxLeverage = Math.max(1, Math.min(maxLeverage, 50)); // Between 1x and 50x console.log(`⚖️ Max Safe Leverage: ${maxLeverage.toFixed(2)}x`); return maxLeverage; } /** * Calculate liquidation price for given position parameters */ static calculateLiquidationPrice(entryPrice, leverage, side, marginRequired, positionSize) { // Simplified liquidation calculation // In reality, this would need to account for fees, funding, etc. if (side === 'long') { // Long liquidation: entry * (1 - 1/leverage) return entryPrice * (1 - 1 / leverage); } else { // Short liquidation: entry * (1 + 1/leverage) return entryPrice * (1 + 1 / leverage); } } /** * Assess risk level based on leverage and position parameters */ static assessRisk(leverage, stopLossDistance, useFullBalance) { if (leverage <= 2 && stopLossDistance >= 0.05) return 'LOW'; if (leverage <= 5 && stopLossDistance >= 0.03) return 'MEDIUM'; if (leverage <= 10 && stopLossDistance >= 0.02) return 'MEDIUM'; return 'HIGH'; } /** * Generate AI reasoning for leverage decision */ static generateLeverageReasoning(finalLeverage, maxSafeLeverage, maxPlatformLeverage, liquidationPrice, stopLossPrice, useFullBalance, side) { const reasons = []; // Balance strategy reasoning if (useFullBalance) { reasons.push("Account <$1k: Using 100% available balance for maximum growth"); } else { reasons.push("Account >$1k: Using 50% balance for controlled risk"); } // Leverage limitation reasoning if (finalLeverage === maxSafeLeverage) { reasons.push(`Max safe leverage ${finalLeverage.toFixed(1)}x maintains liquidation safely beyond stop loss`); } else if (finalLeverage === maxPlatformLeverage) { reasons.push(`Platform limit ${maxPlatformLeverage}x reached (could use ${maxSafeLeverage.toFixed(1)}x safely)`); } // Liquidation safety reasoning const liquidationBuffer = side === 'long' ? (stopLossPrice - liquidationPrice) / stopLossPrice * 100 : (liquidationPrice - stopLossPrice) / stopLossPrice * 100; reasons.push(`Liquidation $${liquidationPrice.toFixed(4)} is ${liquidationBuffer.toFixed(1)}% beyond stop loss`); return reasons.join('. '); } } exports.AILeverageCalculator = AILeverageCalculator; exports.default = AILeverageCalculator;