"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 } interface DataSource { name: string available: boolean description: string } interface DataStatus { status: string sources: DataSource[] recommendations: string[] } interface RealtimeStatus { isActive: boolean tradesCount: number lastTradeTime?: string } 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) const [dataStatus, setDataStatus] = useState(null) const [showStatus, setShowStatus] = useState(false) const [realtimeStatus, setRealtimeStatus] = useState(null) const [realtimeLoading, setRealtimeLoading] = 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.') } } const fetchDataStatus = async () => { try { const response = await fetch('/api/drift/data-status') if (response.ok) { const status = await response.json() setDataStatus(status) } } catch (error) { console.error('Failed to fetch data status:', error) } } const fetchRealtimeStatus = async () => { try { const response = await fetch('/api/drift/realtime-monitoring') if (response.ok) { const data = await response.json() setRealtimeStatus(data.status) } } catch (error) { console.error('Failed to fetch realtime status:', error) } } const handleRealtimeToggle = async () => { try { setRealtimeLoading(true) const action = realtimeStatus?.isActive ? 'stop' : 'start' const response = await fetch('/api/drift/realtime-monitoring', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) }) if (response.ok) { const data = await response.json() setRealtimeStatus(data.status) setMessage(data.message) // If we started monitoring, refresh trades after a moment if (action === 'start') { setTimeout(async () => { await fetchTrades() }, 2000) } } else { const errorData = await response.json() setError(errorData.error || 'Failed to toggle real-time monitoring') } } catch (error) { console.error('Real-time toggle error:', error) setError('Error toggling real-time monitoring') } finally { setRealtimeLoading(false) } } const handleClearRealtimeCache = async () => { try { const response = await fetch('/api/drift/realtime-monitoring', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'clear' }) }) if (response.ok) { const data = await response.json() setRealtimeStatus(data.status) setMessage(data.message) await fetchTrades() // Refresh to show cleared state } } catch (error) { console.error('Clear cache error:', error) setError('Error clearing real-time cache') } } useEffect(() => { async function loadTrades() { setLoading(true) await fetchTrades() await fetchDataStatus() await fetchRealtimeStatus() 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`} {realtimeStatus?.isActive && realtimeStatus.tradesCount > 0 && ( )}
{showStatus && dataStatus && (

Data Source Status: {dataStatus.status}

{/* Real-time Monitoring Status */} {realtimeStatus && (

Real-time Monitoring

{realtimeStatus.isActive ? 'đŸŸĸ ACTIVE' : '🔴 INACTIVE'}
Tracked Trades: {realtimeStatus.tradesCount}
Last Activity: {realtimeStatus.lastTradeTime ? formatTime(realtimeStatus.lastTradeTime) : 'None' }
{realtimeStatus.isActive && (

📡 Monitoring for new trades automatically

)}
)}
{dataStatus.sources.map((source, index) => (
{source.name}

{source.description}

{source.available ? 'Available' : 'Limited'}
))}

Important Notes:

    {dataStatus.recommendations.map((rec, index) => (
  • â€ĸ {rec}
  • ))}
)} {loading ? (
Loading trades...
) : error ? (
âš ī¸

Error Loading Trades

{error}

{message}

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

No Trading History Available

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

💡 Why no history?

  • â€ĸ Complete historical trading data is not publicly accessible via Drift APIs
  • â€ĸ Only current positions and recent fills are available
  • â€ĸ Historical S3 data stopped updating in January 2025

📋 For full trade history:

  • â€ĸ Visit the official Drift app
  • â€ĸ Enable real-time monitoring for future trades
  • â€ĸ Click "Status" above for detailed data source information
) : (
{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)}
)}
) }