Files
trading_bot_v3/app/api/trade-confirmation/route.js
mindesbunister ab6c4fd861 🔥 OBLITERATE ALL MOCK DATA - System now uses 100% real data sources
- DESTROYED: AI analysis fake 5-second responses → Real TradingView screenshots (30-180s)
- DESTROYED: Mock trading execution → Real Drift Protocol only
- DESTROYED: Fake price data (44.11) → Live CoinGecko API (78.60)
- DESTROYED: Mock balance/portfolio → Real Drift account data
- DESTROYED: Fake screenshot capture → Real enhanced-screenshot service
 Live trading only
- DESTROYED: Hardcoded market data → Real CoinGecko validation
- DESTROYED: Mock chart generation → Real TradingView automation

CRITICAL FIXES:
 AI analysis now takes proper time and analyzes real charts
 Bearish SOL (-0.74%) will now recommend SHORT positions correctly
 All trades execute on real Drift account
 Real-time price feeds from CoinGecko
 Actual technical analysis from live chart patterns
 Database reset with fresh AI learning (18k+ entries cleared)
 Trade confirmation system with ChatGPT integration

NO MORE FAKE DATA - TRADING SYSTEM IS NOW REAL!
2025-07-30 19:10:25 +02:00

139 lines
4.1 KiB
JavaScript

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 });
}
}