'use client' import React, { useState, useEffect } from 'react' export default function TradeExecutionPanel({ analysis, symbol = 'SOL' }) { const [tradeType, setTradeType] = useState('BUY') const [amount, setAmount] = useState('') const [customPrice, setCustomPrice] = useState('') const [useRecommendedPrice, setUseRecommendedPrice] = useState(true) const [isExecuting, setIsExecuting] = useState(false) const [executionResult, setExecutionResult] = useState(null) const [balance, setBalance] = useState(null) // Trading mode and coin selection const [tradingMode, setTradingMode] = useState('SPOT') // 'SPOT' or 'PERP' const [fromCoin, setFromCoin] = useState('SOL') const [toCoin, setToCoin] = useState('USDC') const [perpCoin, setPerpCoin] = useState('SOL') // For perpetuals // TP/SL functionality const [enableStopLoss, setEnableStopLoss] = useState(false) const [stopLoss, setStopLoss] = useState('') const [enableTakeProfit, setEnableTakeProfit] = useState(false) const [takeProfit, setTakeProfit] = useState('') // Perp trading settings const [leverage, setLeverage] = useState(1) const [perpSize, setPerpSize] = useState('') // Available coins for trading const availableCoins = [ { symbol: 'SOL', name: 'Solana', icon: '🟣' }, { symbol: 'USDC', name: 'USD Coin', icon: '💵' }, { symbol: 'USDT', name: 'Tether', icon: '💶' }, { symbol: 'BTC', name: 'Bitcoin', icon: '₿' }, { symbol: 'ETH', name: 'Ethereum', icon: '🔷' }, { symbol: 'RAY', name: 'Raydium', icon: '⚡' }, { symbol: 'ORCA', name: 'Orca', icon: '🐋' } ] // Auto-fill TP/SL from AI analysis useEffect(() => { if (analysis) { if (analysis.stopLoss?.price) { setStopLoss(analysis.stopLoss.price.toString()) setEnableStopLoss(true) } if (analysis.takeProfits?.tp1?.price) { setTakeProfit(analysis.takeProfits.tp1.price.toString()) setEnableTakeProfit(true) } } }, [analysis]) // Get recommended price from analysis const getRecommendedPrice = () => { if (!analysis) return null if (analysis.recommendation === 'BUY' && analysis.entry?.price) { return analysis.entry.price } else if (analysis.recommendation === 'SELL' && analysis.entry?.price) { return analysis.entry.price } return null } const recommendedPrice = getRecommendedPrice() // Fetch balance on component mount useEffect(() => { fetchBalance() }, []) const fetchBalance = async () => { try { const response = await fetch('/api/trading/balance') const data = await response.json() if (data.success) { setBalance(data.balance) } } catch (error) { console.error('Failed to fetch balance:', error) } } const executeTrade = async () => { if (!amount || parseFloat(amount) <= 0) { alert('Please enter a valid amount') return } setIsExecuting(true) setExecutionResult(null) try { const tradePrice = useRecommendedPrice && recommendedPrice ? recommendedPrice : customPrice ? parseFloat(customPrice) : undefined // Prepare trade data based on trading mode let tradeData = { symbol: tradingMode === 'PERP' ? perpCoin : fromCoin, side: tradeType, amount: parseFloat(amount), price: tradePrice, orderType: tradePrice ? 'limit' : 'market', useRealDEX: true, // Always use real DEX tradingMode: tradingMode, tradingPair: tradingMode === 'PERP' ? `${perpCoin}-PERP` : `${fromCoin}/${toCoin}`, fromCoin: fromCoin, toCoin: toCoin } // Add TP/SL if enabled if (enableStopLoss && stopLoss) { tradeData.stopLoss = parseFloat(stopLoss) } if (enableTakeProfit && takeProfit) { tradeData.takeProfit = parseFloat(takeProfit) } // Add perpetuals specific data if (tradingMode === 'PERP') { tradeData.leverage = leverage tradeData.perpSize = perpSize ? parseFloat(perpSize) : parseFloat(amount) tradeData.perpCoin = perpCoin } // Determine API endpoint based on trading mode and order type let apiEndpoint = '/api/trading/execute-dex' if (tradingMode === 'PERP') { apiEndpoint = '/api/trading/execute-perp' } else if (tradePrice) { // Limit orders go through the main trading API apiEndpoint = '/api/trading' } const response = await fetch(apiEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(tradeData) }) const result = await response.json() if (result.success) { // Check if this was a limit order creation if (result.type === 'limit_order_created') { setExecutionResult({ success: true, order: result.order, type: 'limit_order', message: result.message }) } else { setExecutionResult({ success: true, trade: result.trade, message: result.message }) } // Refresh balance after successful trade await fetchBalance() } else { setExecutionResult({ success: false, error: result.error, message: result.message }) } } catch (error) { setExecutionResult({ success: false, error: 'Network error', message: 'Failed to execute trade. Please try again.' }) } finally { setIsExecuting(false) } } const getTradeButtonColor = () => { if (tradeType === 'BUY') return 'bg-green-600 hover:bg-green-700' return 'bg-red-600 hover:bg-red-700' } const getRecommendationColor = () => { if (!analysis) return 'text-gray-400' switch (analysis.recommendation) { case 'BUY': return 'text-green-400' case 'SELL': return 'text-red-400' default: return 'text-yellow-400' } } return (

Execute Trade

{symbol} Trading
{/* Balance Display */} {balance && (

Portfolio Balance

${balance.totalValue?.toFixed(2)} Available: ${balance.availableBalance?.toFixed(2)}
)} {/* AI Recommendation Display */} {analysis && (

AI Recommendation

{analysis.recommendation} {analysis.confidence}% confidence
{recommendedPrice && (
Entry: ${recommendedPrice.toFixed(4)} {analysis.entry?.buffer && ( ({analysis.entry.buffer}) )}
)} {analysis.stopLoss && (
Stop Loss: ${analysis.stopLoss.price.toFixed(4)}
)} {analysis.takeProfits?.tp1 && (
TP1: ${analysis.takeProfits.tp1.price.toFixed(4)}
)}
{analysis.reasoning}
)} {/* Trading Mode Selection */}
{/* Coin Selection for Spot Trading */} {tradingMode === 'SPOT' && (
{/* From Coin */}
{/* Swap Arrow */}
{/* To Coin */}
Swap {fromCoin} → {toCoin} via Jupiter DEX
)} {/* Coin Selection and Leverage for Perpetuals */} {tradingMode === 'PERP' && (
{/* Perpetual Coin Selection */}
Choose the asset you want to trade with leverage
{/* Leverage Selection */}
{[1, 2, 5, 10].map(lev => ( ))}
⚠️ Higher leverage = Higher risk. Max 10x for safety.
)} {/* Trade Type Selection */}
{/* Amount Input */}
setAmount(e.target.value)} placeholder="0.00" step="0.001" min="0" className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500" />
{tradingMode === 'PERP' ? `Enter the ${perpCoin} position size to trade with ${leverage}x leverage` : `Enter the amount of ${fromCoin} to swap for ${toCoin}` }
{/* Price Selection */}
{recommendedPrice && ( )} {!useRecommendedPrice && ( setCustomPrice(e.target.value)} placeholder="Enter price (leave empty for market)" step="0.0001" min="0" className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500" /> )}
{/* Stop Loss & Take Profit */}

Risk Management

{/* Stop Loss */}
{enableStopLoss && ( setStopLoss(e.target.value)} placeholder="Stop loss price" step="0.01" className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-500" /> )} {enableStopLoss && analysis?.stopLoss && (
AI Suggested: ${analysis.stopLoss.price.toFixed(4)} - {analysis.stopLoss.rationale}
)}
{/* Take Profit */}
{enableTakeProfit && ( setTakeProfit(e.target.value)} placeholder="Take profit price" step="0.01" className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500" /> )} {enableTakeProfit && analysis?.takeProfits?.tp1 && (
AI Suggested: ${analysis.takeProfits.tp1.price.toFixed(4)} - {analysis.takeProfits.tp1.description}
)}
{/* Execute Button */} {/* Execution Result */} {executionResult && (
{executionResult.success ? ( executionResult.type === 'limit_order' ? '📋 Limit Order Created' : '✅ Trade Executed' ) : '❌ Trade Failed'}
{executionResult.message}
{executionResult.trade && (
TX ID: {executionResult.trade.txId}
)} {executionResult.order && (
Order ID: {executionResult.order.id}
Limit Price: ${executionResult.order.limitPrice}
Status: {executionResult.order.status}
)}
)} {/* Risk Warning */}
⚠️ Trading involves significant risk of loss. Real trades executed via Jupiter DEX using your actual wallet funds.
) }