import { NextResponse } from 'next/server'; import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); export async function POST(request) { try { const { action, analysis, userInput, symbol, timeframe } = await request.json(); console.log(`🤔 Trade confirmation request - ${action} for ${symbol}`); if (action === 'analyze') { // Generate trade recommendation with detailed analysis const systemPrompt = `You are an expert trading analyst. Analyze the provided technical data and give a clear trading recommendation. Rules: 1. Be specific about entry, stop loss, and take profit levels 2. Explain your reasoning clearly 3. Rate your confidence (1-100) 4. Suggest position size as % of account 5. Identify key risks Format your response as: RECOMMENDATION: [LONG/SHORT/WAIT] CONFIDENCE: [1-100]% ENTRY: $[price] STOP LOSS: $[price] TAKE PROFIT: $[price] POSITION SIZE: [1-10]% of account REASONING: [detailed explanation] RISKS: [key risks to consider]`; const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "system", content: systemPrompt }, { role: "user", content: `Symbol: ${symbol}\nTimeframe: ${timeframe}\nTechnical Analysis: ${JSON.stringify(analysis, null, 2)}` } ], max_tokens: 800, temperature: 0.3 }); const recommendation = completion.choices[0].message.content; return NextResponse.json({ success: true, recommendation, analysis, requiresConfirmation: true }); } else if (action === 'chat') { // Chat with GPT about the trade const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "system", content: "You are a helpful trading assistant. Answer questions about trading analysis and help clarify trading decisions. Keep responses concise and actionable." }, { role: "user", content: userInput } ], max_tokens: 500, temperature: 0.7 }); return NextResponse.json({ success: true, response: completion.choices[0].message.content }); } else if (action === 'confirm') { // Log the confirmation decision console.log('✅ Trade confirmed by user'); return NextResponse.json({ success: true, message: 'Trade confirmation recorded', executeSignal: true }); } else if (action === 'abort') { // Log the abort decision with reason console.log(`❌ Trade aborted by user: ${userInput}`); // Store the abort reason for learning try { const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); await prisma.ai_learning_data.create({ data: { id: `abort_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, userId: 'system-user', sessionId: `abort-session-${Date.now()}`, symbol, timeframe, analysisData: analysis || {}, marketConditions: { userDecision: 'ABORT', reason: userInput }, outcome: 'USER_ABORTED', confidenceScore: 0, feedbackData: { abortReason: userInput, timestamp: new Date().toISOString() }, createdAt: new Date() } }); await prisma.$disconnect(); } catch (error) { console.error('Error storing abort reason:', error); } return NextResponse.json({ success: true, message: 'Trade aborted and reason recorded', executeSignal: false }); } return NextResponse.json({ success: false, error: 'Invalid action' }, { status: 400 }); } catch (error) { console.error('Error in trade confirmation:', error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); } }