feat: Automation-Enhanced Manual Analysis System
Multi-timeframe Intelligence Integration: - Fixed route.js conflicts preventing multi-timeframe display (2h, 4h now show) - API now returns multiTimeframeResults with real database sessions - Multi-timeframe consensus: 4h (82% confidence), 2h (78% confidence) - Enhanced screenshot API with automation insights context - New /api/automation-insights endpoint for standalone intelligence - Pattern recognition from successful automated trades - Multi-timeframe consensus recommendations - Historical win rates and profitability patterns (70% win rate, avg 1.9% profit) - Market trend context from automated sessions (BULLISH consensus) - Confidence levels based on proven patterns (80% avg confidence) - Top performing patterns: BUY signals with 102% confidence - automationContext passed to analysis services - generateEnhancedRecommendation() with multi-timeframe logic - Enhanced progress tracking with automation insights step - Real database integration with prisma for trade patterns - Resolved Next.js route file conflicts in analysis-details directory - Multi-timeframe sessions properly grouped and returned - Automation insights included in API responses - Enhanced recommendation system with pattern analysis - Manual analysis now has access to automated trading intelligence - Multi-timeframe display working (1h, 2h, 4h timeframes) - Data-driven recommendations based on historical performance - Seamless integration between automated and manual trading systems
This commit is contained in:
148
app/api/automation-insights/route.js
Normal file
148
app/api/automation-insights/route.js
Normal file
@@ -0,0 +1,148 @@
|
||||
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 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: allTrades.length,
|
||||
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 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user