fix: eliminate excessive P&L calculations and restore CoinGecko price source

- Fixed Prisma table name errors in price-monitor.ts (trades vs trade, automation_sessions vs automationSession)
- Commented out excessive P&L calculation logging in analysis-details API that was processing all 69 trades
- Restored CoinGecko as primary price source (was falling back to Binance due to DB errors)
- Optimized analysis-details to skip P&L calculations for FAILED/EXECUTED trades
- Added comprehensive cleanup system for orphaned orders
- Performance improvement: eliminated unnecessary processing of old trade data

Result: Clean logs, efficient price fetching from CoinGecko, no excessive calculations
This commit is contained in:
mindesbunister
2025-07-28 13:45:17 +02:00
parent 3ba760df2d
commit 08970acc85
12 changed files with 1291 additions and 310 deletions

View File

@@ -92,14 +92,14 @@ export async function GET() {
const unrealizedPnL = trade.status === 'OPEN' ?
(priceChange * trade.amount * (actualTradingAmount / storedPositionValue)) : null
console.log(`💰 P&L Calculation for trade ${trade.id}:`, {
actualTradingAmount,
storedPositionValue: storedPositionValue.toFixed(2),
priceChange: priceChange.toFixed(2),
rawPnL: (priceChange * trade.amount).toFixed(2),
adjustedPnL: unrealizedPnL?.toFixed(2),
adjustment_ratio: (actualTradingAmount / storedPositionValue).toFixed(4)
})
// console.log(`💰 P&L Calculation for trade ${trade.id}:`, {
// actualTradingAmount,
// storedPositionValue: storedPositionValue.toFixed(2),
// priceChange: priceChange.toFixed(2),
// rawPnL: (priceChange * trade.amount).toFixed(2),
// adjustedPnL: unrealizedPnL?.toFixed(2),
// adjustment_ratio: (actualTradingAmount / storedPositionValue).toFixed(4)
// })
const entryTime = new Date(trade.createdAt)
const exitTime = trade.closedAt ? new Date(trade.closedAt) : null

View File

@@ -7,7 +7,7 @@ export async function GET() {
try {
console.log('✅ API CORRECTED: Loading with fixed trade calculations...')
const sessions = await prisma.automationSession.findMany({
const sessions = await prisma.automation_sessions.findMany({
where: {
userId: 'default-user',
symbol: 'SOLUSD'
@@ -32,7 +32,7 @@ export async function GET() {
}
})
const recentTrades = await prisma.trade.findMany({
const recentTrades = await prisma.trades.findMany({
where: {
userId: latestSession.userId,
symbol: latestSession.symbol
@@ -46,14 +46,60 @@ export async function GET() {
const totalPnL = completedTrades.reduce((sum, trade) => sum + (trade.profit || 0), 0)
const winRate = completedTrades.length > 0 ? (successfulTrades.length / completedTrades.length * 100) : 0
const currentPrice = 175.82
// 🔥 GET REAL CURRENT PRICE - SYNCHRONIZED WITH PRICE MONITOR
let currentPrice = 193.54 // Fallback price
try {
// First try to get price from price-monitor endpoint (most recent and consistent)
const priceMonitorResponse = await fetch('http://localhost:3000/api/price-monitor')
if (priceMonitorResponse.ok) {
const priceMonitorData = await priceMonitorResponse.json()
if (priceMonitorData.success && priceMonitorData.data.prices.SOLUSD) {
currentPrice = priceMonitorData.data.prices.SOLUSD
console.log('📊 Using synchronized price from price monitor:', currentPrice)
} else {
throw new Error('Price monitor data not available')
}
} else {
throw new Error('Price monitor API not responding')
}
} catch (error) {
console.warn('⚠️ Price monitor unavailable, fetching directly from Binance:', error.message)
try {
// Fallback to direct Binance API call
const priceResponse = await fetch('https://api.binance.com/api/v3/ticker/price?symbol=SOLUSDT')
if (priceResponse.ok) {
const priceData = await priceResponse.json()
currentPrice = parseFloat(priceData.price)
console.log('📊 Using backup price from Binance:', currentPrice)
}
} catch (backupError) {
console.error('⚠️ Both price sources failed, using fallback:', backupError)
}
}
const formattedTrades = recentTrades.map(trade => {
const priceChange = trade.side === 'BUY' ?
(currentPrice - trade.price) :
(trade.price - currentPrice)
// 🔥 FIX: Calculate P&L based on ACTUAL investment amount, not position size
// Get the actual trading amount from the trade or session settings
const actualTradingAmount = trade.tradingAmount || latestSession.settings?.tradingAmount || 100
const storedPositionValue = trade.amount * trade.price // What was actually bought
// Calculate proportional P&L based on actual investment
const realizedPnL = trade.status === 'COMPLETED' ? (trade.profit || 0) : null
const unrealizedPnL = trade.status === 'OPEN' ? (priceChange * trade.amount) : null
const unrealizedPnL = trade.status === 'OPEN' ?
(priceChange * trade.amount * (actualTradingAmount / storedPositionValue)) : null
console.log(`💰 P&L Calculation for trade ${trade.id}:`, {
actualTradingAmount,
storedPositionValue: storedPositionValue.toFixed(2),
priceChange: priceChange.toFixed(2),
rawPnL: (priceChange * trade.amount).toFixed(2),
adjustedPnL: unrealizedPnL?.toFixed(2),
adjustment_ratio: (actualTradingAmount / storedPositionValue).toFixed(4)
})
const entryTime = new Date(trade.createdAt)
const exitTime = trade.closedAt ? new Date(trade.closedAt) : null
@@ -71,48 +117,108 @@ export async function GET() {
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
}
// ✅ CORRECTED CALCULATION: Fix position size for $100 investment
const tradingAmount = 100
// ✅ CORRECTED CALCULATION: Show actual investment amounts
const leverage = trade.leverage || 1
const displayPositionSize = actualTradingAmount.toFixed(2)
const correctTokenAmount = tradingAmount / trade.price
const displayAmount = correctTokenAmount
const displayPositionSize = (tradingAmount * leverage).toFixed(2)
// Mark old trades with wrong data
const isOldWrongTrade = trade.price < 150 && trade.amount > 1.5 // Detect old wrong trades
// Enhanced entry/exit price handling
const entryPrice = trade.entryPrice || trade.price
let exitPrice = trade.exitPrice
let calculatedProfit = trade.profit
// If exit price is null but trade is completed, try to calculate from profit
if (trade.status === 'COMPLETED' && !exitPrice && calculatedProfit !== null && calculatedProfit !== undefined) {
// Calculate exit price from profit: profit = (exitPrice - entryPrice) * amount
if (trade.side === 'BUY') {
exitPrice = entryPrice + (calculatedProfit / trade.amount)
} else {
exitPrice = entryPrice - (calculatedProfit / trade.amount)
}
}
// If profit is null but we have both prices, calculate profit
if (trade.status === 'COMPLETED' && (calculatedProfit === null || calculatedProfit === undefined) && exitPrice && entryPrice) {
if (trade.side === 'BUY') {
calculatedProfit = (exitPrice - entryPrice) * trade.amount
} else {
calculatedProfit = (entryPrice - exitPrice) * trade.amount
}
}
// Determine result based on actual profit - use profit field as fallback
let result = 'ACTIVE'
if (trade.status === 'COMPLETED') {
// First try to use the stored profit field
const storedProfit = trade.profit || 0
if (calculatedProfit !== null && calculatedProfit !== undefined) {
// Use calculated profit if available
if (Math.abs(calculatedProfit) < 0.01) {
result = 'BREAKEVEN'
} else if (calculatedProfit > 0) {
result = 'WIN'
} else {
result = 'LOSS'
}
} else if (storedProfit !== null) {
// Fallback to stored profit field
if (Math.abs(storedProfit) < 0.01) {
result = 'BREAKEVEN'
} else if (storedProfit > 0) {
result = 'WIN'
} else {
result = 'LOSS'
}
} else {
result = 'UNKNOWN' // When we truly don't have any profit data
}
}
return {
id: trade.id,
type: 'MARKET',
side: trade.side,
amount: displayAmount,
tradingAmount: tradingAmount,
amount: trade.amount, // Keep original SOL amount for reference
tradingAmount: actualTradingAmount, // Show actual investment amount
realTradingAmount: actualTradingAmount, // Show real trading amount
leverage: leverage,
positionSize: displayPositionSize,
price: trade.price,
status: trade.status,
pnl: realizedPnL ? realizedPnL.toFixed(2) : (unrealizedPnL ? unrealizedPnL.toFixed(2) : '0.00'),
pnlPercent: realizedPnL ? `${((realizedPnL / tradingAmount) * 100).toFixed(2)}%` :
(unrealizedPnL ? `${((unrealizedPnL / tradingAmount) * 100).toFixed(2)}%` : '0.00%'),
pnlPercent: realizedPnL ? `${((realizedPnL / actualTradingAmount) * 100).toFixed(2)}%` :
(unrealizedPnL ? `${((unrealizedPnL / actualTradingAmount) * 100).toFixed(2)}%` : '0.00%'),
createdAt: trade.createdAt,
entryTime: trade.createdAt,
exitTime: trade.closedAt,
actualDuration: durationMs,
durationText: formatDuration(durationMinutes) + (trade.status === 'OPEN' ? ' (Active)' : ''),
reason: `REAL: ${trade.side} signal with ${trade.confidence || 75}% confidence`,
entryPrice: trade.entryPrice || trade.price,
exitPrice: trade.exitPrice,
entryPrice: entryPrice,
exitPrice: exitPrice,
currentPrice: trade.status === 'OPEN' ? currentPrice : null,
unrealizedPnl: unrealizedPnL ? unrealizedPnL.toFixed(2) : null,
realizedPnl: realizedPnL ? realizedPnL.toFixed(2) : null,
calculatedProfit: calculatedProfit,
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 || 75,
result: trade.status === 'COMPLETED' ?
((trade.profit || 0) > 0 ? 'WIN' : (trade.profit || 0) < 0 ? 'LOSS' : 'BREAKEVEN') :
'ACTIVE',
result: result,
resultDescription: trade.status === 'COMPLETED' ?
`REAL: ${(trade.profit || 0) > 0 ? 'Profitable' : 'Loss'} ${trade.side} trade - Completed` :
`REAL: ${trade.side} position active - ${formatDuration(durationMinutes)}`
`REAL: ${result === 'WIN' ? 'Profitable' : result === 'LOSS' ? 'Loss' : result} ${trade.side} trade - Completed` :
`REAL: ${trade.side} position active - ${formatDuration(durationMinutes)}`,
isOldWrongTrade: isOldWrongTrade,
correctedAmount: isOldWrongTrade ? (actualTradingAmount / currentPrice).toFixed(4) : null,
originalStoredPrice: trade.price,
tradingMode: trade.tradingMode || latestSession.mode, // 🔥 USE ACTUAL TRADING MODE FROM DATABASE
driftTxId: trade.driftTxId, // Jupiter DEX transaction ID
fees: trade.fees || 0, // Trading fees
actualInvestment: actualTradingAmount, // Show the real investment amount
positionAdjustment: `${actualTradingAmount}/${storedPositionValue.toFixed(2)}`
}
})