Files
trading_bot_v3/app/api/status/route.ts
mindesbunister 416f72181e feat: enhance paper trading with comprehensive AI analysis and learning insights
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
2025-08-02 17:56:02 +02:00

103 lines
3.2 KiB
TypeScript

import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET() {
try {
// Get the latest automation session
const session = await prisma.automation_sessions.findFirst({
orderBy: { createdAt: 'desc' }
})
// Get recent trades for calculations
const recentTrades = session ? await prisma.trades.findMany({
where: {
userId: session.userId,
symbol: session.symbol
},
orderBy: { createdAt: 'desc' },
take: 10
}) : []
// Calculate metrics from actual trades
const completedTrades = recentTrades.filter(t => t.status === 'COMPLETED')
const activeTrades = recentTrades.filter(t => t.status === 'OPEN' || t.status === 'PENDING')
// Calculate win rate
const winRate = completedTrades.length > 0 ?
(completedTrades.filter(t => {
const profit = t.profit || 0
return profit > 0
}).length / completedTrades.length * 100) : 0
// Calculate daily P&L (trades from today)
const today = new Date()
today.setHours(0, 0, 0, 0)
const todayTrades = completedTrades.filter(t =>
new Date(t.createdAt) >= today
)
const dailyPnL = todayTrades.reduce((total, trade) => {
const profit = trade.profit || 0
return total + (typeof profit === 'string' ? parseFloat(profit) : profit)
}, 0)
// Calculate total P&L
const totalPnL = completedTrades.reduce((total, trade) => {
const profit = trade.profit || 0
return total + (typeof profit === 'string' ? parseFloat(profit) : profit)
}, 0)
// Mock portfolio value (base amount + total P&L)
const basePortfolioValue = 1000
const portfolioValue = basePortfolioValue + totalPnL
// Get REAL available coins from Drift positions
const driftResponse = await fetch(`${process.env.APP_URL || 'http://localhost:3000'}/api/drift/positions`);
let availableCoins = ['SOL']; // fallback
if (driftResponse.ok) {
const positionsData = await driftResponse.json();
if (positionsData.success && positionsData.positions) {
availableCoins = positionsData.positions.map((pos: any) => pos.symbol || 'SOL');
}
}
return NextResponse.json({
status: 'connected',
service: 'trading_bot',
timestamp: new Date().toISOString(),
health: 'healthy',
// Trading status data for StatusOverview
portfolioValue: portfolioValue,
dailyPnL: dailyPnL,
totalPnL: totalPnL,
activeTrades: activeTrades.length,
completedTrades: completedTrades.length,
winRate: winRate,
availableCoins: availableCoins,
// Market prices will be fetched separately
marketPrices: []
})
} catch (error) {
console.error('Status API error:', error)
return NextResponse.json({
status: 'error',
service: 'trading_bot',
error: error instanceof Error ? error.message : 'Unknown error',
// Return default values so UI doesn't break
portfolioValue: 1000,
dailyPnL: 0,
totalPnL: 0,
activeTrades: 0,
completedTrades: 0,
winRate: 0,
availableCoins: [],
marketPrices: []
}, { status: 500 })
}
}