Enhanced trade tracking with proper P&L calculation, timing, and analysis modal

- Fixed P&L calculation with proper realized/unrealized separation
- Added real entry/exit times with accurate duration display
- Enhanced trade cards with proper timing information
- Created trade details modal with comprehensive analysis view
- Added screenshots and AI analysis details to modal
- Fixed win rate calculation based on actual trade results
- Updated trade result classification (WIN/LOSS/ACTIVE)
- Added clickable trade cards with analysis popup
- Created detailed trade analysis API endpoint
- Enhanced P&L display with percentage and realized/unrealized indicators
This commit is contained in:
mindesbunister
2025-07-19 00:37:50 +02:00
parent da0a5c8223
commit 10377810c2
4 changed files with 763 additions and 187 deletions

View File

@@ -43,6 +43,9 @@ export async function GET() {
price: 174.25,
status: 'OPEN',
profit: null,
entryTime: new Date(Date.now() - 30 * 60 * 1000).toISOString(), // 30 minutes ago
exitTime: null,
actualDuration: 30 * 60 * 1000, // 30 minutes in milliseconds
createdAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(), // 30 minutes ago
aiAnalysis: 'BUY signal with 78% confidence - Multi-timeframe bullish alignment',
stopLoss: 172.50,
@@ -89,6 +92,9 @@ export async function GET() {
price: 176.88,
status: 'COMPLETED',
profit: 3.24,
entryTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2 hours ago
exitTime: new Date(Date.now() - 2 * 60 * 60 * 1000 + 85 * 60 * 1000).toISOString(), // 85 minutes later
actualDuration: 85 * 60 * 1000, // 85 minutes in milliseconds
createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2 hours ago
aiAnalysis: 'SELL signal with 85% confidence - Resistance level rejection',
stopLoss: 178.50,
@@ -133,6 +139,9 @@ export async function GET() {
price: 173.15,
status: 'COMPLETED',
profit: -1.89,
entryTime: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(), // 4 hours ago
exitTime: new Date(Date.now() - 4 * 60 * 60 * 1000 + 45 * 60 * 1000).toISOString(), // 45 minutes later
actualDuration: 45 * 60 * 1000, // 45 minutes in milliseconds
createdAt: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(), // 4 hours ago
aiAnalysis: 'BUY signal with 72% confidence - Support level bounce',
stopLoss: 171.80,
@@ -177,6 +186,9 @@ export async function GET() {
price: 175.90,
status: 'COMPLETED',
profit: 1.86,
entryTime: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(), // 6 hours ago
exitTime: new Date(Date.now() - 6 * 60 * 60 * 1000 + 52 * 60 * 1000).toISOString(), // 52 minutes later
actualDuration: 52 * 60 * 1000, // 52 minutes in milliseconds
createdAt: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(), // 6 hours ago
aiAnalysis: 'SELL signal with 81% confidence - Bearish momentum confirmed',
stopLoss: 177.20,
@@ -319,89 +331,138 @@ export async function GET() {
},
// Recent trades
// Recent trades
recentTrades: allTrades.map(trade => ({
id: trade.id,
type: trade.type || 'MARKET',
side: trade.side,
amount: trade.amount,
tradingAmount: trade.tradingAmount || baseTradeAmount, // Use consistent base amount
leverage: trade.leverage || baseLeverage, // Use consistent base leverage
positionSize: trade.positionSize || (trade.tradingAmount || baseTradeAmount) * (trade.leverage || baseLeverage),
price: trade.price,
status: trade.status,
pnl: trade.profit,
pnlPercent: trade.profit ? ((trade.profit / (trade.amount * trade.price)) * 100).toFixed(2) + '%' : null,
createdAt: trade.createdAt,
reason: trade.aiAnalysis || `${trade.side} signal with confidence`,
recentTrades: allTrades.map(trade => {
// Calculate proper P&L based on trade amount and price movement
const currentPrice = trade.status === 'OPEN' ? 175.82 : (trade.exitMetrics?.exitPrice || trade.price)
const priceChange = trade.side === 'BUY' ?
(currentPrice - trade.price) :
(trade.price - currentPrice)
const realizedPnL = trade.status === 'COMPLETED' ?
(trade.profit || (priceChange * trade.amount)) : null
const unrealizedPnL = trade.status === 'OPEN' ?
(priceChange * trade.amount) : null
// Enhanced trade details
entryPrice: trade.price,
currentPrice: trade.status === 'OPEN' ? 175.82 : (trade.exitMetrics?.exitPrice || trade.price),
unrealizedPnl: trade.status === 'OPEN' ?
(trade.side === 'BUY' ?
((175.82 - trade.price) * trade.amount).toFixed(2) :
((trade.price - 175.82) * trade.amount).toFixed(2)) : null,
duration: trade.status === 'COMPLETED' ?
(trade.exitMetrics?.timeInTrade || `${Math.floor((Date.now() - new Date(trade.createdAt).getTime()) / (1000 * 60))} minutes`) :
`${Math.floor((Date.now() - new Date(trade.createdAt).getTime()) / (1000 * 60))} minutes (Active)`,
stopLoss: trade.stopLoss || (trade.side === 'BUY' ? (trade.price * 0.98).toFixed(2) : (trade.price * 1.02).toFixed(2)),
takeProfit: trade.takeProfit || (trade.side === 'BUY' ? (trade.price * 1.04).toFixed(2) : (trade.price * 0.96).toFixed(2)),
isActive: trade.status === 'OPEN' || trade.status === 'PENDING',
confidence: trade.confidence || 102,
// Calculate duration
const entryTime = new Date(trade.entryTime || trade.createdAt)
const exitTime = trade.exitTime ? new Date(trade.exitTime) : null
const currentTime = new Date()
// Enhanced analysis context
triggerAnalysis: trade.triggerAnalysis ? {
decision: trade.triggerAnalysis.decision,
confidence: trade.triggerAnalysis.confidence,
timeframe: trade.triggerAnalysis.timeframe,
keySignals: trade.triggerAnalysis.keySignals,
marketCondition: trade.triggerAnalysis.marketCondition,
riskReward: trade.triggerAnalysis.riskReward,
invalidationLevel: trade.triggerAnalysis.invalidationLevel
} : null,
const durationMs = trade.status === 'COMPLETED' ?
(exitTime ? exitTime.getTime() - entryTime.getTime() : (trade.actualDuration || 0)) :
(currentTime.getTime() - entryTime.getTime())
// Current trade metrics (for active trades)
currentMetrics: trade.currentMetrics ? {
currentPrice: trade.currentMetrics.currentPrice,
priceChange: trade.currentMetrics.priceChange,
priceChangePercent: trade.currentMetrics.priceChangePercent,
timeInTrade: trade.currentMetrics.timeInTrade,
unrealizedPnL: trade.currentMetrics.unrealizedPnL,
unrealizedPnLPercent: trade.currentMetrics.unrealizedPnLPercent,
distanceToSL: trade.currentMetrics.distanceToSL,
distanceToTP: trade.currentMetrics.distanceToTP,
riskRewardActual: trade.currentMetrics.riskRewardActual
} : null,
const durationMinutes = Math.floor(durationMs / (1000 * 60))
const durationHours = Math.floor(durationMinutes / 60)
const remainingMinutes = durationMinutes % 60
// Exit metrics (for completed trades)
exitMetrics: trade.exitMetrics ? {
exitPrice: trade.exitMetrics.exitPrice,
exitReason: trade.exitMetrics.exitReason,
timeInTrade: trade.exitMetrics.timeInTrade,
maxUnrealizedPnL: trade.exitMetrics.maxUnrealizedPnL,
maxDrawdown: trade.exitMetrics.maxDrawdown,
analysisAccuracy: trade.exitMetrics.analysisAccuracy,
actualRiskReward: trade.exitMetrics.actualRiskReward
} : null,
const formatDuration = (minutes) => {
if (minutes < 60) return `${minutes}m`
const hours = Math.floor(minutes / 60)
const mins = minutes % 60
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
}
// Exit conditions
exitConditions: trade.exitConditions ? {
stopLossHit: trade.exitConditions.stopLossHit,
takeProfitHit: trade.exitConditions.takeProfitHit,
manualExit: trade.exitConditions.manualExit,
timeBasedExit: trade.exitConditions.timeBasedExit,
analysisInvalidated: trade.exitConditions.analysisInvalidated
} : null,
// Trade result analysis
result: trade.status === 'COMPLETED' ?
(trade.profit > 0 ? 'PROFIT' : trade.profit < 0 ? 'LOSS' : 'BREAKEVEN') :
'ACTIVE',
resultDescription: trade.status === 'COMPLETED' ?
`${trade.profit > 0 ? 'Successful' : 'Failed'} ${trade.side} trade - ${trade.exitMetrics?.exitReason || 'Completed'}` :
`${trade.side} position active - ${trade.currentMetrics?.timeInTrade || 'Active'}`
}))
return {
id: trade.id,
type: trade.type || 'MARKET',
side: trade.side,
amount: trade.amount,
tradingAmount: trade.tradingAmount || baseTradeAmount,
leverage: trade.leverage || baseLeverage,
positionSize: trade.positionSize || (trade.tradingAmount || baseTradeAmount) * (trade.leverage || baseLeverage),
price: trade.price,
status: trade.status,
pnl: realizedPnL,
pnlPercent: realizedPnL ? ((realizedPnL / (trade.tradingAmount || baseTradeAmount)) * 100).toFixed(2) + '%' : null,
createdAt: trade.createdAt,
// Enhanced timing information
entryTime: trade.entryTime || trade.createdAt,
exitTime: trade.exitTime,
actualDuration: durationMs,
durationText: formatDuration(durationMinutes) + (trade.status === 'OPEN' ? ' (Active)' : ''),
reason: trade.aiAnalysis || `${trade.side} signal with confidence`,
// Enhanced trade details
entryPrice: trade.price,
exitPrice: trade.status === 'COMPLETED' ? (trade.exitMetrics?.exitPrice || currentPrice) : null,
currentPrice: trade.status === 'OPEN' ? currentPrice : null,
unrealizedPnl: unrealizedPnL?.toFixed(2) || null,
realizedPnl: realizedPnL?.toFixed(2) || null,
stopLoss: trade.stopLoss || (trade.side === 'BUY' ? (trade.price * 0.98).toFixed(2) : (trade.price * 1.02).toFixed(2)),
takeProfit: trade.takeProfit || (trade.side === 'BUY' ? (trade.price * 1.04).toFixed(2) : (trade.price * 0.96).toFixed(2)),
isActive: trade.status === 'OPEN' || trade.status === 'PENDING',
confidence: trade.confidence || 102,
// Enhanced analysis context
triggerAnalysis: trade.triggerAnalysis ? {
decision: trade.triggerAnalysis.decision,
confidence: trade.triggerAnalysis.confidence,
timeframe: trade.triggerAnalysis.timeframe,
keySignals: trade.triggerAnalysis.keySignals,
marketCondition: trade.triggerAnalysis.marketCondition,
riskReward: trade.triggerAnalysis.riskReward,
invalidationLevel: trade.triggerAnalysis.invalidationLevel
} : null,
// Current trade metrics (for active trades)
currentMetrics: trade.currentMetrics ? {
currentPrice: trade.currentMetrics.currentPrice,
priceChange: trade.currentMetrics.priceChange,
priceChangePercent: trade.currentMetrics.priceChangePercent,
timeInTrade: formatDuration(durationMinutes),
unrealizedPnL: unrealizedPnL?.toFixed(2) || trade.currentMetrics.unrealizedPnL,
unrealizedPnLPercent: unrealizedPnL ? ((unrealizedPnL / (trade.tradingAmount || baseTradeAmount)) * 100).toFixed(2) + '%' : trade.currentMetrics.unrealizedPnLPercent,
distanceToSL: trade.currentMetrics.distanceToSL,
distanceToTP: trade.currentMetrics.distanceToTP,
riskRewardActual: trade.currentMetrics.riskRewardActual
} : null,
// Exit metrics (for completed trades)
exitMetrics: trade.exitMetrics ? {
exitPrice: trade.exitMetrics.exitPrice,
exitReason: trade.exitMetrics.exitReason,
timeInTrade: formatDuration(durationMinutes),
maxUnrealizedPnL: trade.exitMetrics.maxUnrealizedPnL,
maxDrawdown: trade.exitMetrics.maxDrawdown,
analysisAccuracy: trade.exitMetrics.analysisAccuracy,
actualRiskReward: trade.exitMetrics.actualRiskReward
} : null,
// Exit conditions
exitConditions: trade.exitConditions ? {
stopLossHit: trade.exitConditions.stopLossHit,
takeProfitHit: trade.exitConditions.takeProfitHit,
manualExit: trade.exitConditions.manualExit,
timeBasedExit: trade.exitConditions.timeBasedExit,
analysisInvalidated: trade.exitConditions.analysisInvalidated
} : null,
// Trade result analysis
result: trade.status === 'COMPLETED' ?
(realizedPnL > 0 ? 'WIN' : realizedPnL < 0 ? 'LOSS' : 'BREAKEVEN') :
'ACTIVE',
resultDescription: trade.status === 'COMPLETED' ?
`${realizedPnL > 0 ? 'Profitable' : 'Loss'} ${trade.side} trade - ${trade.exitMetrics?.exitReason || 'Completed'}` :
`${trade.side} position active - ${formatDuration(durationMinutes)}`,
// Screenshots and analysis data for modal
screenshots: [
`/api/screenshots/analysis-${trade.id}-ai-layout.png`,
`/api/screenshots/analysis-${trade.id}-diy-layout.png`,
`/api/screenshots/analysis-${trade.id}-overview.png`
],
analysisData: {
timestamp: trade.entryTime || trade.createdAt,
layoutsAnalyzed: ['AI Layout', 'DIY Layout'],
timeframesAnalyzed: ['15m', '1h', '2h', '4h'],
processingTime: '2.3 minutes',
tokensUsed: Math.floor(Math.random() * 2000) + 3000
}
}
})
}
})
} catch (error) {