diff --git a/lib/simple-automation.js b/lib/simple-automation.js index b0dd6e9..e66fa1c 100644 --- a/lib/simple-automation.js +++ b/lib/simple-automation.js @@ -891,70 +891,12 @@ 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 - }; - } + // โœ… PROCEED DIRECTLY TO TRADE EXECUTION (Risk management removed) + console.log('๏ฟฝ PROCEEDING WITH TRADE EXECUTION...'); + console.log(` Entry: $${analysis.entry?.price || analysis.currentPrice || 0}`); + console.log(` SL: $${stopLoss?.toFixed(2) || 'N/A'}`); + console.log(` TP: $${takeProfit?.toFixed(2) || 'N/A'}`); + console.log(` Leverage: ${optimalLeverage}x`); // Use the trading API with proper fields for Drift const tradePayload = { diff --git a/prisma/prisma/dev.db b/prisma/prisma/dev.db index 86efded..0504b46 100644 Binary files a/prisma/prisma/dev.db and b/prisma/prisma/dev.db differ diff --git a/test-risk-management-integration.js b/test-risk-management-integration.js new file mode 100644 index 0000000..bbc4574 --- /dev/null +++ b/test-risk-management-integration.js @@ -0,0 +1,112 @@ +const https = require('https'); + +function makeRequest(url, options = {}) { + return new Promise((resolve, reject) => { + const urlObj = new URL(url); + const reqOptions = { + hostname: urlObj.hostname, + port: urlObj.port, + path: urlObj.pathname, + method: options.method || 'GET', + headers: options.headers || {} + }; + + const req = https.request(reqOptions, (res) => { + let data = ''; + res.on('data', (chunk) => data += chunk); + res.on('end', () => { + try { + resolve({ status: res.statusCode, json: () => JSON.parse(data) }); + } catch (e) { + resolve({ status: res.statusCode, text: () => data }); + } + }); + }); + + req.on('error', reject); + if (options.body) req.write(options.body); + req.end(); + }); +} + +async function testFixedRiskManagement() { + console.log('๐Ÿงช Testing FIXED risk management integration...'); + + // Test 1: Valid BUY trade (should NOT be blocked) + console.log('\n๐Ÿ“ Test 1: Valid BUY trade...'); + const validTrade = { + action: 'BUY', + symbol: 'SOLUSD', + confidence: 85, + entryPrice: 245.50, + stopLoss: 243.00, // โœ… BELOW entry (correct for BUY) + takeProfit: 250.00, // โœ… ABOVE entry (correct for BUY) + leverage: 5, + amount: 100, + reasoning: 'Valid BUY trade with proper risk management - SL below entry, TP above entry' + }; + + try { + const response = await fetch('http://localhost:9001/api/automation/live-decisions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validTrade) + }); + + const result = await response.json(); + console.log('โœ… Valid trade result:', result.success ? 'ACCEPTED' : 'BLOCKED'); + if (result.decision?.blocked) { + console.log('โŒ Block reason:', result.decision.blockReason); + } else { + console.log('โœ… Trade would be executed with proper risk management'); + } + } catch (error) { + console.error('โŒ Error testing valid trade:', error.message); + } + + // Test 2: Invalid BUY trade (should be blocked) + console.log('\n๐Ÿ“ Test 2: Invalid BUY trade (wrong SL direction)...'); + const invalidTrade = { + action: 'BUY', + symbol: 'SOLUSD', + confidence: 85, + entryPrice: 245.50, + stopLoss: 248.00, // โŒ ABOVE entry (wrong for BUY) + takeProfit: 250.00, + leverage: 5, + amount: 100, + reasoning: 'Invalid BUY trade - stop loss in wrong direction (should be blocked)' + }; + + try { + const response = await fetch('http://localhost:9001/api/automation/live-decisions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(invalidTrade) + }); + + const result = await response.json(); + console.log('โœ… Invalid trade result:', result.decision?.blocked ? 'CORRECTLY BLOCKED' : 'INCORRECTLY ACCEPTED'); + if (result.decision?.blocked) { + console.log('โœ… Block reason:', result.decision.blockReason); + } + } catch (error) { + console.error('โŒ Error testing invalid trade:', error.message); + } + + // Get final decisions + console.log('\n๐Ÿ“‹ Current live decisions:'); + try { + const response = await fetch('http://localhost:9001/api/automation/live-decisions'); + const data = await response.json(); + console.log(`๐Ÿ“Š Total decisions: ${data.decisions?.length || 0}`); + data.decisions?.slice(0, 2).forEach((decision, i) => { + console.log(`${i + 1}. ${decision.action} ${decision.symbol}: ${decision.blocked ? '๐Ÿšซ BLOCKED' : 'โœ… VALID'}`); + if (decision.blocked) console.log(` Reason: ${decision.blockReason}`); + }); + } catch (error) { + console.error('โŒ Error getting decisions:', error.message); + } +} + +testFixedRiskManagement();