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)
97 lines
4.3 KiB
JavaScript
97 lines
4.3 KiB
JavaScript
const { MandatoryRiskManager } = require('./lib/mandatory-risk-manager');
|
|
|
|
async function emergencyProtectAllPositions() {
|
|
try {
|
|
console.log('🚨 EMERGENCY POSITION PROTECTION SYSTEM ACTIVATED');
|
|
console.log('🔍 Scanning for unprotected positions...');
|
|
|
|
const riskManager = new MandatoryRiskManager();
|
|
|
|
// Check current position
|
|
const positionResponse = await fetch('http://localhost:9001/api/automation/position-monitor');
|
|
const positionData = await positionResponse.json();
|
|
|
|
if (!positionData.monitor.hasPosition) {
|
|
console.log('✅ No active positions found - no emergency protection needed');
|
|
return;
|
|
}
|
|
|
|
const position = positionData.monitor.position;
|
|
console.log('📊 Active position detected:', {
|
|
symbol: position.symbol,
|
|
side: position.side,
|
|
size: position.size,
|
|
entryPrice: position.entryPrice,
|
|
currentPrice: position.currentPrice,
|
|
unrealizedPnl: position.unrealizedPnl
|
|
});
|
|
|
|
// Check if position has protective orders
|
|
const ordersResponse = await fetch('http://localhost:9001/api/drift/orders');
|
|
const ordersData = await ordersResponse.json();
|
|
|
|
const activeOrders = ordersData.orders?.filter(order => order.isActive) || [];
|
|
console.log(`📋 Active protective orders: ${activeOrders.length}`);
|
|
|
|
if (activeOrders.length === 0) {
|
|
console.log('🚨 UNPROTECTED POSITION DETECTED - CALCULATING EMERGENCY PROTECTION');
|
|
|
|
const protection = await riskManager.emergencyProtectPosition({
|
|
side: position.side,
|
|
size: position.size,
|
|
entryPrice: position.entryPrice
|
|
});
|
|
|
|
console.log('⚠️ EMERGENCY PROTECTION REQUIRED:');
|
|
console.log(` Current Position: ${position.side.toUpperCase()} ${position.size} @ $${position.entryPrice.toFixed(2)}`);
|
|
console.log(` Current P&L: $${position.unrealizedPnl.toFixed(2)}`);
|
|
console.log(` Required Stop-Loss: $${protection.stopLoss.toFixed(2)}`);
|
|
console.log(` Required Take-Profit: $${protection.takeProfit.toFixed(2)}`);
|
|
console.log('');
|
|
console.log('🔧 MANUAL ACTION REQUIRED - Place these orders immediately:');
|
|
|
|
if (position.side === 'short') {
|
|
console.log(` 1. Stop-Loss: LONG ${position.size} SOL @ $${protection.stopLoss.toFixed(2)} (trigger order, reduceOnly: true)`);
|
|
console.log(` 2. Take-Profit: LONG ${position.size} SOL @ $${protection.takeProfit.toFixed(2)} (limit order, reduceOnly: true)`);
|
|
} else {
|
|
console.log(` 1. Stop-Loss: SHORT ${position.size} SOL @ $${protection.stopLoss.toFixed(2)} (trigger order, reduceOnly: true)`);
|
|
console.log(` 2. Take-Profit: SHORT ${position.size} SOL @ $${protection.takeProfit.toFixed(2)} (limit order, reduceOnly: true)`);
|
|
}
|
|
|
|
console.log('');
|
|
console.log('⚡ RISK ASSESSMENT:');
|
|
if (position.unrealizedPnl > 0) {
|
|
console.log(` ✅ Position is currently PROFITABLE (+$${position.unrealizedPnl.toFixed(2)})`);
|
|
console.log(' 🎯 Secure profits with take-profit order');
|
|
} else {
|
|
console.log(` ⚠️ Position is currently at LOSS ($${position.unrealizedPnl.toFixed(2)})`);
|
|
console.log(' 🛑 Limit further losses with stop-loss order');
|
|
}
|
|
|
|
// Calculate potential loss without stop-loss
|
|
const currentPrice = position.currentPrice;
|
|
const worstCasePrice = position.side === 'short' ? currentPrice * 1.10 : currentPrice * 0.90;
|
|
const worstCaseLoss = position.side === 'short' ?
|
|
(worstCasePrice - position.entryPrice) * position.size :
|
|
(position.entryPrice - worstCasePrice) * position.size;
|
|
|
|
console.log('');
|
|
console.log('💥 WITHOUT STOP-LOSS PROTECTION:');
|
|
console.log(` Potential 10% adverse move could cost: $${Math.abs(worstCaseLoss).toFixed(2)}`);
|
|
console.log(' PROTECTION IS CRITICAL!');
|
|
|
|
} else {
|
|
console.log('✅ Position has protective orders in place:');
|
|
activeOrders.forEach(order => {
|
|
console.log(` ${order.direction} ${order.size} @ $${order.price} (${order.orderType})`);
|
|
});
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ Emergency protection system error:', error);
|
|
}
|
|
}
|
|
|
|
// Run emergency protection check
|
|
emergencyProtectAllPositions();
|