//+------------------------------------------------------------------+
//|                                                 ProfitLockEA.mq4 |
//|                                                 Copyright 2024   |  
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link      "https://t.me/myfreeresources_bot?start=resources"
#property version   "0.1"
#property strict

#import "user32.dll"
   int PostMessageA(int hWnd, int Msg, int wParam, int lParam);
   int FindWindowA(string lpClassName, string lpWindowName);
   int FindWindowExA(int hWndParent, int hWndChildAfter, string lpszClass, string lpszWindow);
#import

input int ProfitTrades = 2;
input bool HardDisable = true;

int startHistoryCount = 0;
int profitsSinceStart = 0;
bool disabled = false;

int OnInit()
{
   startHistoryCount = OrdersHistoryTotal();
   Print("ProfitLockEA: Monitoring from trade #", startHistoryCount);
   return INIT_SUCCEEDED;
}

void OnTick()
{
   if(disabled) return;
   
   int currentHistory = OrdersHistoryTotal();
   if(currentHistory > startHistoryCount) {
      
      // Check only new trades since EA started
      for(int i = startHistoryCount; i < currentHistory; i++) {
         if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
            if(OrderProfit() > 0) {
               profitsSinceStart++;
               Print("Profit trade #", profitsSinceStart, " detected");
            }
         }
      }
      
      startHistoryCount = currentHistory;
      
      if(profitsSinceStart >= ProfitTrades) {
         if(HardDisable) {
            DisableAutoTrading();
         } else {
            disabled = true;
            Alert("EA disabled after ", profitsSinceStart, " profits");
         }
      }
   }
}

void DisableAutoTrading()
{
   int hMT4 = FindWindowA("MetaQuotes::MetaTrader4::", NULL);
   if(hMT4 > 0) {
      int hToolbar = FindWindowExA(hMT4, 0, "ToolbarWindow32", NULL);
      if(hToolbar > 0) {
         PostMessageA(hToolbar, 0x111, 32851, 0);
         disabled = true;
         Alert("AutoTrading DISABLED after ", profitsSinceStart, " profits");
      }
   }
}