"use client" import React, { useEffect, useState } from 'react' interface Trade { id: string symbol: string side: string amount: number price: number status: string executedAt: string pnl?: number } export default function TradingHistory() { const [trades, setTrades] = useState([]) const [loading, setLoading] = useState(true) const [isClient, setIsClient] = useState(false) const [error, setError] = useState(null) const [message, setMessage] = useState('') const [syncing, setSyncing] = useState(false) useEffect(() => { setIsClient(true) }, []) const formatTime = (dateString: string) => { if (!isClient) return '--:--:--' return new Date(dateString).toLocaleTimeString() } const formatDate = (dateString: string) => { if (!isClient) return '--/--/--' return new Date(dateString).toLocaleDateString() } const handleSync = async () => { try { setSyncing(true) const response = await fetch('/api/drift/sync-trades', { method: 'POST' }) if (response.ok) { const data = await response.json() setMessage(data.message || 'Sync completed') // Refresh the trading history after sync await fetchTrades() } else { setError('Failed to sync trades') } } catch (error) { console.error('Sync error:', error) setError('Error during sync') } finally { setSyncing(false) } } const fetchTrades = async () => { try { setError(null) setMessage('') // Try Drift trading history first const driftRes = await fetch('/api/drift/trading-history') if (driftRes.ok) { const data = await driftRes.json() if (data.success && data.trades) { setTrades(data.trades) setMessage(data.message || `Found ${data.trades.length} trade(s)`) } else { setTrades([]) setMessage(data.message || 'No trades available') if (data.error) { setError(data.error) } } } else { // API failed - try fallback to local database const res = await fetch('/api/trading-history') if (res.ok) { const data = await res.json() setTrades(data || []) setMessage(data?.length > 0 ? `Found ${data.length} local trade(s)` : 'No trading history available') } else { // Both APIs failed - show empty state setTrades([]) setError('Failed to load trading history from both sources') setMessage('Unable to fetch trading history. Please try again.') } } } catch (error) { console.error('Failed to fetch trades:', error) setTrades([]) setError('Network error while fetching trades') setMessage('Check your connection and try again.') } } useEffect(() => { async function loadTrades() { setLoading(true) await fetchTrades() setLoading(false) } loadTrades() }, []) const getSideColor = (side: string) => { return side.toLowerCase() === 'buy' ? 'text-green-400' : 'text-red-400' } const getStatusColor = (status: string) => { switch (status.toLowerCase()) { case 'filled': return 'text-green-400' case 'pending': return 'text-yellow-400' case 'cancelled': return 'text-red-400' default: return 'text-gray-400' } } const getPnLColor = (pnl?: number) => { if (!pnl) return 'text-gray-400' return pnl >= 0 ? 'text-green-400' : 'text-red-400' } return (

📊 Trading History

{message || `Latest ${trades.length} trades`}
{loading ? (
Loading trades...
) : error ? (
⚠️

Error Loading Trades

{error}

{message}

) : trades.length === 0 ? (
📈

No Trading History

{message || 'Your completed trades will appear here'}

💡 If you recently closed positions with positive P&L, they may take a few minutes to appear

) : (
{trades.map((trade, index) => ( ))}
Asset Side Amount Price Status P&L Time
{trade.symbol.slice(0, 2)}
{trade.symbol}
{trade.side} {trade.amount} ${trade.price.toLocaleString()} {trade.status} {trade.pnl ? `${trade.pnl >= 0 ? '+' : ''}$${trade.pnl.toFixed(2)}` : '--'}
{formatTime(trade.executedAt)}
{formatDate(trade.executedAt)}
)}
) }