#!/usr/bin/env node /** * DEMONSTRATE COMPLETE TRADE OUTCOME TRACKING * Shows how the AI learns from trade wins/losses on Drift Protocol */ async function demonstrateOutcomeTracking() { console.log('šŸŽÆ DRIFT PROTOCOL OUTCOME TRACKING DEMONSTRATION') console.log('='.repeat(70)) console.log(` šŸ“Š HOW THE AI LEARNS WIN/LOSS FROM REAL TRADES: 1. šŸš€ TRADE EXECUTION (Already Working): āœ… Place order on Drift Protocol āœ… Create learning record in database āœ… Store entry price, stop loss, take profit āœ… Record transaction IDs 2. šŸ”„ OUTCOME MONITORING (Need to Start): šŸ” Monitor Drift positions every 30 seconds šŸ“Š Check if position is still open or closed šŸ’° Determine if closed via stop loss or take profit šŸ“ˆ Calculate actual profit/loss percentage 3. šŸ“š LEARNING UPDATE (Automatic): āœ… Update trade record with WIN/LOSS/BREAKEVEN 🧠 Link outcome back to AI analysis šŸ“Š Calculate prediction accuracy šŸš€ Improve AI for next trade `) console.log('šŸ”§ CURRENT STATUS CHECK:') try { // Check current monitoring status const statusResponse = await fetch('http://localhost:3000/api/drift/feedback') const status = await statusResponse.json() console.log('šŸ“Š Feedback Loop Status:', status.monitoring.status) if (status.monitoring.status === 'STOPPED') { console.log('\nšŸš€ Starting outcome monitoring...') const startResponse = await fetch('http://localhost:3000/api/drift/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start_monitoring' }) }) const startResult = await startResponse.json() if (startResult.success) { console.log('āœ… Monitoring started successfully!') console.log('šŸ”„ System now checking trade outcomes every 30 seconds') } else { console.log('āŒ Failed to start monitoring:', startResult.details) console.log('šŸ’” This is expected if RPC has limitations') } } else { console.log('āœ… Monitoring already active') } } catch (error) { console.error('āŒ Status check failed:', error.message) } console.log('\nšŸ“‹ CHECKING RECENT TRADES FOR OUTCOME EXAMPLES:') try { const { PrismaClient } = await import('@prisma/client') const prisma = new PrismaClient() // Get recent real Drift trades const recentTrades = await prisma.trade.findMany({ where: { userId: 'default-user', tradingMode: 'REAL', driftTxId: { not: null } }, orderBy: { createdAt: 'desc' }, take: 5 }) console.log(`\nšŸ” Found ${recentTrades.length} recent real Drift trades:`) recentTrades.forEach((trade, index) => { const outcomeEmoji = trade.outcome === 'WIN' ? '🟢' : trade.outcome === 'LOSS' ? 'šŸ”“' : trade.outcome === 'BREAKEVEN' ? '🟔' : 'ā³' console.log(` ${index + 1}. ${outcomeEmoji} ${trade.symbol} ${trade.side.toUpperCase()} - ${trade.outcome || 'PENDING'}`) console.log(` Entry: $${trade.entryPrice || trade.price}`) console.log(` Stop: $${trade.stopLoss} | Target: $${trade.takeProfit}`) console.log(` P&L: ${trade.pnlPercent ? trade.pnlPercent.toFixed(2) + '%' : 'Pending'}`) console.log(` Status: ${trade.status}`) console.log(` Created: ${trade.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`) console.log('') }) // Show outcome statistics const completedTrades = recentTrades.filter(t => t.outcome) if (completedTrades.length > 0) { const wins = completedTrades.filter(t => t.outcome === 'WIN').length const winRate = (wins / completedTrades.length * 100).toFixed(1) const avgPnL = completedTrades.reduce((sum, t) => sum + (t.pnlPercent || 0), 0) / completedTrades.length console.log('šŸ“Š LEARNING STATISTICS:') console.log(` Total Completed: ${completedTrades.length}`) console.log(` Win Rate: ${winRate}%`) console.log(` Average P&L: ${avgPnL.toFixed(2)}%`) } else { console.log('ā³ No completed trades yet - outcomes still being monitored') } await prisma.$disconnect() } catch (error) { console.error('āŒ Database check failed:', error.message) } } async function demonstrateOutcomeDetection() { console.log('\nšŸ” HOW OUTCOME DETECTION WORKS:') console.log('='.repeat(50)) console.log(` šŸŽÆ DRIFT POSITION MONITORING: 1. Every 30 seconds, system checks Drift account 2. Compares current positions with open trades 3. Detects when position is closed or reduced šŸ“Š OUTCOME DETECTION LOGIC: For a BUY trade: • If position closed above stop loss → Check if TP hit or manual close • If position closed at/near stop loss → Outcome = LOSS • If position closed at/near take profit → Outcome = WIN • Calculate exact P&L percentage from entry to exit For a SELL trade: • Same logic but inverted price movements • Stop loss above entry, take profit below entry šŸ’° P&L CALCULATION: • Entry Price: $183.24 (from trade record) • Exit Price: $185.99 (detected when position closes) • P&L = ((185.99 - 183.24) / 183.24) * 100 = +1.50% • Outcome = WIN (profitable trade) 🧠 AI LEARNING UPDATE: • Trade record updated: outcome = 'WIN', pnlPercent = 1.50 • AI analysis linked: predicted outcome vs actual outcome • Accuracy score calculated and stored • Pattern recognition improved for future trades `) console.log('šŸš€ TRIGGER MANUAL OUTCOME CHECK:') try { const checkResponse = await fetch('http://localhost:3000/api/drift/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'check_trades' }) }) const checkResult = await checkResponse.json() if (checkResult.success) { console.log('āœ… Manual outcome check completed') console.log('šŸ”„ Any closed positions should now be detected') } else { console.log('āŒ Manual check failed:', checkResult.error) } } catch (error) { console.error('āŒ Manual check failed:', error.message) } } async function showLearningInsights() { console.log('\n🧠 AI LEARNING INSIGHTS:') console.log('='.repeat(40)) try { const insightsResponse = await fetch('http://localhost:3000/api/drift/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'get_insights' }) }) const insights = await insightsResponse.json() if (insights.success) { console.log('šŸ“Š Current Performance:') console.log(` Total Trades: ${insights.insights.recentPerformance.totalTrades}`) console.log(` Win Rate: ${insights.insights.recentPerformance.winRate}`) console.log(` Avg P&L: ${insights.insights.recentPerformance.avgPnL}`) console.log(` Time Range: ${insights.insights.recentPerformance.timeRange}`) console.log(` Feedback Status: ${insights.insights.feedbackLoopStatus}`) if (insights.insights.latestInsights) { console.log('\nšŸŽÆ Latest Learning Insights:') console.log(JSON.stringify(insights.insights.latestInsights, null, 2)) } else { console.log('\nā³ No comprehensive insights yet - need more completed trades') } } } catch (error) { console.error('āŒ Insights check failed:', error.message) } } if (require.main === module) { demonstrateOutcomeTracking() .then(() => demonstrateOutcomeDetection()) .then(() => showLearningInsights()) .then(() => { console.log('\nšŸŽ‰ COMPLETE LEARNING CYCLE DEMONSTRATED!') console.log('\nšŸ’” NEXT STEPS:') console.log('1. Keep monitoring running for automatic outcome detection') console.log('2. Place more trades to build learning database') console.log('3. AI will improve accuracy based on real results') console.log('4. Check insights regularly to see learning progress') }) }