//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>

#define INDENT_LEFT                         (11)
#define INDENT_TOP                          (11)
#define CONTROLS_GAP_X                      (5)

#define BUTTON_WIDTH                        (100)
#define BUTTON_HEIGHT                       (20)


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
class CAppWindowTwoButtons : public CAppDialog
  {

private:
   CButton           m_button1;                       // the button object
   CButton           m_button2;                       // the button object

public:
                     CAppWindowTwoButtons(void);
                    ~CAppWindowTwoButtons(void);
   //--- create
   virtual bool      Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
   //--- chart event handler
   virtual bool      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);

protected:
   //--- create dependent controls
   bool              CreateButton1(void);
   bool              CreateButton2(void);
   //--- handlers of the dependent controls events
   void              OnClickButton1(void);
   void              OnClickButton2(void);

  };
//+------------------------------------------------------------------+
//| Event Handling                                                   |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CAppWindowTwoButtons)
ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
ON_EVENT(ON_CLICK,m_button2,OnClickButton2)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::CAppWindowTwoButtons(void)
  {
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::~CAppWindowTwoButtons(void)
  {
  }
//+------------------------------------------------------------------+
//| Create                                                           |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  {
   if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
      return(false);
//--- create dependent controls
   if(!CreateButton1())
      return(false);
   if(!CreateButton2())
      return(false);
//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Global Variable                                                  |
//+------------------------------------------------------------------+
CAppWindowTwoButtons ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton1(void)
  {
//--- coordinates
   int x1=INDENT_LEFT;        // x1            = 11  pixels
   int y1=INDENT_TOP;         // y1            = 11  pixels
   int x2=x1+BUTTON_WIDTH;    // x2 = 11 + 100 = 111 pixels
   int y2=y1+BUTTON_HEIGHT;   // y2 = 11 + 20  = 32  pixels
//--- create
   if(!m_button1.Create(0,"Button1",0,x1,y1,x2,y2))
      return(false);
   if(!m_button1.Text("Закрыть sell"))
      return(false);
   if(!Add(m_button1))
      return(false);

//--- succeed
   return(true);
  }
//+------------------------------------------------------------------+
//| Create the "Button2"                                             |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton2(void)
  {
//--- coordinates
   int x1=INDENT_LEFT+120;   // x1 = 11  + 2 * (100 + 5) = 221 pixels
   int y1=INDENT_TOP;                                    // y1                       = 11  pixels
   int x2=x1+BUTTON_WIDTH;                               // x2 = 221 + 100           = 321 pixels
   int y2=y1+BUTTON_HEIGHT;                              // y2 = 11  + 20            = 31  pixels
//--- create
   if(!m_button2.Create(0,"Button2",0,x1,y1,x2,y2))
      return(false);
   if(!m_button2.Text("Закрыть buy"))
      return(false);
   if(!Add(m_button2))
      return(false);
//--- succeed
   return(true);
  }


input double BelowCurrentPriceLevel = 1;  // Уровень ниже текущей цены для алерта
input double AboveCurrentPriceLevel = 2;  // Уровень выше текущей цены для алерта
input int PipsToChange = 5;                 // Количество пунктов изменения цены
input double InitialLots = 0.1;              // Количество лотов для начальной сделки
input double LotChangePercent = 10.0;        // Процент изменения количества лотов
input ENUM_TIMEFRAMES TimeFrame = PERIOD_H1;

double currentLots = InitialLots;            // Текущее количество лотов
double lastPrice;                            // Последняя цена для отслеживания изменения на N пунктов
bool belowLevelAlerted = false;              // Флаг отправки алерта для нижнего уровня
bool aboveLevelAlerted = false;              // Флаг отправки алерта для верхнего уровня

datetime lastBarTime = 0;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {

   if(!ExtDialog.Create(0,"Закрытие позиций",0,15,100,270,220))
      return(INIT_FAILED);
//--- run application
   ExtDialog.Run();

   MqlRates rates[];
   if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0)
     {
      lastBarTime = rates[0].time;
     }
   else
     {
      Print("Ошибка при получении информации о барах: ", GetLastError());
      return (INIT_FAILED);
     }
   OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
   OpenOrder(ORDER_TYPE_SELL, currentLots, "S");

   lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);;
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
//--- destroy dialog
   ExtDialog.Destroy(reason);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,         // event ID
                  const long& lparam,   // event parameter of the long type
                  const double& dparam, // event parameter of the double type
                  const string& sparam) // event parameter of the string type
  {
   ExtDialog.ChartEvent(id,lparam,dparam,sparam);
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double NormalizeLot(double lot, double min_lot, double max_lot, double lot_step)
  {
// Округление до ближайшего допустимого значения
   lot = MathMax(min_lot, lot);
   lot -= fmod(lot - min_lot, lot_step);
   lot = MathMin(max_lot, lot);
   return NormalizeDouble(lot, _Digits);
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CalculateAndSetLotSize()
  {
   double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);

// Увеличение текущего размера лота на заданный процент
   currentLots *= (1 + LotChangePercent / 100.0);

// Округление до ближайшего допустимого значения
   currentLots = NormalizeLot(currentLots, min_lot, max_lot, lot_step);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnClickButton1(void)
  {
   Print("Button 1 clicked!");
   int totalPositions = PositionsTotal();
   for(int i = totalPositions - 1; i >= 0; i--)
     {
      string symbol = PositionGetSymbol(i);
      if(!PositionSelect(symbol))
         continue;

      //— Check for position type
      if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL)
         continue;

      //— Prepare request structure
      MqlTradeRequest request = {};
      MqlTradeResult result = {};

      request.action = TRADE_ACTION_DEAL;               // Immediate deal
      request.symbol = symbol;                          // Position symbol
      request.volume = PositionGetDouble(POSITION_VOLUME); // Position volume
      request.type = ORDER_TYPE_SELL == ORDER_TYPE_BUY ? ORDER_TYPE_SELL : ORDER_TYPE_BUY; // Reverse type for closing
      request.position = PositionGetInteger(POSITION_TICKET); // Position ticket
      request.price = ORDER_TYPE_SELL == ORDER_TYPE_BUY ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK); // Price to close

      //— Send trade request
      OrderSend(request, result);

      //— Check for errors
      if(result.retcode != TRADE_RETCODE_DONE)
        {
         string error_msg = "Failed to close position #";
         error_msg += IntegerToString(request.position) + " Return code: " + IntegerToString(result.retcode);
         Print(error_msg);
        }
     }
  }
