'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) } // Set trade type based on analysis recommendation if (analysis.recommendation === 'BUY' || analysis.sentiment === 'BULLISH') { setTradeType('BUY') } else if (analysis.recommendation === 'SELL' || analysis.sentiment === 'BEARISH') { setTradeType('SELL') } } }, [analysis]) // Initialize coin selection based on symbol prop useEffect(() => { if (symbol && availableCoins.find(coin => coin.symbol === symbol)) { setFromCoin(symbol) setPerpCoin(symbol) // If it's not a stablecoin, trade it against USDC if (symbol !== 'USDC' && symbol !== 'USDT') { setToCoin('USDC') } } }, [symbol]) // 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 (