Files
trading_bot_v3/app/api/automation/trade-details/[id]/route.js
mindesbunister 10377810c2 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
2025-07-19 00:37:50 +02:00

323 lines
10 KiB
JavaScript

import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import fs from 'fs'
import path from 'path'
const prisma = new PrismaClient()
export async function GET(request, { params }) {
try {
const { id } = params
// Mock detailed trade data with screenshots
const mockTradeDetails = {
'demo-trade-1': {
id: 'demo-trade-1',
side: 'BUY',
amount: 1.5,
tradingAmount: 100,
leverage: 1,
positionSize: 100,
price: 174.25,
status: 'OPEN',
entryTime: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
exitTime: null,
confidence: 78,
// Analysis screenshots
screenshots: {
aiLayout: {
url: '/screenshots/demo-trade-1-ai-layout.png',
title: 'AI Layout Analysis',
description: 'Multi-timeframe analysis showing BUY signal with RSI oversold and MACD bullish crossover'
},
diyLayout: {
url: '/screenshots/demo-trade-1-diy-layout.png',
title: 'DIY Layout Analysis',
description: 'Custom indicators showing support bounce confirmation and volume spike'
},
overview: {
url: '/screenshots/demo-trade-1-overview.png',
title: 'Market Overview',
description: 'Full market context with key levels and trend analysis'
}
},
// Detailed analysis that triggered the trade
detailedAnalysis: {
timestamp: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
decision: 'BUY',
confidence: 78,
overallSentiment: 'BULLISH',
// Multi-timeframe analysis
timeframes: {
'15m': {
decision: 'BUY',
confidence: 75,
signals: ['RSI oversold (28)', 'Price bouncing from support'],
trend: 'BULLISH'
},
'1h': {
decision: 'BUY',
confidence: 80,
signals: ['MACD bullish crossover', 'Volume spike on bounce'],
trend: 'BULLISH'
},
'2h': {
decision: 'BUY',
confidence: 72,
signals: ['Support level holding', 'Bullish divergence'],
trend: 'NEUTRAL'
},
'4h': {
decision: 'BUY',
confidence: 75,
signals: ['Higher lows pattern', 'EMA support'],
trend: 'BULLISH'
}
},
// Key levels identified
keyLevels: {
entry: {
price: 174.25,
rationale: 'Support bounce with high volume confirmation'
},
stopLoss: {
price: 172.50,
rationale: 'Below key support level with 1% risk'
},
takeProfit: {
price: 178.00,
rationale: 'Previous resistance level with 2.2:1 R/R ratio'
}
},
// Risk management
riskManagement: {
riskReward: '1:2.2',
riskPercentage: 1.75,
positionSize: 100,
maxDrawdown: 1.75,
expectedValue: 'Positive based on historical similar setups'
},
// Technical indicators
technicalIndicators: {
rsi: {
value: 28,
interpretation: 'Oversold - potential reversal signal'
},
macd: {
value: 0.125,
interpretation: 'Bullish crossover - momentum building'
},
volume: {
value: 'Above average',
interpretation: 'Strong buying interest at support'
},
movingAverages: {
ema20: 173.85,
ema50: 172.90,
interpretation: 'Price above key EMAs - bullish structure'
}
},
// Market context
marketContext: {
overallTrend: 'BULLISH',
marketPhase: 'Correction within uptrend',
volatility: 'Moderate',
newsEvents: 'No major events expected',
correlations: 'Positive correlation with crypto market'
},
// AI reasoning
aiReasoning: `
Multi-timeframe analysis indicates a high-probability BUY setup:
1. Technical Setup: RSI oversold (28) with MACD bullish crossover
2. Price Action: Clean bounce from key support level at 174.00
3. Volume Confirmation: Above-average volume on the bounce
4. Risk/Reward: Excellent 1:2.2 ratio with clear stop loss
5. Market Context: Correction within overall bullish trend
The combination of oversold conditions, support bounce, and volume confirmation
provides a high-confidence entry point with favorable risk/reward.
`,
// Execution plan
executionPlan: {
entry: 'Market buy at 174.25',
stopLoss: 'Set at 172.50 (1.75% risk)',
takeProfit: 'Target 178.00 (2.2:1 R/R)',
positionSize: '$100 with 1x leverage',
monitoring: 'Monitor for volume continuation and trend strength'
}
}
},
'demo-trade-2': {
id: 'demo-trade-2',
side: 'SELL',
amount: 2.04,
tradingAmount: 100,
leverage: 1,
positionSize: 100,
price: 176.88,
status: 'COMPLETED',
entryTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
exitTime: new Date(Date.now() - 2 * 60 * 60 * 1000 + 85 * 60 * 1000).toISOString(),
confidence: 85,
profit: 3.24,
screenshots: {
aiLayout: {
url: '/screenshots/demo-trade-2-ai-layout.png',
title: 'AI Layout Analysis',
description: 'Resistance rejection pattern with RSI overbought and bearish divergence'
},
diyLayout: {
url: '/screenshots/demo-trade-2-diy-layout.png',
title: 'DIY Layout Analysis',
description: 'Distribution pattern at key resistance with volume confirmation'
},
overview: {
url: '/screenshots/demo-trade-2-overview.png',
title: 'Market Overview',
description: 'Clear resistance level rejection with bearish momentum building'
}
},
detailedAnalysis: {
timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
decision: 'SELL',
confidence: 85,
overallSentiment: 'BEARISH',
timeframes: {
'15m': {
decision: 'SELL',
confidence: 88,
signals: ['RSI overbought (72)', 'Resistance rejection'],
trend: 'BEARISH'
},
'1h': {
decision: 'SELL',
confidence: 85,
signals: ['Bearish divergence', 'Volume on rejection'],
trend: 'BEARISH'
},
'2h': {
decision: 'SELL',
confidence: 80,
signals: ['Distribution pattern', 'Lower highs'],
trend: 'BEARISH'
},
'4h': {
decision: 'SELL',
confidence: 82,
signals: ['Key resistance level', 'Momentum shift'],
trend: 'BEARISH'
}
},
keyLevels: {
entry: {
price: 176.88,
rationale: 'Resistance rejection with high volume'
},
stopLoss: {
price: 178.50,
rationale: 'Above resistance with 0.9% risk'
},
takeProfit: {
price: 174.20,
rationale: 'Support level with 1.6:1 R/R ratio'
}
},
riskManagement: {
riskReward: '1:1.6',
riskPercentage: 0.9,
positionSize: 100,
maxDrawdown: 0.9,
expectedValue: 'Positive based on resistance rejection pattern'
},
technicalIndicators: {
rsi: {
value: 72,
interpretation: 'Overbought - potential reversal signal'
},
macd: {
value: -0.085,
interpretation: 'Bearish divergence - momentum weakening'
},
volume: {
value: 'High on rejection',
interpretation: 'Strong selling pressure at resistance'
},
movingAverages: {
ema20: 176.45,
ema50: 175.20,
interpretation: 'Resistance at key EMA levels'
}
},
marketContext: {
overallTrend: 'BEARISH',
marketPhase: 'Distribution at resistance',
volatility: 'Moderate',
newsEvents: 'No major events',
correlations: 'Negative correlation with broader market'
},
aiReasoning: `
High-confidence SELL setup based on resistance rejection:
1. Technical Setup: RSI overbought (72) with bearish divergence
2. Price Action: Clear rejection at key resistance level
3. Volume Confirmation: High volume on the rejection candle
4. Risk/Reward: Good 1:1.6 ratio with tight stop loss
5. Market Context: Distribution pattern at resistance
The combination of overbought conditions, resistance rejection, and volume
confirmation provides excellent entry with favorable risk/reward profile.
`,
executionPlan: {
entry: 'Market sell at 176.88',
stopLoss: 'Set at 178.50 (0.9% risk)',
takeProfit: 'Target 174.20 (1.6:1 R/R)',
positionSize: '$100 with 1x leverage',
monitoring: 'Monitor for break below support levels'
}
}
}
}
const tradeDetails = mockTradeDetails[id]
if (!tradeDetails) {
return NextResponse.json({
success: false,
error: 'Trade not found'
}, { status: 404 })
}
return NextResponse.json({
success: true,
data: tradeDetails
})
} catch (error) {
console.error('Error fetching trade details:', error)
return NextResponse.json({
success: false,
error: 'Failed to fetch trade details'
}, { status: 500 })
}
}