//+------------------------------------------------------------------+
//|                        CloseBySymbolOnProfitPercentOfBalance.mq4 |
//|                                  Copyright 2025, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

#import "user32.dll"
    void keybd_event(int bVk, int bScan, int dwFlags, int dwExtraInfo);
#import

#define REL  0x0002
#define CTRL 0x11
#define E    0x45

//--- Input parameters
input double ProfitPercentOfBalance = 1.0; // Profit % to trigger close and disable (e.g., 1%)

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Print("CloseOnProfit EA initialized.");
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Print("CloseOnProfit EA deinitialized.");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   double totalSymbolProfit = 0.0;
   double balance = AccountBalance();
   
   //--- Calculate total profit for this symbol
   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == _Symbol)
         {
            totalSymbolProfit += OrderProfit() + OrderSwap() + OrderCommission();
         }
      }
   }
   
   double triggerProfit = (ProfitPercentOfBalance/100.0) * balance;
   
   if(totalSymbolProfit >= triggerProfit)
   {
      //--- Close all trades and delete pending orders
      CloseAndDeleteAllSymbolOrders(_Symbol);
      
      //--- Check again if there are no orders left for the symbol
      bool noOrdersLeft = true;
      for(int j=OrdersTotal()-1; j>=0; j--)
      {
         if(OrderSelect(j, SELECT_BY_POS, MODE_TRADES))
         {
            if(OrderSymbol() == _Symbol)
            {
               noOrdersLeft = false;
               break;
            }
         }
      }
      
      //--- If no more orders, disable Auto Trading (simulate Ctrl+E)
      if(noOrdersLeft&&IsAutoTradingAllowed())
      {
         DisableAutoTrading();
      }
   }
  }
//+------------------------------------------------------------------+
//| Function to close and delete all orders for the symbol          |
//+------------------------------------------------------------------+
void CloseAndDeleteAllSymbolOrders(string symbol)
{
   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == symbol)
         {
            if(OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
               double price = (OrderType() == OP_BUY) ? Bid : Ask;
               int slippage = 3;
               if(!OrderClose(OrderTicket(), OrderLots(), price, slippage, clrRed))
               {
                  Print("Failed to close order #", OrderTicket(), " Error: ", GetLastError());
                  Sleep(500);
                  RefreshRates();
                  if(!OrderClose(OrderTicket(), OrderLots(), price, slippage, clrRed))
                  {
                     Print("Retry failed to close order #", OrderTicket(), " Error: ", GetLastError());
                  }
                  else
                  {
                     Print("Retry SUCCESS to close order #", OrderTicket());
                  }
               }
            }
            else if(OrderType() == OP_BUYLIMIT || OrderType() == OP_BUYSTOP || 
                    OrderType() == OP_SELLLIMIT || OrderType() == OP_SELLSTOP)
            {
               if(!OrderDelete(OrderTicket()))
               {
                  Print("Failed to delete pending order #", OrderTicket(), " Error: ", GetLastError());
                  Sleep(500);
                  if(!OrderDelete(OrderTicket()))
                  {
                     Print("Retry failed to delete pending order #", OrderTicket(), " Error: ", GetLastError());
                  }
                  else
                  {
                     Print("Retry SUCCESS to delete pending order #", OrderTicket());
                  }
               }
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Function to simulate Ctrl+E                                      |
//+------------------------------------------------------------------+
void DisableAutoTrading()
  {
   Print("Simulating Ctrl+E to disable Auto Trading...");
   
   keybd_event(CTRL,0,0,  0);
   keybd_event(E,   0,0,  0);
   keybd_event(CTRL,0,REL,0);
   keybd_event(E,   0,REL,0);
  }
//+------------------------------------------------------------------+
bool IsAutoTradingAllowed()
{
   return (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) ? false : true);
}
//+------------------------------------------------------------------+
