- Modified /api/analytics/last-trade to extract currentSize from configSnapshot.positionManagerState - For open positions (exitReason === null), displays runner size after TP1 instead of original positionSizeUSD - Falls back to original positionSizeUSD for closed positions or when Position Manager state unavailable - Fixes UI showing 2.54 when actual runner is 2.59 - Provides accurate exposure visibility on analytics dashboard Example: Position opens at 2.54, TP1 closes 70% → runner 2.59 → UI now shows 2.59
62 lines
1.9 KiB
TypeScript
62 lines
1.9 KiB
TypeScript
/**
|
|
* 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 }
|
|
)
|
|
}
|
|
}
|