'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) // 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 const response = await fetch('/api/trading/execute', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ symbol, side: tradeType, amount: parseFloat(amount), price: tradePrice, orderType: tradePrice ? 'limit' : 'market' }) }) const result = await response.json() if (result.success) { 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}
)} {/* 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" />
{/* 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" /> )}
{/* Execute Button */} {/* Execution Result */} {executionResult && (
{executionResult.success ? '✅ Trade Executed' : '❌ Trade Failed'}
{executionResult.message}
{executionResult.trade && (
TX ID: {executionResult.trade.txId}
)}
)} {/* Risk Warning */}
⚠️ Trading involves significant risk. This is a simulated trading environment using Bitquery data.
) }