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
259 lines
8.8 KiB
JavaScript
259 lines
8.8 KiB
JavaScript
import { NextResponse } from 'next/server'
|
|
|
|
export async function POST(request) {
|
|
try {
|
|
const { symbol, timeframe, layouts, currentBalance } = await request.json()
|
|
|
|
console.log('🛡️ Enhanced Anti-Chasing Analysis Started')
|
|
console.log(`📊 Request: ${symbol} ${timeframe} [${layouts?.join(', ')}]`)
|
|
console.log(`💰 Account Balance: $${currentBalance}`)
|
|
|
|
// Validate inputs
|
|
if (!symbol || !timeframe) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Symbol and timeframe are required'
|
|
}, { status: 400 })
|
|
}
|
|
|
|
// Dynamic imports to handle TypeScript files
|
|
const { EnhancedAntiChasingAI } = await import('../../../lib/enhanced-anti-chasing-ai')
|
|
const { EnhancedRiskManager } = await import('../../../lib/enhanced-risk-manager')
|
|
|
|
try {
|
|
// Capture fresh screenshots for analysis
|
|
console.log('📸 Capturing fresh screenshots...')
|
|
|
|
const screenshotResponse = await fetch(`${process.env.NEXTAUTH_URL || 'http://localhost:3000'}/api/enhanced-screenshot`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
symbol,
|
|
timeframe,
|
|
layouts: layouts || ['ai', 'diy'],
|
|
analyze: false // We'll do our own analysis
|
|
})
|
|
})
|
|
|
|
if (!screenshotResponse.ok) {
|
|
const errorText = await screenshotResponse.text()
|
|
console.error('❌ Screenshot capture failed:', errorText)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to capture fresh screenshots',
|
|
details: errorText
|
|
}, { status: 500 })
|
|
}
|
|
|
|
const screenshotData = await screenshotResponse.json()
|
|
const screenshots = screenshotData.screenshots || []
|
|
|
|
if (screenshots.length === 0) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'No screenshots captured',
|
|
suggestion: 'Check screenshot service configuration'
|
|
}, { status: 404 })
|
|
}
|
|
|
|
console.log(`📸 Captured ${screenshots.length} fresh screenshots for analysis`)
|
|
|
|
// Initialize AI and Risk Manager instances
|
|
const antiChasingAI = new EnhancedAntiChasingAI()
|
|
const riskManager = new EnhancedRiskManager({ currentBalance })
|
|
|
|
// Perform anti-chasing analysis
|
|
let analysis
|
|
if (screenshots.length === 1) {
|
|
analysis = await antiChasingAI.analyzeWithAntiChasing(screenshots[0])
|
|
} else {
|
|
analysis = await antiChasingAI.analyzeMultipleWithAntiChasing(screenshots)
|
|
}
|
|
|
|
if (!analysis) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to analyze screenshots with anti-chasing AI'
|
|
}, { status: 500 })
|
|
}
|
|
|
|
console.log('🧠 Anti-chasing analysis completed:')
|
|
console.log(` Recommendation: ${analysis.recommendation}`)
|
|
console.log(` Confidence: ${analysis.confidence}%`)
|
|
console.log(` Momentum Status: ${analysis.momentumStatus?.type}`)
|
|
console.log(` Entry Quality: ${analysis.entryQuality?.score}/100`)
|
|
|
|
// If we have a trading signal, perform risk assessment
|
|
let riskAssessment = null
|
|
let tradeAllowed = false
|
|
let riskDecision = null
|
|
|
|
if (analysis.recommendation !== 'HOLD' && analysis.entry && analysis.stopLoss) {
|
|
console.log('🛡️ Performing risk assessment...')
|
|
|
|
const recentLosses = await riskManager.getRecentLossCount()
|
|
|
|
const riskParams = {
|
|
symbol,
|
|
direction: analysis.recommendation === 'BUY' ? 'LONG' : 'SHORT',
|
|
entryPrice: analysis.entry.price,
|
|
stopLoss: analysis.stopLoss.price,
|
|
takeProfit: analysis.takeProfits?.tp1?.price || (
|
|
analysis.recommendation === 'BUY'
|
|
? analysis.entry.price * 1.02
|
|
: analysis.entry.price * 0.98
|
|
),
|
|
timeframe,
|
|
currentBalance: currentBalance || 127, // Default to current balance
|
|
recentLosses
|
|
}
|
|
|
|
const tradeDecision = await riskManager.shouldAllowTrade(riskParams)
|
|
riskAssessment = tradeDecision.riskAssessment
|
|
tradeAllowed = tradeDecision.allowed
|
|
riskDecision = {
|
|
allowed: tradeDecision.allowed,
|
|
reason: tradeDecision.reason
|
|
}
|
|
|
|
// Record the risk decision
|
|
await riskManager.recordTradeDecision(
|
|
tradeAllowed ? 'APPROVED' : 'REJECTED',
|
|
tradeDecision.reason,
|
|
riskAssessment
|
|
)
|
|
|
|
console.log('🛡️ Risk assessment completed:')
|
|
console.log(` Trade Allowed: ${tradeAllowed}`)
|
|
console.log(` Reason: ${tradeDecision.reason}`)
|
|
console.log(` Recommended Size: $${riskAssessment.recommendedSize}`)
|
|
}
|
|
|
|
// Enhanced response with anti-chasing insights
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
analysis,
|
|
riskAssessment,
|
|
tradeDecision: riskDecision,
|
|
antiChasingInsights: {
|
|
momentumStatus: analysis.momentumStatus,
|
|
entryQuality: analysis.entryQuality,
|
|
timeframeAlignment: analysis.timeframeAlignment,
|
|
riskWarnings: riskAssessment?.riskWarnings || []
|
|
},
|
|
recommendations: {
|
|
shouldTrade: tradeAllowed,
|
|
positionSize: riskAssessment?.recommendedSize,
|
|
stopLoss: analysis.stopLoss?.price,
|
|
takeProfit: analysis.takeProfits?.tp1?.price,
|
|
riskReward: analysis.riskToReward,
|
|
timeframeAdvice: `This is a ${riskAssessment?.timeframeRisk || 'UNKNOWN'} risk timeframe`
|
|
}
|
|
},
|
|
metadata: {
|
|
timestamp: new Date().toISOString(),
|
|
screenshotsAnalyzed: screenshots.length,
|
|
analysisModel: 'enhanced-anti-chasing-ai',
|
|
riskModel: 'enhanced-risk-manager'
|
|
}
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('❌ Error in enhanced analysis:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to perform enhanced anti-chasing analysis',
|
|
details: error instanceof Error ? error.message : 'Unknown error'
|
|
}, { status: 500 })
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ API Error:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Internal server error',
|
|
details: error instanceof Error ? error.message : 'Unknown error'
|
|
}, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function GET(request) {
|
|
try {
|
|
const url = new URL(request.url)
|
|
const symbol = url.searchParams.get('symbol') || 'SOLUSD'
|
|
const timeframe = url.searchParams.get('timeframe') || '240'
|
|
const balance = parseFloat(url.searchParams.get('balance') || '127')
|
|
|
|
console.log('🛡️ Enhanced Anti-Chasing Analysis (GET)')
|
|
console.log(`📊 Query: ${symbol} ${timeframe}`)
|
|
console.log(`💰 Balance: $${balance}`)
|
|
|
|
// For GET requests, we'll analyze the most recent screenshots
|
|
const screenshotsDir = '/app/screenshots'
|
|
|
|
try {
|
|
const fs = await import('fs/promises')
|
|
const path = await import('path')
|
|
|
|
const files = await fs.readdir(screenshotsDir)
|
|
const recentFiles = files
|
|
.filter(f => f.includes(symbol) && f.includes(timeframe))
|
|
.sort((a, b) => b.localeCompare(a))
|
|
.slice(0, 1) // Just take the most recent one for GET
|
|
|
|
if (recentFiles.length === 0) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'No recent screenshots available',
|
|
suggestion: 'Capture new screenshots using POST /api/enhanced-screenshot'
|
|
})
|
|
}
|
|
|
|
const analysis = await enhancedAntiChasingAI.analyzeWithAntiChasing(
|
|
path.join(screenshotsDir, recentFiles[0])
|
|
)
|
|
|
|
if (!analysis) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Analysis failed'
|
|
})
|
|
}
|
|
|
|
// Simplified response for GET requests
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
recommendation: analysis.recommendation,
|
|
confidence: analysis.confidence,
|
|
momentumStatus: analysis.momentumStatus?.type,
|
|
entryQuality: analysis.entryQuality?.score,
|
|
timeframeRisk: analysis.entryQuality?.riskLevel,
|
|
reasoning: analysis.reasoning,
|
|
warnings: analysis.entryQuality?.missingConfirmations || []
|
|
},
|
|
metadata: {
|
|
timestamp: new Date().toISOString(),
|
|
screenshot: recentFiles[0],
|
|
model: 'enhanced-anti-chasing-ai'
|
|
}
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('❌ GET analysis error:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to analyze recent screenshots'
|
|
})
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ GET API Error:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Internal server error'
|
|
})
|
|
}
|
|
}
|