//+------------------------------------------------------------------+ //| RevolutionaryAI_EA.mq5 | //| Revolutionary AI Trading with Dynamic TP/SL | //| Multi-Spectrum Analysis & Smart Orders | //+------------------------------------------------------------------+ #property copyright "Revolutionary AI Trading System" #property link "https://revolutionary-ai-trading.com" #property version "3.0" #property strict #include #include #include #include #include #include #include #include // Strategy Mode Selection enum STRATEGY_MODE { BANKER_STRATEGY, // 🏦 Institutional: Patient, multi-timeframe, high conviction WALL_STREET_STRATEGY, // 🔥 Aggressive: Fast scalping, frequent trades, quick profits HYBRID_STRATEGY // 🔄 Adaptive: Switches based on market conditions }; //+------------------------------------------------------------------+ //| INPUT PARAMETERS | //+------------------------------------------------------------------+ // === CORE SETTINGS === input group "🚀 Core Revolutionary AI Settings" input STRATEGY_MODE TradingStrategy = BANKER_STRATEGY; // Trading strategy mode input string ServerURL = "http://localhost:8000"; // Revolutionary AI Server URL input bool EnableAutoTrading = true; // Enable automatic trading input double RiskPerTrade = 2.0; // Risk per trade (%) input double MaxDailyLoss = 5.0; // Maximum daily loss (%) input int MinConfidence = 70; // Minimum AI confidence (%) // === ADVANCED FEATURES === input group "⚡ Advanced Features" input bool EnableDynamicTPSL = true; // Enable dynamic TP/SL management input bool EnablePendingOrders = true; // Enable smart pending orders input bool EnableMultiSpectrum = true; // Enable multi-spectrum analysis input bool EnableStoryDashboard = true; // Enable story dashboard display input bool EnableRealTimeSync = true; // Enable real-time strategy sync // === TIMING SETTINGS === input group "⏰ Timing & Intervals" input int AnalysisInterval = 300; // Analysis interval (seconds) - 5 minutes input int MinTimeBetweenTrades = 900; // Minimum time between trades (seconds) - 15 minutes input int TPSLUpdateInterval = 120; // TP/SL update interval (seconds) - 2 minutes input int PendingOrdersInterval = 180; // Pending orders check interval (seconds) - 3 minutes // === DASHBOARD SETTINGS === input group "🖥️ Dashboard Display" input int DashboardXPos = 20; // Dashboard X position input int DashboardYPos = 50; // Dashboard Y position input color DashboardBGColor = C'30,30,40'; // Dashboard background color input color DashboardTextColor = clrWhite; // Dashboard text color //+------------------------------------------------------------------+ //| GLOBAL VARIABLES | //+------------------------------------------------------------------+ // Core components CTrade trade; AIIntegrationManager aiManager("http://localhost:8000", ""); DashboardManager dashboard(""); SimplifiedStoryDashboard* storyDashboard = NULL; // Advanced Trading Components CAdvancedTradeManager* tradeManager = NULL; CAdvancedRiskManager* riskManager = NULL; CAdvancedIndicatorEngine* indicatorEngine = NULL; // Timing variables datetime lastAnalysisTime = 0; datetime lastTradeTime = 0; datetime lastTPSLUpdateTime = 0; datetime lastPendingOrdersCheck = 0; datetime lastStrategySyncTime = 0; // Trading state bool isTrading = false; double currentBalance = 0; double dailyPnL = 0; datetime dailyStartTime = 0; string currentStrategyMode = ""; // Analysis results string lastSignal = ""; double lastConfidence = 0; double lastEntryPrice = 0; double lastStopLoss = 0; double lastTakeProfit = 0; string lastMarketRegime = ""; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Print("🚀 Revolutionary AI EA v3.0 - Initializing..."); // Initialize components if (!InitializeComponents()) { Print("❌ Failed to initialize components"); return INIT_FAILED; } // Set up dashboard if (!SetupDashboard()) { Print("❌ Failed to setup dashboard"); return INIT_FAILED; } // Initialize daily tracking ResetDailyTracking(); // Initial strategy sync if (EnableRealTimeSync) { CheckAndSyncStrategyMode(); } Print("✅ Revolutionary AI EA initialized successfully"); return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { Print("🔄 Revolutionary AI EA - Shutting down..."); // Clean up dashboard dashboard.DestroyDashboard(); if (storyDashboard != NULL) { storyDashboard.DestroyDashboard(); delete storyDashboard; storyDashboard = NULL; } // Clean up advanced components if (tradeManager != NULL) { delete tradeManager; tradeManager = NULL; } if (riskManager != NULL) { delete riskManager; riskManager = NULL; } if (indicatorEngine != NULL) { delete indicatorEngine; indicatorEngine = NULL; } Print("✅ Revolutionary AI EA - Advanced shutdown complete"); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Update current balance currentBalance = AccountInfoDouble(ACCOUNT_BALANCE); // Check daily loss limit if (CheckDailyLossLimit()) { return; } // Strategy sync check if (EnableRealTimeSync && TimeCurrent() - lastStrategySyncTime >= AnalysisInterval) { CheckAndSyncStrategyMode(); lastStrategySyncTime = TimeCurrent(); } // AI analysis check if (TimeCurrent() - lastAnalysisTime >= AnalysisInterval) { PerformAIAnalysis(); lastAnalysisTime = TimeCurrent(); } // Dynamic TP/SL management if (EnableDynamicTPSL && TimeCurrent() - lastTPSLUpdateTime >= TPSLUpdateInterval) { ManageOpenPositions(); lastTPSLUpdateTime = TimeCurrent(); } // Smart pending orders management if (EnablePendingOrders && TimeCurrent() - lastPendingOrdersCheck >= PendingOrdersInterval) { ManagePendingOrders(); lastPendingOrdersCheck = TimeCurrent(); } // Update dashboard dashboard.UpdateDashboard(); if (EnableStoryDashboard && storyDashboard != NULL) { storyDashboard.UpdateDashboard(); } } //+------------------------------------------------------------------+ //| Initialize all components | //+------------------------------------------------------------------+ bool InitializeComponents() { // Set symbols for all components aiManager.SetSymbol(_Symbol); dashboard.SetSymbol(_Symbol); // Initialize Advanced Trade Manager if (tradeManager != NULL) delete tradeManager; tradeManager = new CAdvancedTradeManager(); if (!tradeManager.Initialize(_Symbol, 12345, RiskPerTrade)) { Print("❌ Failed to initialize Advanced Trade Manager"); return false; } Print("✅ Advanced Trade Manager initialized"); // Initialize Risk Manager if (riskManager != NULL) delete riskManager; riskManager = new CAdvancedRiskManager(); if (!riskManager.Initialize()) { Print("❌ Failed to initialize Risk Manager"); return false; } // Set risk parameters RiskParameters riskParams; riskParams.maxRiskPerTrade = RiskPerTrade; riskParams.maxDailyRisk = MaxDailyLoss; riskParams.maxDrawdown = 15.0; riskParams.maxCorrelation = 0.7; riskParams.maxPositionSize = 10.0; riskParams.maxOpenPositions = 3; riskParams.emergencyStopLevel = 20.0; riskManager.SetRiskParameters(riskParams); Print("✅ Risk Manager initialized with professional parameters"); // Initialize Indicator Engine if (indicatorEngine != NULL) delete indicatorEngine; indicatorEngine = new CAdvancedIndicatorEngine(); if (!indicatorEngine.Initialize(_Symbol, PERIOD_H1)) { Print("❌ Failed to initialize Indicator Engine"); return false; } Print("✅ Technical Indicator Engine initialized"); // Initialize story dashboard if (EnableStoryDashboard) { if (storyDashboard != NULL) delete storyDashboard; storyDashboard = new SimplifiedStoryDashboard(&aiManager, _Symbol, DashboardXPos + 400, DashboardYPos); Print("✅ Story Dashboard initialized"); } return true; } //+------------------------------------------------------------------+ //| Setup dashboard display | //+------------------------------------------------------------------+ bool SetupDashboard() { // Create main dashboard if (!dashboard.CreateDashboard()) { Print("❌ Failed to create main dashboard"); return false; } // Create story dashboard if (EnableStoryDashboard && storyDashboard != NULL && !storyDashboard.CreateDashboard()) { Print("❌ Failed to create story dashboard"); return false; } return true; } //+------------------------------------------------------------------+ //| Perform AI analysis and get trading signals | //+------------------------------------------------------------------+ void PerformAIAnalysis() { if (!EnableAutoTrading) return; Print("🧠 Performing AI analysis..."); // Get current market data string marketData = PrepareMarketData(); // Send analysis request to AI server string analysisResult; if (EnableMultiSpectrum) { analysisResult = aiManager.GetRevolutionaryAnalysis(marketData); } else { analysisResult = aiManager.GetBasicAnalysis(marketData); } if (analysisResult != "") { ProcessAnalysisResult(analysisResult); } } //+------------------------------------------------------------------+ //| Process AI analysis results | //+------------------------------------------------------------------+ void ProcessAnalysisResult(string analysisJson) { // Parse analysis result AIAnalysisResult result = aiManager.ParseAnalysisResult(analysisJson); // Update global variables lastSignal = EnumToString(result.signal); lastConfidence = result.confidence; lastEntryPrice = result.entry_price; lastStopLoss = result.stop_loss; lastTakeProfit = result.take_profit; lastMarketRegime = result.market_regime; // Update dashboard dashboard.UpdateAnalysisInfo(result); // Execute trading logic if confidence is sufficient if (result.confidence >= MinConfidence) { ExecuteTradingStrategy(result); } Print("📊 Analysis processed - Signal: " + lastSignal + ", Confidence: " + DoubleToString(lastConfidence, 1) + "%"); } //+------------------------------------------------------------------+ //| Execute trading strategy based on analysis | //+------------------------------------------------------------------+ void ExecuteTradingStrategy(AIAnalysisResult &result) { // Check minimum time between trades if (TimeCurrent() - lastTradeTime < MinTimeBetweenTrades) { Print("⏰ Minimum time between trades not met"); return; } // Get technical analysis confirmation IndicatorSignal techSignal = indicatorEngine.GetSignal(); // Risk management check if (!riskManager.IsTradeAllowed(_Symbol, ORDER_TYPE_BUY, 0.1)) { Print("🚫 Trade blocked by risk management"); return; } // Combine AI and technical analysis bool signalConfirmed = false; if (result.signal == AI_SIGNAL_BUY && techSignal.signal == SIGNAL_BUY) { signalConfirmed = true; Print("✅ BULLISH signal confirmed by both AI and technical analysis"); } else if (result.signal == AI_SIGNAL_SELL && techSignal.signal == SIGNAL_SELL) { signalConfirmed = true; Print("✅ BEARISH signal confirmed by both AI and technical analysis"); } if (!signalConfirmed) { Print("⚠️ AI and technical signals not aligned - skipping trade"); return; } // Apply strategy-specific logic switch(TradingStrategy) { case BANKER_STRATEGY: ExecuteBankerStrategy(result); break; case WALL_STREET_STRATEGY: ExecuteWallStreetStrategy(result); break; case HYBRID_STRATEGY: ExecuteHybridStrategy(result); break; } } //+------------------------------------------------------------------+ //| Execute Banker Strategy (Conservative, High Conviction) | //+------------------------------------------------------------------+ void ExecuteBankerStrategy(AIAnalysisResult &result) { // Banker strategy requires higher confidence if (result.confidence < 80) return; // Conservative position sizing double lotSize = CalculateLotSize(RiskPerTrade * 0.7); // Reduced risk if (result.signal == AI_SIGNAL_BUY) { OpenPosition(ORDER_TYPE_BUY, lotSize, result); } else if (result.signal == AI_SIGNAL_SELL) { OpenPosition(ORDER_TYPE_SELL, lotSize, result); } } //+------------------------------------------------------------------+ //| Execute Wall Street Strategy (Aggressive, Fast Scalping) | //+------------------------------------------------------------------+ void ExecuteWallStreetStrategy(AIAnalysisResult &result) { // Wall Street strategy allows lower confidence but faster execution if (result.confidence < 65) return; // Aggressive position sizing double lotSize = CalculateLotSize(RiskPerTrade * 1.2); // Increased risk if (result.signal == AI_SIGNAL_BUY) { OpenPosition(ORDER_TYPE_BUY, lotSize, result); } else if (result.signal == AI_SIGNAL_SELL) { OpenPosition(ORDER_TYPE_SELL, lotSize, result); } } //+------------------------------------------------------------------+ //| Execute Hybrid Strategy (Adaptive) | //+------------------------------------------------------------------+ void ExecuteHybridStrategy(AIAnalysisResult &result) { // Hybrid strategy adapts based on market regime double confidenceThreshold = 75; double riskMultiplier = 1.0; if (result.market_regime == "High Volatility") { confidenceThreshold = 80; riskMultiplier = 0.8; // Reduce risk in high volatility } else if (result.market_regime == "Low Volatility") { confidenceThreshold = 70; riskMultiplier = 1.1; // Slightly increase risk in low volatility } if (result.confidence < confidenceThreshold) return; double lotSize = CalculateLotSize(RiskPerTrade * riskMultiplier); if (result.signal == AI_SIGNAL_BUY) { OpenPosition(ORDER_TYPE_BUY, lotSize, result); } else if (result.signal == AI_SIGNAL_SELL) { OpenPosition(ORDER_TYPE_SELL, lotSize, result); } } //+------------------------------------------------------------------+ //| Open trading position | //+------------------------------------------------------------------+ void OpenPosition(ENUM_ORDER_TYPE orderType, double lotSize, AIAnalysisResult &result) { // Use professional trade manager TradeResult tradeResult; string comment = "Revolutionary AI v3.0 - " + EnumToString(TradingStrategy); // Calculate optimal lot size using risk management double stopLossPoints = MathAbs(result.entry_price - result.stop_loss) / SymbolInfoDouble(_Symbol, SYMBOL_POINT); double optimalLotSize = riskManager.CalculateOptimalLotSize(_Symbol, RiskPerTrade, stopLossPoints); // Use the smaller of requested and optimal lot size lotSize = MathMin(lotSize, optimalLotSize); // Get dynamic TP/SL levels double sl = result.stop_loss; double tp = result.take_profit; if (EnableDynamicTPSL) { // Enhanced TP/SL using technical levels MarketStructure structure = indicatorEngine.GetMarketStructure(); if (orderType == ORDER_TYPE_BUY) { sl = MathMax(sl, structure.support * 0.999); // Use support as SL floor tp = MathMin(tp, structure.resistance * 1.001); // Use resistance as TP ceiling } else { sl = MathMin(sl, structure.resistance * 1.001); // Use resistance as SL ceiling tp = MathMax(tp, structure.support * 0.999); // Use support as TP floor } } // Execute trade using professional trade manager if (orderType == ORDER_TYPE_BUY) { tradeResult = tradeManager.OpenBuy(lotSize, sl, tp, comment); } else { tradeResult = tradeManager.OpenSell(lotSize, sl, tp, comment); } if (tradeResult.success) { lastTradeTime = TimeCurrent(); // Add position to risk manager tracking riskManager.AddPosition(tradeResult.ticket, _Symbol, lotSize, sl); Print("✅ Professional trade executed: " + EnumToString(orderType) + " " + DoubleToString(lotSize, 2) + " lots, Ticket: " + IntegerToString(tradeResult.ticket)); Print("📊 Entry: " + DoubleToString(tradeResult.price, _Digits) + ", SL: " + DoubleToString(sl, _Digits) + ", TP: " + DoubleToString(tp, _Digits)); // Update dashboard dashboard.UpdateTradeInfo(orderType, lotSize, tradeResult.price, result.confidence); // Print risk report riskManager.PrintRiskReport(); } else { Print("❌ Professional trade failed: " + tradeResult.message); Print("🔍 Error code: " + IntegerToString(tradeResult.retcode)); } } //+------------------------------------------------------------------+ //| Calculate lot size based on risk management | //+------------------------------------------------------------------+ double CalculateLotSize(double riskPercent) { // Use professional risk manager for lot size calculation double stopLossPoints = 50; // Default stop loss in points double optimalLotSize = riskManager.CalculateOptimalLotSize(_Symbol, riskPercent, stopLossPoints); // Also check trade manager calculation double tradeManagerLotSize = tradeManager.CalculateOptimalLotSize(riskPercent, stopLossPoints); // Use the more conservative (smaller) lot size double finalLotSize = MathMin(optimalLotSize, tradeManagerLotSize); Print("📊 Risk Manager Lot Size: " + DoubleToString(optimalLotSize, 3)); Print("📊 Trade Manager Lot Size: " + DoubleToString(tradeManagerLotSize, 3)); Print("📊 Final Lot Size: " + DoubleToString(finalLotSize, 3)); return finalLotSize; } //+------------------------------------------------------------------+ //| Manage open positions with dynamic TP/SL | //+------------------------------------------------------------------+ void ManageOpenPositions() { // Update risk manager position tracking riskManager.UpdatePositionRisk(); // Update trailing stops using trade manager tradeManager.UpdateTrailingStops(); // Check for emergency stop conditions if (riskManager.IsEmergencyStop()) { Print("🚨 EMERGENCY STOP TRIGGERED - Closing all positions"); tradeManager.CloseAllPositions(); return; } // Enhanced position management for (int i = PositionsTotal() - 1; i >= 0; i--) { if (PositionSelectByIndex(i) && PositionGetString(POSITION_SYMBOL) == _Symbol) { ulong ticket = PositionGetInteger(POSITION_TICKET); // Get current technical analysis IndicatorSignal currentSignal = indicatorEngine.GetSignal(); MarketStructure structure = indicatorEngine.GetMarketStructure(); // Check if position should be closed based on technical analysis ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); bool shouldClose = false; if (posType == POSITION_TYPE_BUY && currentSignal.signal == SIGNAL_SELL && currentSignal.strength >= SIGNAL_STRONG) { shouldClose = true; Print("📉 Closing BUY position due to strong SELL signal"); } else if (posType == POSITION_TYPE_SELL && currentSignal.signal == SIGNAL_BUY && currentSignal.strength >= SIGNAL_STRONG) { shouldClose = true; Print("📈 Closing SELL position due to strong BUY signal"); } if (shouldClose) { if (tradeManager.ClosePosition(ticket)) { riskManager.RemovePosition(ticket); Print("✅ Position closed due to technical signal reversal"); } } else { // Get updated TP/SL from AI if no closure needed string tpslData = aiManager.GetDynamicTPSL(ticket); if (tpslData != "") { // Parse and update TP/SL UpdatePositionTPSL(ticket, tpslData); } } } } // Print risk report periodically static datetime lastRiskReport = 0; if (TimeCurrent() - lastRiskReport >= 3600) // Every hour { riskManager.PrintRiskReport(); indicatorEngine.PrintAnalysis(); lastRiskReport = TimeCurrent(); } } //+------------------------------------------------------------------+ //| Update position TP/SL based on AI recommendations | //+------------------------------------------------------------------+ void UpdatePositionTPSL(ulong ticket, string tpslJson) { // Parse TP/SL data from AI response double newSL, newTP; if (aiManager.ParseTPSLUpdate(tpslJson, newSL, newTP)) { if (trade.PositionModify(ticket, newSL, newTP)) { Print("✅ Updated TP/SL for position " + IntegerToString(ticket)); } } } //+------------------------------------------------------------------+ //| Manage smart pending orders | //+------------------------------------------------------------------+ void ManagePendingOrders() { // Get pending order recommendations from AI string pendingOrdersData = aiManager.GetSmartPendingOrders(); if (pendingOrdersData != "") { ProcessPendingOrdersRecommendations(pendingOrdersData); } } //+------------------------------------------------------------------+ //| Process pending orders recommendations | //+------------------------------------------------------------------+ void ProcessPendingOrdersRecommendations(string ordersJson) { // Parse and process pending order recommendations aiManager.ProcessPendingOrdersResponse(ordersJson); } //+------------------------------------------------------------------+ //| Check and sync strategy mode with server | //+------------------------------------------------------------------+ void CheckAndSyncStrategyMode() { StrategyModeInfo modeInfo = aiManager.GetCurrentStrategyMode(); if (modeInfo.current_mode != currentStrategyMode) { currentStrategyMode = modeInfo.current_mode; // Update strategy based on server recommendation if (modeInfo.current_mode == "BANKER") { TradingStrategy = BANKER_STRATEGY; } else if (modeInfo.current_mode == "WALL_STREET") { TradingStrategy = WALL_STREET_STRATEGY; } else if (modeInfo.current_mode == "HYBRID") { TradingStrategy = HYBRID_STRATEGY; } Print("🔄 Strategy mode synced: " + currentStrategyMode); dashboard.UpdateStrategyMode(currentStrategyMode); } } //+------------------------------------------------------------------+ //| Prepare market data for AI analysis | //+------------------------------------------------------------------+ string PrepareMarketData() { // Collect current market data double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double spread = ask - bid; // Get recent price data MqlRates rates[]; int copied = CopyRates(_Symbol, PERIOD_M5, 0, 100, rates); // Prepare JSON data string marketData = "{"; marketData += "\"symbol\":\"" + _Symbol + "\","; marketData += "\"bid\":" + DoubleToString(bid, _Digits) + ","; marketData += "\"ask\":" + DoubleToString(ask, _Digits) + ","; marketData += "\"spread\":" + DoubleToString(spread, _Digits) + ","; marketData += "\"timestamp\":" + IntegerToString(TimeCurrent()) + ","; marketData += "\"strategy_mode\":\"" + EnumToString(TradingStrategy) + "\","; marketData += "\"rates\":["; for (int i = 0; i < copied && i < 20; i++) // Send last 20 bars { if (i > 0) marketData += ","; marketData += "{"; marketData += "\"time\":" + IntegerToString(rates[i].time) + ","; marketData += "\"open\":" + DoubleToString(rates[i].open, _Digits) + ","; marketData += "\"high\":" + DoubleToString(rates[i].high, _Digits) + ","; marketData += "\"low\":" + DoubleToString(rates[i].low, _Digits) + ","; marketData += "\"close\":" + DoubleToString(rates[i].close, _Digits) + ","; marketData += "\"volume\":" + IntegerToString(rates[i].tick_volume); marketData += "}"; } marketData += "]}"; return marketData; } //+------------------------------------------------------------------+ //| Check daily loss limit | //+------------------------------------------------------------------+ bool CheckDailyLossLimit() { // Reset daily tracking if new day if (TimeToStruct(TimeCurrent()).day != TimeToStruct(dailyStartTime).day) { ResetDailyTracking(); } // Calculate daily P&L dailyPnL = AccountInfoDouble(ACCOUNT_BALANCE) - AccountInfoDouble(ACCOUNT_BALANCE); // Simplified // Check loss limit if (dailyPnL < -MaxDailyLoss) { Print("🚨 Daily loss limit reached: " + DoubleToString(dailyPnL, 2) + "%"); return true; } return false; } //+------------------------------------------------------------------+ //| Reset daily tracking variables | //+------------------------------------------------------------------+ void ResetDailyTracking() { dailyStartTime = TimeCurrent(); dailyPnL = 0; }