Files
trading_bot_v3/app/api/batch-analysis/route.js
mindesbunister a062bae8e2 feat: Complete sync fixes with batch analysis and security improvements
- Implement batch comparative analysis system for multi-timeframe insights
- Add comprehensive credential redaction for security (safe-logging.ts)
- Fix TypeScript compilation errors and interface compatibility
- Remove marketing text from analysis UI as requested
- Add concurrency protection to prevent analysis process overlap
- Fix duplicate screenshot display in gallery components
- All systems now working with successful build completion
2025-07-17 14:58:47 +02:00

186 lines
6.5 KiB
JavaScript

import { NextResponse } from 'next/server'
import { enhancedScreenshotService } from '../../../lib/enhanced-screenshot'
import { aiAnalysisService } from '../../../lib/ai-analysis'
import { progressTracker } from '../../../lib/progress-tracker'
export async function POST(request) {
try {
const body = await request.json()
const {
symbol,
timeframes = [],
layouts = ['ai'],
sessionId: providedSessionId
} = body
console.log('🎯 Batch analysis request:', { symbol, timeframes, layouts })
// Use provided sessionId or generate one
const sessionId = providedSessionId || `batch_analysis_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
console.log('🔍 Using batch session ID:', sessionId)
// Create progress tracking with batch-specific steps
const totalCaptures = timeframes.length * layouts.length
const initialSteps = [
{
id: 'init',
title: 'Initializing Batch Analysis',
description: `Preparing to capture ${totalCaptures} screenshots across ${timeframes.length} timeframes`,
status: 'pending'
},
{
id: 'auth',
title: 'TradingView Authentication',
description: 'Logging into TradingView accounts',
status: 'pending'
},
{
id: 'batch_capture',
title: 'Batch Screenshot Capture',
description: `Capturing screenshots for all ${timeframes.length} timeframes`,
status: 'pending'
},
{
id: 'comparative_analysis',
title: 'Comparative AI Analysis',
description: `Analyzing all ${totalCaptures} screenshots together for timeframe comparison`,
status: 'pending'
}
]
// Create the progress session
progressTracker.createSession(sessionId, initialSteps)
const allScreenshots = []
const timeframeResults = []
try {
// Mark init as completed
progressTracker.updateStep(sessionId, 'init', 'completed', 'Batch analysis initialized')
progressTracker.updateStep(sessionId, 'auth', 'active', 'Starting authentication...')
// Capture screenshots for each timeframe WITHOUT analysis
for (let i = 0; i < timeframes.length; i++) {
const timeframe = timeframes[i]
console.log(`📸 Capturing ${timeframe} screenshots (${i + 1}/${timeframes.length})...`)
// Update progress
progressTracker.updateStep(sessionId, 'batch_capture', 'active',
`Capturing ${timeframe} screenshots (${i + 1}/${timeframes.length})`)
const config = {
symbol: symbol || 'BTCUSD',
timeframe: timeframe,
layouts: layouts,
sessionId: `${sessionId}_tf_${timeframe}`, // Sub-session for this timeframe
credentials: {
email: process.env.TRADINGVIEW_EMAIL,
password: process.env.TRADINGVIEW_PASSWORD
}
}
try {
// Capture screenshots only (no analysis)
const screenshots = await enhancedScreenshotService.captureWithLogin(config)
allScreenshots.push(...screenshots)
timeframeResults.push({
timeframe,
screenshots: screenshots.length,
files: screenshots
})
console.log(`${timeframe}: ${screenshots.length} screenshots captured`)
} catch (error) {
console.error(`❌ Failed to capture ${timeframe}:`, error)
timeframeResults.push({
timeframe,
error: error.message,
screenshots: 0,
files: []
})
}
}
// Mark capture as completed
progressTracker.updateStep(sessionId, 'batch_capture', 'completed',
`All timeframes captured: ${allScreenshots.length} total screenshots`)
// Now perform comparative analysis on ALL screenshots
console.log(`🤖 Starting comparative analysis of ${allScreenshots.length} screenshots...`)
progressTracker.updateStep(sessionId, 'comparative_analysis', 'active',
`Analyzing ${allScreenshots.length} screenshots for timeframe comparison`)
let analysis = null
if (allScreenshots.length > 0) {
try {
// Use the analyzeMultipleScreenshots method for comparative analysis
analysis = await aiAnalysisService.analyzeMultipleScreenshots(allScreenshots)
if (analysis) {
progressTracker.updateStep(sessionId, 'comparative_analysis', 'completed',
'Comparative analysis completed successfully!')
} else {
progressTracker.updateStep(sessionId, 'comparative_analysis', 'error',
'Analysis returned no results')
}
} catch (analysisError) {
console.error('❌ Comparative analysis failed:', analysisError)
progressTracker.updateStep(sessionId, 'comparative_analysis', 'error',
`Analysis failed: ${analysisError.message}`)
}
} else {
progressTracker.updateStep(sessionId, 'comparative_analysis', 'error',
'No screenshots available for analysis')
}
// Cleanup session after delay
setTimeout(() => progressTracker.deleteSession(sessionId), 5000)
const result = {
success: true,
sessionId,
type: 'batch_comparative',
symbol: symbol || 'BTCUSD',
timeframes,
layouts,
totalScreenshots: allScreenshots.length,
screenshots: allScreenshots,
timeframeBreakdown: timeframeResults,
analysis,
summary: `Captured ${allScreenshots.length} screenshots across ${timeframes.length} timeframes for comparative analysis`
}
console.log('✅ Batch comparative analysis completed:', {
timeframes: timeframes.length,
screenshots: allScreenshots.length,
hasAnalysis: !!analysis
})
return NextResponse.json(result)
} catch (error) {
console.error('❌ Batch analysis error:', error)
progressTracker.updateStep(sessionId, 'comparative_analysis', 'error',
`Batch analysis failed: ${error.message}`)
return NextResponse.json({
success: false,
error: error.message,
sessionId,
partialResults: {
timeframeResults,
screenshotsCaptured: allScreenshots.length
}
}, { status: 500 })
}
} catch (error) {
console.error('❌ Batch analysis request error:', error)
return NextResponse.json({
success: false,
error: error.message
}, { status: 500 })
}
}