Files
trading_bot_v3/app/api/analyze/route.ts
mindesbunister cf58d41444 🔐 Implement robust session persistence to avoid 'are you human' captcha checks
- Add comprehensive session persistence with cookies, localStorage, and sessionStorage
- Implement stealth browser features to reduce bot detection
- Add smartLogin() method that prioritizes saved sessions over fresh logins
- Create session management utilities (refresh, clear, test validity)
- Update enhanced screenshot service to use session persistence
- Add comprehensive documentation and test script
- Support manual login fallback when captcha is encountered
- Sessions stored in .tradingview-session/ directory for Docker compatibility

This solves the captcha problem by avoiding repeated logins through persistent sessions.
2025-07-12 21:39:53 +02:00

85 lines
3.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { aiAnalysisService } from '../../../lib/ai-analysis'
import { enhancedScreenshotService } from '../../../lib/enhanced-screenshot'
import { settingsManager } from '../../../lib/settings'
import path from 'path'
import fs from 'fs'
export async function POST(req: NextRequest) {
try {
const { symbol, layouts, timeframe, useExisting } = await req.json()
// Load current settings
const settings = await settingsManager.loadSettings()
// Use provided values or fall back to saved settings
const finalSymbol = symbol || settings.symbol
const finalTimeframe = timeframe || settings.timeframe
const finalLayouts = layouts || settings.layouts
if (!finalSymbol) {
return NextResponse.json({ error: 'Missing symbol' }, { status: 400 })
}
let screenshots: string[] = []
// If useExisting is true, find existing screenshots
if (useExisting) {
console.log('Using existing screenshots for analysis...')
const screenshotsDir = path.join(process.cwd(), 'screenshots')
const allFiles = await fs.promises.readdir(screenshotsDir)
// Find screenshots matching the symbol and timeframe
const matchingFiles = allFiles.filter(file =>
file.includes(finalSymbol) &&
file.includes(finalTimeframe) &&
file.endsWith('.png') &&
!file.includes('debug')
)
if (matchingFiles.length > 0) {
// Use the most recent screenshots (limit to 3 for analysis)
screenshots = matchingFiles
.sort((a, b) => b.localeCompare(a)) // Sort by name (which includes timestamp)
.slice(0, 3)
.map(file => path.join(screenshotsDir, file))
} else {
return NextResponse.json({ error: `No existing screenshots found for ${finalSymbol} ${finalTimeframe}` }, { status: 404 })
}
} else {
// Original behavior - capture new screenshots
const baseFilename = `${finalSymbol}_${finalTimeframe}_${Date.now()}`
screenshots = await enhancedScreenshotService.capture(finalSymbol, `${baseFilename}.png`, finalLayouts, finalTimeframe)
}
let result
// For now, always use single screenshot analysis to debug the issue
if (screenshots.length > 0) {
// Always use single screenshot analysis - get the first/most recent screenshot
const filename = path.basename(screenshots[0])
console.log(`Analyzing single screenshot: ${filename}`)
result = await aiAnalysisService.analyzeScreenshot(filename)
} else {
return NextResponse.json({ error: 'No screenshots available for analysis' }, { status: 404 })
}
if (!result) {
return NextResponse.json({ error: 'Analysis failed' }, { status: 500 })
}
return NextResponse.json({
...result,
layoutsAnalyzed: finalLayouts,
settings: {
symbol: finalSymbol,
timeframe: finalTimeframe,
layouts: finalLayouts
},
screenshots: screenshots.map((s: string) => path.basename(s)),
usedExisting: useExisting || false
})
} catch (e: any) {
return NextResponse.json({ error: e.message }, { status: 500 })
}
}