feat: Complete live trading decisions visibility system
LIVE TRADING ANALYSIS PANEL - Real-time decision tracking - Live decisions API endpoint (/api/automation/live-decisions) - Complete automation-v2 page with enhanced AI trading analysis - Real-time visibility into AI's trading decisions and reasoning - Block reason display showing why trades are prevented - Execution details with entry, SL, TP, leverage, and reasoning - Auto-refreshing decision history (30-second intervals) - Enhanced risk management integration MANDATORY RISK MANAGEMENT SYSTEM - Mandatory risk manager with strict validation - Emergency position protection system - Stop loss direction validation (below entry for BUY, above for SELL) - Integration with automation system for real-time blocking AUTOMATION PAGE ENHANCEMENT - All original automation-v2 features preserved - Multi-timeframe selection with presets - Trading configuration controls - Account balance and position monitoring - Enhanced AI Learning Panel integration - Live status indicators and feedback COMPREHENSIVE TESTING - Live decisions API testing harness - Risk management validation tests - Sample decision data for development The system now provides complete transparency into: - ✅ Trade execution decisions with full reasoning - ✅ Risk management blocks with specific reasons - ✅ AI analysis and confidence levels - ✅ Real-time decision tracking and history - ✅ Entry, stop loss, take profit details - ✅ Leverage calculations and risk assessment Tested and working on development container (port 9001:3000)
This commit is contained in:
@@ -891,6 +891,71 @@ class SimpleAutomation {
|
||||
console.warn('⚠️ Pre-trade cleanup error:', cleanupError.message);
|
||||
}
|
||||
|
||||
// 🛡️ MANDATORY RISK MANAGEMENT - NO TRADE WITHOUT PROPER SL/TP
|
||||
console.log('🛡️ ENFORCING MANDATORY RISK MANAGEMENT...');
|
||||
try {
|
||||
const { MandatoryRiskManager } = require('./mandatory-risk-manager');
|
||||
const riskManager = new MandatoryRiskManager();
|
||||
|
||||
// Get current price for risk calculations
|
||||
const currentPrice = analysis.entry?.price || analysis.currentPrice || 185; // fallback
|
||||
|
||||
// Enforce mandatory risk management
|
||||
const validatedTrade = await riskManager.enforceRiskManagement({
|
||||
symbol: this.config.symbol,
|
||||
side: side,
|
||||
amount: this.config.tradingAmount || 49,
|
||||
currentPrice: currentPrice,
|
||||
stopLoss: stopLoss,
|
||||
takeProfit: takeProfit,
|
||||
leverage: optimalLeverage
|
||||
});
|
||||
|
||||
// Update with validated/calculated SL/TP
|
||||
stopLoss = validatedTrade.stopLoss;
|
||||
takeProfit = validatedTrade.takeProfit;
|
||||
|
||||
console.log('✅ MANDATORY RISK MANAGEMENT PASSED');
|
||||
console.log(` Final SL: $${stopLoss.toFixed(2)}`);
|
||||
console.log(` Final TP: $${takeProfit.toFixed(2)}`);
|
||||
|
||||
} catch (riskError) {
|
||||
console.error('🚫 TRADE BLOCKED BY RISK MANAGEMENT:', riskError.message);
|
||||
|
||||
// Log the blocked decision for live analysis panel
|
||||
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: 'TRADE_BLOCKED',
|
||||
action: side?.toUpperCase() || 'UNKNOWN',
|
||||
symbol: this.config.symbol,
|
||||
blocked: true,
|
||||
blockReason: riskError.message,
|
||||
confidence: analysis.confidence || 0,
|
||||
entryPrice: analysis.entry?.price || analysis.currentPrice || 0,
|
||||
stopLoss: analysis.exit?.stopLoss || null,
|
||||
takeProfit: analysis.exit?.takeProfit || null,
|
||||
leverage: optimalLeverage,
|
||||
reasoning: analysis.reasoning || 'No reasoning provided',
|
||||
timestamp: new Date().toISOString(),
|
||||
cycle: this.stats.totalCycles
|
||||
})
|
||||
});
|
||||
} catch (logError) {
|
||||
console.warn('⚠️ Failed to log blocked decision:', logError.message);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: 'Trade blocked by mandatory risk management',
|
||||
details: riskError.message,
|
||||
riskManagementBlocked: true
|
||||
};
|
||||
}
|
||||
|
||||
// Use the trading API with proper fields for Drift
|
||||
const tradePayload = {
|
||||
symbol: this.config.symbol,
|
||||
@@ -918,6 +983,35 @@ class SimpleAutomation {
|
||||
this.stats.totalTrades = (this.stats.totalTrades || 0) + 1;
|
||||
this.stats.successfulTrades = (this.stats.successfulTrades || 0) + 1;
|
||||
|
||||
// Log the successful trade for live analysis panel
|
||||
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: 'TRADE_EXECUTED',
|
||||
action: side?.toUpperCase() || 'UNKNOWN',
|
||||
symbol: this.config.symbol,
|
||||
blocked: false,
|
||||
executed: true,
|
||||
confidence: analysis.confidence || 0,
|
||||
entryPrice: analysis.entry?.price || analysis.currentPrice || 0,
|
||||
stopLoss: stopLoss,
|
||||
takeProfit: takeProfit,
|
||||
leverage: optimalLeverage,
|
||||
amount: tradePayload.amount,
|
||||
reasoning: analysis.reasoning || 'No reasoning provided',
|
||||
aiLeverageReasoning: leverageResult ? leverageResult.reasoning : 'AI leverage calculation not available',
|
||||
txId: result.transactionId || result.signature,
|
||||
timestamp: new Date().toISOString(),
|
||||
cycle: this.stats.totalCycles
|
||||
})
|
||||
});
|
||||
} catch (logError) {
|
||||
console.warn('⚠️ Failed to log executed trade:', logError.message);
|
||||
}
|
||||
|
||||
// Update DCA timestamp to prevent over-execution
|
||||
this.lastDCATime = Date.now();
|
||||
console.log(`⏰ DCA cooldown activated - Next DCA possible in ${this.dcaCooldownHours} hours`);
|
||||
|
||||
Reference in New Issue
Block a user