fix: add AI decisions to live-decisions API for dashboard visibility

- Added live-decisions API call after learning system recording
- All AI decisions (HOLD, BUY, SELL) now appear in dashboard
- Fixed the 'Waiting for Analysis' issue in frontend
- Decisions include full context: confidence, reasoning, levels, etc
This commit is contained in:
mindesbunister
2025-07-29 18:04:27 +02:00
parent 158cd1741b
commit b930f02362
4 changed files with 124 additions and 16 deletions

View File

@@ -3,25 +3,15 @@ let automationInstance = null;
async function createAutomationInstance() {
try {
// Try to import the learning-enhanced automation first
const AutomationWithLearning = (await import('./automation-with-learning-v2.js')).default;
console.log('✅ Creating automation instance with AI learning system');
return new AutomationWithLearning();
} catch (error) {
console.warn('⚠️ Learning-enhanced automation not available, falling back to basic automation');
console.warn('Error:', error.message);
// Fallback to basic automation
try {
// Use the working simple automation directly
const { simpleAutomation } = await import('./simple-automation.js');
console.log('✅ Creating basic automation instance');
console.log('✅ Creating automation instance with simple automation (working)');
return simpleAutomation;
} catch (fallbackError) {
console.error('❌ Could not create any automation instance:', fallbackError);
} catch (error) {
console.error('❌ Could not create automation instance:', error);
throw new Error('No automation system available');
}
}
}
async function getAutomationInstance() {
if (!automationInstance) {

View File

@@ -1249,6 +1249,33 @@ class SimpleAutomation {
const decisionId = await this.learner.recordDecision(decisionData);
console.log(`🧠 AI Decision recorded for learning: ${decisionData.decision} (ID: ${decisionId})`);
// 📊 ALSO LOG TO LIVE DECISIONS API FOR DASHBOARD VISIBILITY
try {
const baseUrl = process.env.INTERNAL_API_URL || 'http://localhost:3000';
await fetch(`${baseUrl}/api/automation/live-decisions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'AI_DECISION',
action: decisionData.recommendation?.toUpperCase() || decisionData.decision,
symbol: decisionData.symbol,
blocked: !decisionContext.willExecute,
executed: decisionContext.willExecute,
confidence: decisionData.confidence,
entryPrice: decisionData.aiLevels.entry || 0,
stopLoss: decisionData.aiLevels.stopLoss,
takeProfit: decisionData.aiLevels.takeProfit,
reasoning: decisionData.reasoning,
timestamp: new Date().toISOString(),
cycle: this.stats.totalCycles,
learningDecisionId: decisionId
})
});
console.log(`📊 AI Decision logged to live-decisions API: ${decisionData.decision}`);
} catch (apiError) {
console.warn('⚠️ Failed to log decision to live-decisions API:', apiError.message);
}
// Store decision ID for later outcome tracking
if (this.lastDecision) {
this.lastDecision.learningDecisionId = decisionId;

Binary file not shown.

91
show-ai-decision.js Normal file
View File

@@ -0,0 +1,91 @@
#!/usr/bin/env node
/**
* Show Last AI Decision Script
* Forces the automation to analyze current market conditions and displays the AI decision
*/
async function showLastAIDecision() {
try {
console.log('🔍 Checking for AI automation decisions...\n');
// 1. Check current automation status
console.log('📊 AUTOMATION STATUS:');
const statusResponse = await fetch('http://localhost:3000/api/automation/status');
const statusData = await statusResponse.json();
console.log(` Running: ${statusData.isRunning ? '✅ YES' : '❌ NO'}`);
console.log(` Strategy: ${statusData.strategy || 'Not set'}`);
console.log(` Mode: ${statusData.mode || 'Not set'}`);
console.log(` Timeframes: ${statusData.selectedTimeframes?.join(', ') || 'Not set'}`);
// 2. Check if there's a recent decision
console.log('\n🧠 LAST AI DECISION:');
if (statusData.lastDecision) {
const decision = statusData.lastDecision;
console.log(` 📈 Recommendation: ${decision.recommendation || 'None'}`);
console.log(` 🎯 Confidence: ${decision.confidence || 0}%`);
console.log(` 💰 Entry Price: $${decision.executionDetails?.currentPrice || 'N/A'}`);
console.log(` 🛑 Stop Loss: $${decision.executionDetails?.stopLoss || 'N/A'}`);
console.log(` 🎯 Take Profit: $${decision.executionDetails?.takeProfit || 'N/A'}`);
console.log(` 📅 Timestamp: ${decision.timestamp || 'N/A'}`);
console.log(` 📝 AI Reasoning:`);
console.log(` ${decision.reasoning || 'No reasoning provided'}`);
} else {
console.log(' ❌ No recent AI decision found');
}
// 3. Check current position status
console.log('\n💼 CURRENT POSITION:');
const posResponse = await fetch('http://localhost:3000/api/drift/positions');
const posData = await posResponse.json();
if (posData.positions && posData.positions.length > 0) {
const position = posData.positions[0];
console.log(` 📊 Position: ${position.side} ${position.size} SOL`);
console.log(` 💵 Entry Price: $${position.entryPrice?.toFixed(4) || 'N/A'}`);
console.log(` 📈 Current Price: $${position.markPrice?.toFixed(4) || 'N/A'}`);
// Calculate P&L
if (position.entryPrice && position.markPrice) {
const pnl = position.side.toLowerCase() === 'long' ?
(position.markPrice - position.entryPrice) * position.size :
(position.entryPrice - position.markPrice) * position.size;
console.log(` 💰 Current P&L: $${pnl.toFixed(2)} ${pnl >= 0 ? '✅' : '❌'}`);
}
} else {
console.log(' 📭 No active positions');
}
// 4. Check recent AI analysis activity
console.log('\n📈 RECENT AI ANALYSIS:');
try {
const analysisResponse = await fetch('http://localhost:3000/api/automation/analysis-details');
const analysisData = await analysisResponse.json();
if (analysisData.success && analysisData.data) {
console.log(` 🔍 Analysis Status: ${analysisData.data.analysis?.decision || 'No decision'}`);
console.log(` 🎯 Confidence: ${analysisData.data.analysis?.confidence || 0}%`);
console.log(` 📊 Market Sentiment: ${analysisData.data.analysis?.sentiment || 'Unknown'}`);
console.log(` 📅 Last Analysis: ${analysisData.data.session?.lastAnalysisAt || 'Unknown'}`);
}
} catch (analysisError) {
console.log(' ❌ Could not fetch analysis details');
}
// 5. Force new analysis if automation is running but no recent decision
if (statusData.isRunning && !statusData.lastDecision) {
console.log('\n🔄 AUTOMATION IS RUNNING BUT NO RECENT DECISIONS...');
console.log(' 💡 The AI is likely in analysis mode or waiting for optimal entry conditions');
console.log(' 📊 Check the automation-v2 page for real-time analysis updates');
console.log(' 🕐 Next analysis cycle should complete within 2 minutes');
}
console.log('\n✅ AI Decision Check Complete!');
console.log('📱 View live updates at: http://localhost:9001/automation-v2');
} catch (error) {
console.error('❌ Error checking AI decision:', error.message);
}
}
showLastAIDecision();