New Features: - 📊 Detailed Market Analysis Panel (similar to pro trading interface) * Market sentiment, recommendation, resistance/support levels * Detailed trading setup with entry/exit points * Risk management with R:R ratios and confirmation triggers * Technical indicators (RSI, OBV, VWAP) analysis - 🧠 AI Learning Insights Panel * Real-time learning status and success rates * Winner/Loser trade outcome tracking * AI reflection messages explaining what was learned * Current thresholds and pattern recognition data - 🔮 AI Database Integration * Shows what AI learned from previous trades * Current confidence thresholds and risk parameters * Pattern recognition for symbol/timeframe combinations * Next trade adjustments based on learning - 🎓 Intelligent Learning from Outcomes * Automatic trade outcome analysis (winner/loser) * AI generates learning insights from each trade result * Confidence adjustment based on trade performance * Pattern reinforcement or correction based on results - Beautiful gradient panels with color-coded sections - Clear winner/loser indicators with visual feedback - Expandable detailed analysis view - Real-time learning progress tracking - Completely isolated paper trading (no real money risk) - Real market data integration for authentic learning - Safe practice environment with professional analysis tools This provides a complete AI learning trading simulation where users can: 1. Get real market analysis with detailed reasoning 2. Execute safe paper trades with zero risk 3. See immediate feedback on trade outcomes 4. Learn from AI reflections and insights 5. Understand how AI adapts and improves over time
202 lines
7.9 KiB
JavaScript
202 lines
7.9 KiB
JavaScript
import { NextResponse } from 'next/server'
|
|
import { aiAnalysisService } from '../../../lib/ai-analysis'
|
|
import { progressTracker } from '../../../lib/progress-tracker'
|
|
|
|
export async function POST(request) {
|
|
let sessionId = null
|
|
|
|
try {
|
|
console.log('🔍 Enhanced Screenshot API starting...')
|
|
const body = await request.json()
|
|
console.log('🔍 Enhanced Screenshot API request:', body)
|
|
|
|
// PAPER_TRADING PROTECTION: Block requests that could trigger automation
|
|
if (body.paperTrading || body.enhancedPrompts) {
|
|
console.log('🚨 PAPER_TRADING PROTECTION: Blocking request that could trigger automation')
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'PAPER_TRADING_BLOCK: This API cannot be used from paper trading to prevent real trade execution',
|
|
safety: true
|
|
}, { status: 403 })
|
|
}
|
|
|
|
const config = {
|
|
symbol: body.symbol || 'SOLUSD',
|
|
timeframe: body.timeframe || '240',
|
|
layouts: body.layouts || ['ai', 'diy'],
|
|
analyze: body.analyze === true
|
|
}
|
|
|
|
console.log('🔍 Processed config:', config)
|
|
console.log('🔍 Config.layouts type:', typeof config.layouts)
|
|
console.log('🔍 Config.layouts isArray:', Array.isArray(config.layouts))
|
|
console.log('🔍 Config.layouts length:', config.layouts?.length)
|
|
|
|
// Create session for progress tracking
|
|
const progressSteps = [
|
|
{ id: 'init', title: 'Initialize', description: 'Starting browser sessions...', status: 'pending' },
|
|
{ id: 'auth', title: 'Authentication', description: 'Logging into TradingView', status: 'pending' },
|
|
{ id: 'loading', title: 'Loading Chart', description: 'Loading chart data', status: 'pending' },
|
|
{ id: 'capture', title: 'Capture Screenshot', description: 'Capturing screenshots', status: 'pending' },
|
|
{ id: 'analysis', title: 'AI Analysis', description: 'Running AI analysis', status: 'pending' }
|
|
]
|
|
|
|
sessionId = `screenshot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
|
const progress = progressTracker.createSession(sessionId, progressSteps)
|
|
config.sessionId = sessionId
|
|
|
|
let screenshots = []
|
|
let analysis = null
|
|
|
|
// Capture screenshots using enhanced screenshot service
|
|
try {
|
|
console.log('🚀 Starting enhanced screenshot capture...')
|
|
console.log('📋 Config being passed to captureWithLogin:', JSON.stringify(config, null, 2))
|
|
|
|
// Use dynamic import for TypeScript module
|
|
const { EnhancedScreenshotService } = await import('../../../lib/enhanced-screenshot')
|
|
const enhancedScreenshotService = new EnhancedScreenshotService()
|
|
|
|
// Use captureWithLogin for proper authentication and session management
|
|
const screenshotPaths = await enhancedScreenshotService.captureWithLogin(config)
|
|
|
|
console.log('📸 Raw screenshotPaths result:', screenshotPaths)
|
|
console.log('📸 Type of screenshotPaths:', typeof screenshotPaths)
|
|
console.log('📸 Is screenshotPaths array?', Array.isArray(screenshotPaths))
|
|
|
|
screenshots = screenshotPaths || []
|
|
console.log('📸 Enhanced screenshot capture completed:', screenshots.length, 'files')
|
|
} catch (screenshotError) {
|
|
console.error('❌ Enhanced screenshot capture failed:', screenshotError)
|
|
throw new Error(`Screenshot capture failed: ${screenshotError.message}`)
|
|
}
|
|
|
|
// Run AI analysis if requested
|
|
if (config.analyze && screenshots.length > 0) {
|
|
try {
|
|
console.log('🤖 Starting AI analysis...')
|
|
progressTracker.updateStep(sessionId, 'analysis', 'active', 'Analyzing screenshots...')
|
|
|
|
const analysisConfig = {
|
|
sessionId,
|
|
screenshots,
|
|
symbol: config.symbol,
|
|
timeframe: config.timeframe,
|
|
layouts: config.layouts
|
|
}
|
|
|
|
// Use dynamic import for TypeScript module and call the correct method
|
|
const { aiAnalysisService } = await import('../../../lib/ai-analysis')
|
|
|
|
if (screenshots.length === 1) {
|
|
analysis = await aiAnalysisService.analyzeScreenshot(screenshots[0])
|
|
} else {
|
|
analysis = await aiAnalysisService.analyzeMultipleScreenshots(screenshots)
|
|
}
|
|
|
|
if (analysis) {
|
|
progressTracker.updateStep(sessionId, 'analysis', 'completed', 'Analysis completed successfully')
|
|
console.log('✅ AI analysis completed')
|
|
} else {
|
|
progressTracker.updateStep(sessionId, 'analysis', 'error', 'Analysis failed to return results')
|
|
console.warn('⚠️ AI analysis completed but returned no results')
|
|
}
|
|
|
|
} catch (analysisError) {
|
|
console.error('❌ AI analysis failed:', analysisError)
|
|
progressTracker.updateStep(sessionId, 'analysis', 'error', analysisError.message)
|
|
// Don't throw - return partial results with screenshots
|
|
analysis = { error: analysisError.message }
|
|
}
|
|
}
|
|
|
|
console.log('📸 Final screenshots:', screenshots)
|
|
|
|
const result = {
|
|
success: true,
|
|
sessionId,
|
|
timestamp: Date.now(),
|
|
symbol: config.symbol,
|
|
layouts: config.layouts,
|
|
timeframes: [config.timeframe],
|
|
screenshots,
|
|
analysis,
|
|
message: `Successfully captured ${screenshots.length} screenshot(s)${config.analyze ? ' with AI analysis' : ''}`
|
|
}
|
|
|
|
console.log('✅ Enhanced screenshot API completed successfully')
|
|
return NextResponse.json(result)
|
|
|
|
} catch (error) {
|
|
console.error('❌ Enhanced screenshot API error:', error)
|
|
|
|
if (sessionId) {
|
|
// Mark any active step as error
|
|
const progress = progressTracker.getProgress(sessionId)
|
|
if (progress) {
|
|
const activeStep = progress.steps.find(step => step.status === 'active')
|
|
if (activeStep) {
|
|
progressTracker.updateStep(sessionId, activeStep.id, 'error', error.message)
|
|
}
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: error.message,
|
|
timestamp: Date.now(),
|
|
sessionId
|
|
}, { status: 500 })
|
|
|
|
} finally {
|
|
// CRITICAL: Always run cleanup in finally block
|
|
console.log('🧹 FINALLY BLOCK: Running screenshot service cleanup...')
|
|
|
|
try {
|
|
// Import aggressive cleanup for browser process cleanup
|
|
const aggressiveCleanup = (await import('../../../lib/aggressive-cleanup')).default
|
|
await aggressiveCleanup.forceCleanup()
|
|
console.log('✅ FINALLY BLOCK: Aggressive cleanup completed')
|
|
|
|
// Also run process cleanup to ensure no orphaned browsers
|
|
const { exec } = await import('child_process')
|
|
const { promisify } = await import('util')
|
|
const execAsync = promisify(exec)
|
|
|
|
try {
|
|
await execAsync('pkill -f "chromium|chrome" || true')
|
|
console.log('✅ FINALLY BLOCK: Browser process cleanup completed')
|
|
} catch (cleanupError) {
|
|
console.log('⚠️ FINALLY BLOCK: Browser process cleanup had minor issues:', cleanupError.message)
|
|
}
|
|
const { automatedCleanupService } = await import('../../../lib/automated-cleanup-service')
|
|
await automatedCleanupService.forceCleanup()
|
|
console.log('✅ FINALLY BLOCK: Automated cleanup completed')
|
|
|
|
} catch (cleanupError) {
|
|
console.error('❌ FINALLY BLOCK: Error during cleanup:', cleanupError)
|
|
}
|
|
|
|
// Clean up progress session after delay to allow frontend to read final state
|
|
if (sessionId) {
|
|
setTimeout(() => {
|
|
try {
|
|
progressTracker.deleteSession(sessionId)
|
|
console.log(`🗑️ Cleaned up session ${sessionId}`)
|
|
} catch (sessionCleanupError) {
|
|
console.error('Error cleaning up session:', sessionCleanupError)
|
|
}
|
|
}, 30000) // 30 second delay
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function GET() {
|
|
return NextResponse.json({
|
|
message: 'Enhanced Screenshot API - use POST method for analysis',
|
|
endpoints: {
|
|
POST: '/api/enhanced-screenshot - Run analysis with parameters'
|
|
}
|
|
})
|
|
}
|