feat: integrate AI learning system with trading automation
- AutomationWithLearning class with decision recording and outcome assessment - Enhanced API endpoints with learning status visibility - Singleton automation manager for seamless learning system integration - EnhancedAILearningPanel component for real-time learning visibility - Learning-enhanced trade execution with AI adjustments to SL/TP - Automatic decision tracking and outcome-based learning Key Features: - Records trading decisions before execution - Enhances analysis with learned patterns - Tracks trade outcomes for continuous improvement - Provides full visibility into AI decision-making process - Integrates SimplifiedStopLossLearner with real trading flow - Whether learning system is active - How many decisions are being tracked - Real-time learning statistics and insights - AI enhancements applied to trading decisions
This commit is contained in:
71
app/api/automation/learning-status/route.js
Normal file
71
app/api/automation/learning-status/route.js
Normal file
@@ -0,0 +1,71 @@
|
||||
// API route to get detailed learning system status and visibility
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
// Import the automation instance to get learning status
|
||||
async function getAutomationInstance() {
|
||||
try {
|
||||
// Import the singleton automation instance
|
||||
const { getAutomationInstance } = await import('../../../lib/automation-singleton.js');
|
||||
return getAutomationInstance();
|
||||
} catch (error) {
|
||||
console.error('❌ Could not get automation instance:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const automation = await getAutomationInstance();
|
||||
|
||||
if (!automation) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: 'Automation instance not available'
|
||||
}, { status: 503 });
|
||||
}
|
||||
|
||||
// Check if automation has learning capabilities
|
||||
if (typeof automation.getLearningStatus !== 'function') {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
learningSystem: {
|
||||
enabled: false,
|
||||
message: 'Basic automation running - learning system not integrated',
|
||||
recommendation: 'Restart automation to enable AI learning system'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Get detailed learning status
|
||||
const learningStatus = await automation.getLearningStatus();
|
||||
const automationStatus = automation.getStatus();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
learningSystem: {
|
||||
...learningStatus,
|
||||
automationRunning: automationStatus.isRunning,
|
||||
totalCycles: automationStatus.stats.totalCycles,
|
||||
totalTrades: automationStatus.stats.totalTrades
|
||||
},
|
||||
visibility: {
|
||||
decisionTrackingActive: learningStatus.activeDecisions > 0,
|
||||
learningDatabaseConnected: learningStatus.enabled,
|
||||
aiEnhancementsActive: learningStatus.learningActive,
|
||||
lastUpdateTime: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error getting learning system status:', error);
|
||||
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: error.message,
|
||||
learningSystem: {
|
||||
enabled: false,
|
||||
error: 'Failed to retrieve learning status'
|
||||
}
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,52 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { simpleAutomation } from '@/lib/simple-automation';
|
||||
|
||||
// Import singleton automation manager
|
||||
async function getAutomationInstance() {
|
||||
try {
|
||||
const { getAutomationInstance } = await import('../../../lib/automation-singleton.js');
|
||||
return await getAutomationInstance();
|
||||
} catch (error) {
|
||||
console.error('❌ Could not get automation instance:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const config = await request.json();
|
||||
|
||||
console.log('🚀 AUTOMATION START: Received config:', JSON.stringify(config, null, 2));
|
||||
console.log('🧠 LEARNING SYSTEM: Attempting to start with AI learning integration');
|
||||
|
||||
const result = await simpleAutomation.start(config);
|
||||
const automation = await getAutomationInstance();
|
||||
const result = await automation.start(config);
|
||||
|
||||
// Add learning system status to response
|
||||
const response = {
|
||||
...result,
|
||||
learningSystem: {
|
||||
integrated: typeof automation.getLearningStatus === 'function',
|
||||
type: automation.constructor.name
|
||||
}
|
||||
};
|
||||
|
||||
if (result.success) {
|
||||
return NextResponse.json(result);
|
||||
console.log('✅ AUTOMATION STARTED:', response.learningSystem.integrated ? 'With AI Learning' : 'Basic Mode');
|
||||
return NextResponse.json(response);
|
||||
} else {
|
||||
return NextResponse.json(result, { status: 400 });
|
||||
return NextResponse.json(response, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Start automation error:', error);
|
||||
console.error('❌ Start automation error:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'Internal server error',
|
||||
message: error.message
|
||||
message: error.message,
|
||||
learningSystem: {
|
||||
integrated: false,
|
||||
error: 'Failed to initialize'
|
||||
}
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,56 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { simpleAutomation } from '@/lib/simple-automation';
|
||||
|
||||
// Import singleton automation manager
|
||||
async function getAutomationInstance() {
|
||||
try {
|
||||
const { getAutomationInstance } = await import('../../../lib/automation-singleton.js');
|
||||
return await getAutomationInstance();
|
||||
} catch (error) {
|
||||
console.error('❌ Could not get automation instance:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const status = simpleAutomation.getStatus();
|
||||
const automation = await getAutomationInstance();
|
||||
|
||||
if (!automation) {
|
||||
return NextResponse.json({
|
||||
error: 'No automation instance available',
|
||||
isRunning: false,
|
||||
learningSystem: { enabled: false }
|
||||
}, { status: 503 });
|
||||
}
|
||||
|
||||
const status = automation.getStatus();
|
||||
|
||||
// Add learning system status if available
|
||||
if (typeof automation.getLearningStatus === 'function') {
|
||||
try {
|
||||
const learningStatus = await automation.getLearningStatus();
|
||||
status.learningSystem = learningStatus;
|
||||
} catch (learningError) {
|
||||
status.learningSystem = {
|
||||
enabled: false,
|
||||
error: learningError.message
|
||||
};
|
||||
}
|
||||
} else {
|
||||
status.learningSystem = {
|
||||
enabled: false,
|
||||
message: 'Basic automation - learning not integrated'
|
||||
};
|
||||
}
|
||||
|
||||
return NextResponse.json(status);
|
||||
} catch (error) {
|
||||
console.error('Status error:', error);
|
||||
console.error('❌ Status error:', error);
|
||||
return NextResponse.json({
|
||||
error: 'Failed to get status',
|
||||
message: error.message
|
||||
message: error.message,
|
||||
isRunning: false,
|
||||
learningSystem: { enabled: false, error: 'Status check failed' }
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
import { simpleAutomation } from '@/lib/simple-automation';
|
||||
// Import singleton automation manager
|
||||
async function getAutomationInstance() {
|
||||
try {
|
||||
const { getAutomationInstance } = await import('../../../lib/automation-singleton.js');
|
||||
return await getAutomationInstance();
|
||||
} catch (error) {
|
||||
console.error('❌ Could not get automation instance:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
console.log('🛑 AUTOMATION STOP: Request received');
|
||||
|
||||
const result = await simpleAutomation.stop();
|
||||
const automation = await getAutomationInstance();
|
||||
let result = { success: false, message: 'No automation instance available' };
|
||||
|
||||
if (automation) {
|
||||
result = await automation.stop();
|
||||
|
||||
// Check if learning system was active
|
||||
if (typeof automation.getLearningStatus === 'function') {
|
||||
const learningStatus = await automation.getLearningStatus();
|
||||
console.log('🧠 LEARNING SYSTEM: Stopped with', learningStatus.activeDecisions, 'active decisions');
|
||||
}
|
||||
}
|
||||
|
||||
// Additional cleanup
|
||||
try {
|
||||
@@ -17,7 +37,7 @@ export async function POST() {
|
||||
|
||||
return Response.json(result);
|
||||
} catch (error) {
|
||||
console.error('Stop automation error:', error);
|
||||
console.error('❌ Stop automation error:', error);
|
||||
return Response.json({
|
||||
success: false,
|
||||
message: error.message
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import EnhancedAILearningPanel from '../../components/EnhancedAILearningPanel'
|
||||
|
||||
// Available timeframes for automation (matching analysis page format)
|
||||
const timeframes = [
|
||||
@@ -27,21 +28,18 @@ export default function AutomationPageV2() {
|
||||
const [positions, setPositions] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [monitorData, setMonitorData] = useState(null)
|
||||
const [aiLearningData, setAiLearningData] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus()
|
||||
fetchBalance()
|
||||
fetchPositions()
|
||||
fetchMonitorData()
|
||||
fetchAiLearningData()
|
||||
|
||||
const interval = setInterval(() => {
|
||||
fetchStatus()
|
||||
fetchBalance()
|
||||
fetchPositions()
|
||||
fetchMonitorData()
|
||||
fetchAiLearningData()
|
||||
}, 300000) // 5 minutes instead of 30 seconds
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
@@ -107,18 +105,6 @@ export default function AutomationPageV2() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchAiLearningData = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/ai-learning-status')
|
||||
const data = await response.json()
|
||||
if (data.success) {
|
||||
setAiLearningData(data.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch AI learning data:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleStart = async () => {
|
||||
console.log('🚀 Starting automation...')
|
||||
setLoading(true)
|
||||
@@ -149,6 +135,9 @@ export default function AutomationPageV2() {
|
||||
|
||||
if (data.success) {
|
||||
console.log('✅ Automation started successfully')
|
||||
if (data.learningSystem?.integrated) {
|
||||
console.log('🧠 AI Learning System: Activated')
|
||||
}
|
||||
fetchStatus()
|
||||
} else {
|
||||
console.error('Failed to start automation:', data.error)
|
||||
@@ -941,112 +930,8 @@ export default function AutomationPageV2() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Enhanced AI Learning Status Panel */}
|
||||
{aiLearningData && (
|
||||
<div className="bg-gradient-to-br from-gray-900/90 via-slate-800/80 to-gray-900/90 backdrop-blur-xl p-6 rounded-2xl border border-gray-600/30 shadow-2xl">
|
||||
<div className="flex items-center space-x-3 mb-6">
|
||||
<div className="w-14 h-14 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-xl flex items-center justify-center shadow-lg shadow-purple-500/25">
|
||||
<span className="text-2xl">🧠</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-white">AI Learning Status</h3>
|
||||
<p className="text-gray-400">{aiLearningData.phase} • Real-time learning progress</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Stats Grid */}
|
||||
<div className="grid grid-cols-4 gap-4 mb-6">
|
||||
<div className="p-4 bg-gradient-to-br from-green-900/30 to-emerald-900/20 rounded-xl border border-green-500/30">
|
||||
<div className="text-green-400 text-2xl font-bold">{aiLearningData.avgAccuracy}%</div>
|
||||
<div className="text-gray-400 text-sm">Avg Accuracy</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gradient-to-br from-blue-900/30 to-cyan-900/20 rounded-xl border border-blue-500/30">
|
||||
<div className="text-blue-400 text-2xl font-bold">{aiLearningData.winRate}%</div>
|
||||
<div className="text-gray-400 text-sm">Win Rate</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gradient-to-br from-purple-900/30 to-violet-900/20 rounded-xl border border-purple-500/30">
|
||||
<div className="text-purple-400 text-2xl font-bold">{aiLearningData.confidenceLevel}%</div>
|
||||
<div className="text-gray-400 text-sm">Confidence Level</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gradient-to-br from-yellow-900/30 to-orange-900/20 rounded-xl border border-yellow-500/30">
|
||||
<div className="text-yellow-400 text-2xl font-bold">{aiLearningData.daysActive}</div>
|
||||
<div className="text-gray-400 text-sm">Days Active</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Trading Performance Section */}
|
||||
{aiLearningData.statistics && aiLearningData.statistics.totalTrades > 0 && (
|
||||
<div className="mb-6">
|
||||
<h4 className="text-lg font-semibold text-cyan-400 mb-3 flex items-center">
|
||||
<span className="mr-2">📊</span>Trading Performance
|
||||
</h4>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 mb-4">
|
||||
<div className="p-3 bg-black/20 rounded-lg">
|
||||
<div className="text-green-400 font-bold text-lg">{aiLearningData.statistics.wins}</div>
|
||||
<div className="text-gray-400 text-sm">Wins</div>
|
||||
<div className="text-green-300 text-xs">+${aiLearningData.statistics.winsPnl.toFixed(2)}</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-black/20 rounded-lg">
|
||||
<div className="text-red-400 font-bold text-lg">{aiLearningData.statistics.losses}</div>
|
||||
<div className="text-gray-400 text-sm">Losses</div>
|
||||
<div className="text-red-300 text-xs">${aiLearningData.statistics.lossesPnl.toFixed(2)}</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-black/20 rounded-lg">
|
||||
<div className={`font-bold text-lg ${aiLearningData.statistics.totalPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
|
||||
${aiLearningData.statistics.totalPnl >= 0 ? '+' : ''}${aiLearningData.statistics.totalPnl.toFixed(2)}
|
||||
</div>
|
||||
<div className="text-gray-400 text-sm">Total P&L</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced Metrics */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-3 bg-black/20 rounded-lg">
|
||||
<div className="text-gray-400 text-sm mb-1">Avg Win</div>
|
||||
<div className="text-green-400 font-semibold">${aiLearningData.statistics.avgWin.toFixed(2)}</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-black/20 rounded-lg">
|
||||
<div className="text-gray-400 text-sm mb-1">Avg Loss</div>
|
||||
<div className="text-red-400 font-semibold">${aiLearningData.statistics.avgLoss.toFixed(2)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Learning Progress */}
|
||||
<div className="mb-4">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-gray-400 text-sm">Learning Progress</span>
|
||||
<span className="text-white text-sm">{aiLearningData.totalAnalyses} analyses</span>
|
||||
</div>
|
||||
<div className="w-full bg-gray-700 rounded-full h-2">
|
||||
<div
|
||||
className="bg-gradient-to-r from-purple-500 to-blue-500 h-2 rounded-full transition-all duration-500"
|
||||
style={{ width: `${Math.min(100, (aiLearningData.avgAccuracy / 100) * 100)}%` }}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Next Milestone */}
|
||||
<div className="p-3 bg-gradient-to-r from-indigo-900/30 to-purple-900/30 rounded-xl border border-indigo-500/30">
|
||||
<div className="text-indigo-400 font-semibold text-sm mb-1">Next Milestone</div>
|
||||
<div className="text-white text-sm">{aiLearningData.nextMilestone}</div>
|
||||
</div>
|
||||
|
||||
{/* AI Recommendation */}
|
||||
<div className="mt-4 p-3 bg-gradient-to-r from-cyan-900/30 to-blue-900/30 rounded-xl border border-cyan-500/30">
|
||||
<div className="text-cyan-400 font-semibold text-sm mb-1">AI Recommendation</div>
|
||||
<div className="text-white text-sm">{aiLearningData.recommendation}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Enhanced AI Learning System Panel */}
|
||||
<EnhancedAILearningPanel />
|
||||
|
||||
{/* Enhanced AI Trading Analysis Panel */}
|
||||
<div className="bg-gradient-to-br from-purple-900/40 via-blue-900/30 to-purple-900/40 backdrop-blur-xl p-8 rounded-2xl border-2 border-purple-500/40 shadow-2xl shadow-purple-500/20">
|
||||
|
||||
Reference in New Issue
Block a user