/** * Last Trade API Endpoint * * Returns details of the most recent trade */ import { NextResponse } from 'next/server' import { getLastTrade } from '@/lib/database/trades' export async function GET() { try { const trade = await getLastTrade() if (!trade) { return NextResponse.json({ trade: null, }) } // Format the trade data for the frontend // For open positions, use currentSize from Position Manager state if available const configSnapshot = trade.configSnapshot as any const positionManagerState = configSnapshot?.positionManagerState const currentSize = positionManagerState?.currentSize // Use currentSize for open positions (after TP1), fallback to original positionSizeUSD const displaySize = trade.exitReason === null && currentSize ? currentSize : trade.positionSizeUSD const formattedTrade = { id: trade.id, symbol: trade.symbol, direction: trade.direction, entryPrice: trade.entryPrice, entryTime: trade.entryTime.toISOString(), exitPrice: trade.exitPrice || undefined, exitTime: trade.exitTime?.toISOString() || undefined, exitReason: trade.exitReason || undefined, realizedPnL: trade.realizedPnL || undefined, realizedPnLPercent: trade.realizedPnLPercent || undefined, positionSizeUSD: displaySize, // Use current size for open positions leverage: trade.leverage, stopLossPrice: trade.stopLossPrice, takeProfit1Price: trade.takeProfit1Price, takeProfit2Price: trade.takeProfit2Price, isTestTrade: trade.isTestTrade || false, signalQualityScore: trade.signalQualityScore || undefined, } return NextResponse.json({ trade: formattedTrade, }) } catch (error) { console.error('Failed to fetch last trade:', error) return NextResponse.json( { error: 'Failed to fetch last trade' }, { status: 500 } ) } }