// Dynamic Position Calculator Component "use client" import React, { useState, useEffect } from 'react' interface PositionCalculatorProps { analysis?: any // The AI analysis results currentPrice?: number symbol?: string onPositionChange?: (position: PositionCalculation) => void } interface PositionCalculation { investmentAmount: number leverage: number positionSize: number entryPrice: number stopLoss: number takeProfit: number liquidationPrice: number maxLoss: number maxProfit: number riskRewardRatio: number marginRequired: number tradingFee: number netInvestment: number } export default function PositionCalculator({ analysis, currentPrice = 0, symbol = 'BTCUSD', onPositionChange }: PositionCalculatorProps) { const [investmentAmount, setInvestmentAmount] = useState(100) const [leverage, setLeverage] = useState(10) const [positionType, setPositionType] = useState<'long' | 'short'>('long') const [calculation, setCalculation] = useState(null) const [showAdvanced, setShowAdvanced] = useState(false) // Trading parameters const [tradingFee, setTradingFee] = useState(0.1) // 0.1% fee const [maintenanceMargin, setMaintenanceMargin] = useState(0.5) // 0.5% maintenance margin // Calculate position metrics const calculatePosition = () => { if (!currentPrice || currentPrice <= 0) return null const positionSize = investmentAmount * leverage const marginRequired = investmentAmount const fee = positionSize * (tradingFee / 100) const netInvestment = investmentAmount + fee // Get AI analysis targets if available let entryPrice = currentPrice let stopLoss = 0 let takeProfit = 0 if (analysis && analysis.analysis) { // Try to extract entry, stop loss, and take profit from AI analysis const analysisText = analysis.analysis.toLowerCase() // Look for entry price const entryMatch = analysisText.match(/entry[:\s]*[\$]?(\d+\.?\d*)/i) if (entryMatch) { entryPrice = parseFloat(entryMatch[1]) } // Look for stop loss const stopMatch = analysisText.match(/stop[:\s]*[\$]?(\d+\.?\d*)/i) if (stopMatch) { stopLoss = parseFloat(stopMatch[1]) } // Look for take profit const profitMatch = analysisText.match(/(?:take profit|target)[:\s]*[\$]?(\d+\.?\d*)/i) if (profitMatch) { takeProfit = parseFloat(profitMatch[1]) } // If no specific targets found, use percentage-based defaults if (!stopLoss) { stopLoss = positionType === 'long' ? entryPrice * 0.95 // 5% stop loss for long : entryPrice * 1.05 // 5% stop loss for short } if (!takeProfit) { takeProfit = positionType === 'long' ? entryPrice * 1.10 // 10% take profit for long : entryPrice * 0.90 // 10% take profit for short } } else { // Default targets if no analysis stopLoss = positionType === 'long' ? currentPrice * 0.95 : currentPrice * 1.05 takeProfit = positionType === 'long' ? currentPrice * 1.10 : currentPrice * 0.90 } // Calculate liquidation price const liquidationPrice = positionType === 'long' ? entryPrice * (1 - (1 / leverage) + (maintenanceMargin / 100)) : entryPrice * (1 + (1 / leverage) - (maintenanceMargin / 100)) // Calculate PnL const stopLossChange = positionType === 'long' ? (stopLoss - entryPrice) / entryPrice : (entryPrice - stopLoss) / entryPrice const takeProfitChange = positionType === 'long' ? (takeProfit - entryPrice) / entryPrice : (entryPrice - takeProfit) / entryPrice const maxLoss = positionSize * Math.abs(stopLossChange) const maxProfit = positionSize * Math.abs(takeProfitChange) const riskRewardRatio = maxProfit / maxLoss const result: PositionCalculation = { investmentAmount, leverage, positionSize, entryPrice, stopLoss, takeProfit, liquidationPrice, maxLoss, maxProfit, riskRewardRatio, marginRequired, tradingFee: fee, netInvestment } setCalculation(result) onPositionChange?.(result) return result } // Recalculate when parameters change useEffect(() => { calculatePosition() }, [investmentAmount, leverage, positionType, currentPrice, analysis, tradingFee, maintenanceMargin]) const formatCurrency = (amount: number, decimals: number = 2) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(amount) } const formatPrice = (price: number) => { return new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(price) } return (

📊 Position Calculator

{/* Input Controls */}
{/* Investment Amount */}
setInvestmentAmount(Number(e.target.value))} className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" min="1" step="1" />
{/* Position Type */}
{/* Leverage Slider */}
setLeverage(Number(e.target.value))} className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer slider" style={{ background: `linear-gradient(to right, #10B981 0%, #10B981 ${leverage}%, #374151 ${leverage}%, #374151 100%)` }} />
1x 25x 50x 100x
{/* Advanced Settings */} {showAdvanced && (
setTradingFee(Number(e.target.value))} className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" min="0" max="1" step="0.01" />
setMaintenanceMargin(Number(e.target.value))} className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" min="0.1" max="5" step="0.1" />
)} {/* Calculation Results */} {calculation && (
{/* Position Summary */}
Position Size
{formatCurrency(calculation.positionSize)}
Entry Price
${formatPrice(calculation.entryPrice)}
Margin Required
{formatCurrency(calculation.marginRequired)}
{/* Risk Metrics */}
🚨 Risk Metrics
Stop Loss: ${formatPrice(calculation.stopLoss)}
Max Loss: {formatCurrency(calculation.maxLoss)}
Liquidation: ${formatPrice(calculation.liquidationPrice)}
💰 Profit Potential
Take Profit: ${formatPrice(calculation.takeProfit)}
Max Profit: {formatCurrency(calculation.maxProfit)}
Risk/Reward: 1:{calculation.riskRewardRatio.toFixed(2)}
{/* Fee Breakdown */}
💸 Fee Breakdown
Trading Fee: {formatCurrency(calculation.tradingFee)}
Net Investment: {formatCurrency(calculation.netInvestment)}
Leverage: {leverage}x
{/* Risk Warning */} {leverage > 50 && (
⚠️ High Leverage Warning

Using {leverage}x leverage is extremely risky. A small price movement against your position could result in liquidation.

)}
)}
) }