//+------------------------------------------------------------------+
//| Event handler                                                    |
//+------------------------------------------------------------------+


void CAppWindowTwoButtons::OnClickButton2(void)
  {
   Print("Button 2 clicked!");
   int totalPositions = PositionsTotal();
   for(int i = totalPositions - 1; i >= 0; i--)
     {
      string symbol = PositionGetSymbol(i);
      if(!PositionSelect(symbol))
         continue;

      //— Check for position type
      if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY)
         continue;

      //— Prepare request structure
      MqlTradeRequest request = {};
      MqlTradeResult result = {};

      request.action = TRADE_ACTION_DEAL;               // Immediate deal
      request.symbol = symbol;                          // Position symbol
      request.volume = PositionGetDouble(POSITION_VOLUME); // Position volume
      request.type = ORDER_TYPE_BUY == ORDER_TYPE_BUY ? ORDER_TYPE_SELL : ORDER_TYPE_BUY; // Reverse type for closing
      request.position = PositionGetInteger(POSITION_TICKET); // Position ticket
      request.price = ORDER_TYPE_BUY == ORDER_TYPE_BUY ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK); // Price to close

      //— Send trade request
      OrderSend(request, result);

      //— Check for errors
      if(result.retcode != TRADE_RETCODE_DONE)
        {
         string error_msg = "Failed to close position #";
         error_msg += IntegerToString(request.position) + " Return code: " + IntegerToString(result.retcode);
         Print(error_msg);
        }
     }
  }


//±-----------------------------------------------------------------+
//| Expert tick function                                             |
//±-----------------------------------------------------------------+
void OnTick()
  {
   double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);

// Отправляем алерты при достижении указанных уровней
   if(!belowLevelAlerted && bidPrice <= BelowCurrentPriceLevel)
     {
      Alert("Цена достигла уровня BelowCurrentPriceLevel");
      belowLevelAlerted = true; // Отмечаем, что алерт был отправлен
     }

   if(!aboveLevelAlerted && askPrice >= AboveCurrentPriceLevel)
     {
      Alert("Цена достигла уровня AboveCurrentPriceLevel");
      aboveLevelAlerted = true; // Отмечаем, что алерт был отправлен
     }

   datetime currentTime = TimeCurrent();                    // Текущее время сервера
   MqlRates rates[];
   if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0)      // Получаем последний бар для H1
     {
      datetime newBarTime = rates[0].time;                // Время начала последнего бара

      if(newBarTime != lastBarTime)
        {

         if(MathAbs(bidPrice - lastPrice) > PipsToChange * _Point)
           {
            // Подсчитаем новый размер лота
            CalculateAndSetLotSize();

            lastPrice = bidPrice; // Обновление последней цены

            // Открываем новые ордера с новым размером лота
            OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
            OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
           }



         lastBarTime = newBarTime;                       // Обновляем время начала последнего бара
        }
     }

  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic)
  {

   MqlTradeRequest request = {};
   MqlTradeResult result = {};

// Заполнение полей структуры запроса на сделку
   request.action = TRADE_ACTION_DEAL;
   request.symbol = _Symbol;
   request.volume = lots;
   request.type = type;
   request.sl = 0.0;    // Уровень стоп-лосс не задан
   request.tp = 0.0;    // Уровень тейк-профит не задан
   request.deviation = 0;
   request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount()));

//request.comment = "Auto trade order";

   if(type == ORDER_TYPE_BUY)
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   else
      if(type == ORDER_TYPE_SELL)
         request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(!OrderSend(request,result))
      PrintFormat("OrderSend error %d",GetLastError());
// Попытка отправить торговый запрос
  }
//+------------------------------------------------------------------+
вот мой код в mql5 у меня не работают void CAppWindowTwoButtons::OnClickButton1(void) и void CAppWindowTwoButtons::OnClickButton2(void) первый должен закрывать все sell позиции второй все buy позиции исправь