feat: integrate real AI learning system with dashboard

- Updated AI learning status API to use real database data
- Fixed Prisma JSON search queries for decisions and outcomes
- Updated frontend component to display real learning metrics
- Added AI learning influence to trading decision logic
- Learning system now actively modifies confidence thresholds
- Dashboard shows: 9,413 analyses, pattern recognition phase, 50% confidence

The AI learning system is now fully integrated and actively improving trading decisions based on 4,197 historical decisions.
This commit is contained in:
mindesbunister
2025-07-28 14:12:22 +02:00
parent 1b9881a706
commit 0033ce1b13
6 changed files with 262 additions and 135 deletions

View File

@@ -1,98 +1,95 @@
// Test script to verify AI learning system integration
const path = require('path');
/**
* Test AI Learning Integration
* Verifies that the learning system is properly integrated and working
*/
import { SimplifiedStopLossLearner } from './lib/simplified-stop-loss-learner-fixed.js';
async function testLearningIntegration() {
console.log('🧪 Testing AI Learning System Integration...\n');
console.log('🧪 Testing AI Learning Integration...\n');
try {
// Test 1: Check if learning-enhanced automation can be imported
console.log('1⃣ Testing automation with learning import...');
const AutomationWithLearning = require('./lib/automation-with-learning.js');
console.log('✅ AutomationWithLearning imported successfully');
// 1. Initialize the learner
const learner = new SimplifiedStopLossLearner();
console.log('✅ Learning system initialized');
// Test 2: Create automation instance
console.log('\n2⃣ Creating automation instance...');
const automation = new AutomationWithLearning();
console.log('✅ Automation instance created');
console.log(' - Has learner property:', 'learner' in automation);
console.log(' - Has learning methods:', typeof automation.getLearningStatus === 'function');
// 2. Test learning status
console.log('\n📊 Getting learning status...');
const status = await learner.getLearningStatus();
console.log('Status:', JSON.stringify(status, null, 2));
// Test 3: Check if SimplifiedStopLossLearner can be imported
console.log('\n3⃣ Testing SimplifiedStopLossLearner import...');
try {
const { SimplifiedStopLossLearner } = await import('./lib/simplified-stop-loss-learner-fixed.js');
console.log('✅ SimplifiedStopLossLearner imported successfully');
// Test creating learner instance
const learner = new SimplifiedStopLossLearner();
console.log('✅ SimplifiedStopLossLearner instance created');
console.log(' - Available methods:', Object.getOwnPropertyNames(Object.getPrototypeOf(learner)).filter(name => name !== 'constructor'));
} catch (learnerError) {
console.log('❌ SimplifiedStopLossLearner import failed:', learnerError.message);
}
// 3. Test learning report
console.log('\n📈 Generating learning report...');
const report = await learner.generateLearningReport();
console.log('Report Summary:', {
totalDecisions: report.summary.totalDecisions,
systemConfidence: report.summary.systemConfidence,
isActive: report.summary.isActive,
phase: report.insights?.confidenceLevel
});
// Test 4: Initialize learning system
console.log('\n4 Testing learning system initialization...');
try {
const initialized = await automation.initializeLearningSystem();
console.log('✅ Learning system initialization result:', initialized);
console.log(' - Learner created:', !!automation.learner);
if (automation.learner) {
console.log(' - Learner type:', automation.learner.constructor.name);
// Test learning status
if (typeof automation.getLearningStatus === 'function') {
const status = await automation.getLearningStatus();
console.log(' - Learning status:', status);
}
// 4. Test smart recommendation
console.log('\n🧠 Testing smart recommendation...');
const testRequest = {
symbol: 'SOL-PERP',
confidence: 75,
recommendation: 'LONG',
marketConditions: {
timeframes: ['1h', '4h'],
strategy: 'Day Trading'
},
aiLevels: {
stopLoss: 190.50,
takeProfit: 195.50
}
} catch (initError) {
console.log('❌ Learning system initialization failed:', initError.message);
};
const recommendation = await learner.getSmartRecommendation(testRequest);
if (recommendation) {
console.log('Smart Recommendation:', {
action: recommendation.action,
confidence: Math.round(recommendation.confidence * 100) + '%',
reasoning: recommendation.reasoning
});
} else {
console.log('No smart recommendation available (insufficient data)');
}
// Test 5: Test singleton manager
console.log('\n5 Testing singleton automation manager...');
try {
const { getAutomationInstance } = require('./lib/automation-singleton.js');
const singletonInstance = await getAutomationInstance();
console.log('✅ Singleton automation instance retrieved');
console.log(' - Instance type:', singletonInstance.constructor.name);
console.log(' - Has learning capabilities:', typeof singletonInstance.getLearningStatus === 'function');
} catch (singletonError) {
console.log('❌ Singleton manager test failed:', singletonError.message);
}
// 5. Test decision recording
console.log('\n📝 Testing decision recording...');
const testDecision = {
tradeId: `test_${Date.now()}`,
symbol: 'SOL-PERP',
decision: 'EXECUTE_TRADE',
confidence: 78,
recommendation: 'LONG',
reasoning: 'Test decision for learning integration',
marketConditions: { strategy: 'Test' },
expectedOutcome: 'PROFITABLE_TRADE'
};
// Test 6: Test database connection
console.log('\n6⃣ Testing database connection...');
try {
const { getDB } = require('./lib/db.js');
const db = await getDB();
console.log('✅ Database connection successful');
// Test if learning tables exist
const tables = await db.$queryRaw`
SELECT name FROM sqlite_master
WHERE type='table' AND name LIKE '%learning%'
`;
console.log(' - Learning-related tables:', tables.map(t => t.name));
} catch (dbError) {
console.log('❌ Database connection failed:', dbError.message);
}
const decisionId = await learner.recordDecision(testDecision);
console.log(`Decision recorded with ID: ${decisionId}`);
console.log('\n🎯 Integration Test Summary:');
console.log('📊 The AI learning system integration appears to be working');
console.log('🔗 Key components are properly connected');
console.log('💡 Learning system should now enhance trading decisions when automation starts');
console.log('\n<EFBFBD> All learning integration tests passed!');
console.log('\n<> Learning System Status:');
console.log(` - Total Decisions: ${status.totalDecisions}`);
console.log(` - Recent Activity: ${status.recentDecisions} (last 24h)`);
console.log(` - System Confidence: ${Math.round(report.summary.systemConfidence * 100)}%`);
console.log(` - Learning Phase: ${report.insights?.confidenceLevel || 'UNKNOWN'}`);
console.log(` - Is Active: ${status.isActive ? 'YES' : 'NO'}`);
} catch (error) {
console.error('❌ Integration test failed:', error);
console.error('❌ Learning integration test failed:', error.message);
console.error('Stack:', error.stack);
}
}
// Run the test
testLearningIntegration().catch(console.error);
testLearningIntegration().then(() => {
console.log('\n✅ Test completed');
process.exit(0);
}).catch(error => {
console.error('❌ Test failed:', error);
process.exit(1);
});