Files
trading_bot_v3/app/api/automation-insights/route.js
mindesbunister 71e1a64b5d fix: correct entry prices and position sizing in trading system
- Fixed automation service to use real SOL price (~89) instead of hardcoded 00
- Updated position size calculation to properly convert USD investment to token amount
- Enhanced trade display to show separate entry/exit prices with price difference
- Added data quality warnings for trades with missing exit data
- Updated API to use current SOL price (189.50) and improved trade result determination
- Added detection and warnings for old trades with incorrect price data

Resolves issue where trades showed 9-100 entry prices instead of real SOL price of 89
and position sizes of 2.04 SOL instead of correct ~0.53 SOL for 00 investment
2025-07-21 09:26:48 +02:00

157 lines
5.9 KiB
JavaScript

import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Generate enhanced recommendations based on automation insights
function generateEnhancedRecommendation(automationContext) {
if (!automationContext) return null
const { multiTimeframeSignals, topPatterns, marketContext } = automationContext
// Multi-timeframe consensus
const signals = multiTimeframeSignals.filter(s => s.decision)
const bullishSignals = signals.filter(s => s.decision === 'BUY').length
const bearishSignals = signals.filter(s => s.decision === 'SELL').length
// Pattern strength
const avgWinRate = signals.length > 0 ?
signals.reduce((sum, s) => sum + (s.winRate || 0), 0) / signals.length : 0
// Profitability insights
const avgProfit = topPatterns.length > 0 ?
topPatterns.reduce((sum, p) => sum + Number(p.profitPercent || 0), 0) / topPatterns.length : 0
let recommendation = '🤖 AUTOMATION-ENHANCED: '
if (bullishSignals > bearishSignals) {
recommendation += `BULLISH CONSENSUS (${bullishSignals}/${signals.length} timeframes)`
if (avgWinRate > 60) recommendation += ` ✅ Strong pattern (${avgWinRate.toFixed(1)}% win rate)`
if (avgProfit > 3) recommendation += ` 💰 High profit potential (~${avgProfit.toFixed(1)}%)`
} else if (bearishSignals > bullishSignals) {
recommendation += `BEARISH CONSENSUS (${bearishSignals}/${signals.length} timeframes)`
} else {
recommendation += 'NEUTRAL - Mixed signals across timeframes'
}
return recommendation
}
export async function GET(request) {
try {
const { searchParams } = new URL(request.url)
const symbol = searchParams.get('symbol') || 'SOLUSD'
console.log('🧠 Getting automation insights for manual analysis:', symbol)
// Get recent automation sessions for context
const sessions = await prisma.automationSession.findMany({
where: {
userId: 'default-user',
symbol: symbol,
lastAnalysisData: { not: null }
},
orderBy: { createdAt: 'desc' },
take: 3
})
// Get top performing trades for pattern recognition
const successfulTrades = await prisma.trade.findMany({
where: {
userId: 'default-user',
symbol: symbol,
status: 'COMPLETED',
profit: { gt: 0 }
},
orderBy: { profit: 'desc' },
take: 5
})
// Get actual total trades count for consistency
const totalTradesCount = await prisma.trade.count({
where: {
userId: 'default-user',
symbol: symbol
}
})
// Get recent market context
const allTrades = await prisma.trade.findMany({
where: {
userId: 'default-user',
symbol: symbol,
status: 'COMPLETED'
},
orderBy: { createdAt: 'desc' },
take: 10
})
const recentPnL = allTrades.reduce((sum, t) => sum + (t.profit || 0), 0)
const winningTrades = allTrades.filter(t => (t.profit || 0) > 0)
const winRate = allTrades.length > 0 ? (winningTrades.length / allTrades.length * 100) : 0
const automationContext = {
multiTimeframeSignals: sessions.map(s => ({
timeframe: s.timeframe,
decision: s.lastAnalysisData?.decision,
confidence: s.lastAnalysisData?.confidence,
sentiment: s.lastAnalysisData?.sentiment,
winRate: s.winRate,
totalPnL: s.totalPnL,
totalTrades: s.totalTrades
})),
topPatterns: successfulTrades.map(t => ({
side: t.side,
profit: t.profit,
confidence: t.confidence,
entryPrice: t.price,
exitPrice: t.exitPrice,
profitPercent: t.exitPrice ? ((t.exitPrice - t.price) / t.price * 100).toFixed(2) : null
})),
marketContext: {
recentPnL,
winRate: winRate.toFixed(1),
totalTrades: totalTradesCount, // Use actual total count
avgProfit: allTrades.length > 0 ? (recentPnL / allTrades.length).toFixed(2) : 0,
trend: sessions.length > 0 ? sessions[0].lastAnalysisData?.sentiment : 'NEUTRAL'
}
}
const insights = {
multiTimeframeConsensus: automationContext.multiTimeframeSignals.length > 0 ?
automationContext.multiTimeframeSignals[0].decision : null,
avgConfidence: automationContext.multiTimeframeSignals.length > 0 ?
(automationContext.multiTimeframeSignals.reduce((sum, s) => sum + (s.confidence || 0), 0) / automationContext.multiTimeframeSignals.length).toFixed(1) : null,
marketTrend: automationContext.marketContext.trend,
winRate: automationContext.marketContext.winRate + '%',
profitablePattern: automationContext.topPatterns.length > 0 ?
`${automationContext.topPatterns[0].side} signals with avg ${automationContext.topPatterns.reduce((sum, p) => sum + Number(p.profitPercent || 0), 0) / automationContext.topPatterns.length}% profit` : null,
recommendation: generateEnhancedRecommendation(automationContext),
timeframeAnalysis: automationContext.multiTimeframeSignals,
topPerformingPatterns: automationContext.topPatterns.slice(0, 3),
marketMetrics: automationContext.marketContext
}
return NextResponse.json({
success: true,
symbol: symbol,
automationInsights: insights,
enhancementSummary: {
timeframesAnalyzed: automationContext.multiTimeframeSignals.length,
patternsFound: automationContext.topPatterns.length,
totalTradesAnalyzed: automationContext.marketContext.totalTrades,
overallConfidence: insights.avgConfidence ? insights.avgConfidence + '%' : 'N/A'
},
message: `🧠 Automation insights gathered for ${symbol} manual analysis enhancement`
})
} catch (error) {
console.error('Error getting automation insights:', error)
return NextResponse.json({
success: false,
error: 'Failed to get automation insights',
message: error.message
}, { status: 500 })
}
}