Close an Open Trade By Magic Number (MT5!)

 

Hi everyone,

i tried to build a mql5 function that close an order by a magic number input.

Below I insert the code of the function.

                  void Close_Position_MN(ulong magicNumber)
                  {  
                      int total = PositionsTotal();
                      for(int i = total-1 ; i >= 0; i--)
                      {
                          ulong ticket = PositionGetTicket(i);
                          if(PositionSelect(ticket)) // Seleziona la posizione con il ticket
                          {
                              if (PositionGetInteger(POSITION_MAGIC) == magicNumber && PositionGetInteger(POSITION_TICKET) == ticket)
                              {
                                  string symbol = PositionGetSymbol(ticket);
                                  if(symbol == _Symbol) // Verifica il simbolo
                                  {
                                      Print("MN "+magicNumber);
                                      trade.PositionClose(ticket);
                                  }
                              }
                          }
                          else
                          {
                              int errorCode = GetLastError();
                              //Print("PositionSelect failed with error code: ", errorCode);
                          }
                      }
                  } 

I insert in OnTick function the following line of script after i opened some  orders with magic number 22 (MN 22.png)

 Close_Position_MN(22);

The function always goes on the error and returns me as GetLastError: "PositionSelect failed with error code: 4753"

It seems that not found the position but i tried to insert:

                  void Close_Position_MN(ulong magicNumber)
                  {  
                      int total = PositionsTotal();
                      for(int i = total-1 ; i >= 0; i--)
                      {
                          ulong ticket = PositionGetTicket(i);
                          Print("Ticket: "+ticket+" - MN "+PositionGetInteger(POSITION_MAGIC) );
                          if(PositionSelect(ticket)) // Seleziona la posizione con il ticket
                          {
                              if (PositionGetInteger(POSITION_MAGIC) == magicNumber && PositionGetInteger(POSITION_TICKET) == ticket)
                              {
                                  string symbol = PositionGetSymbol(ticket);
                                  if(symbol == _Symbol) // Verifica il simbolo
                                  {
                                      Print("MN "+magicNumber);
                                      trade.PositionClose(ticket);
                                  }
                              }
                          }
                          else
                          {
                              int errorCode = GetLastError();
                              //Print("PositionSelect failed with error code: ", errorCode);
                          }
                      }
                  } 


The logs are like this:

2024.05.17 00:33:24.484 Ticket: 655163011 - MN 22

2024.05.17 00:33:25.256 Ticket: 655163618 - MN 22

Can you help me please?!

Many Thanks



Files:
MN_22.png  7 kb
 

Nothing i solved just now!!

void Close_Position_MN(ulong magicNumber)
{  
    int total = PositionsTotal();
    for(int i = total - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);

        // Use PositionSelect by symbol instead of ticket
        string symbol = PositionGetSymbol(i);
        if(PositionSelect(symbol))
        {
            if (PositionGetInteger(POSITION_MAGIC) == magicNumber && PositionGetInteger(POSITION_TICKET) == ticket)
            {
                if(symbol == _Symbol) // Verify the symbol
                {
                    Print("MN " + magicNumber);
                    trade.PositionClose(ticket);
                }
            }
        }
        else
        {
            int errorCode = GetLastError();
            Print("aaaa PositionSelect failed with error code: ", errorCode);
        }
    }
}
 
Sidi Mohamed El Alaoui #Nothing i solved just now!!

Hello, try the following:

//+--------------------------------------------------------------------------------------------------------------------+
//| This function closes all positions (symbol / magic number)                                                         |
//+--------------------------------------------------------------------------------------------------------------------+
bool ClosePositions(string symbol, ulong tf_magic)
  {
//--- Local variables
   int   Cnt, positions_total = PositionsTotal();
   ulong TICKET;

//--- Checks positions
   for(Cnt = positions_total - 1; Cnt >= 0; Cnt --)
     {
      //--- Gets the ticket and selects the position
      TICKET = PositionGetTicket(Cnt);
      if(TICKET == 0)
        {
         Print(__FUNCTION__, " - Failed to get position ticket...");
         return(false);
        }
      //--- Checks symbol and magic number
      if(PositionGetString(POSITION_SYMBOL) == symbol && PositionGetInteger(POSITION_MAGIC) == tf_magic)
        {
         //--- Checks SYMBOL_TRADE_STOPS_LEVEL
         if(Check_SL_TP(symbol, PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, PositionGetDouble(POSITION_SL), PositionGetDouble(POSITION_TP)))
           {
            //--- Closes position
            if(m_trade.PositionClose(TICKET))
              {
               Print(__FUNCTION__, " - Closing of position ", TICKET, " [ Enter the reason for closing the position here ].");
              }
            else
              {
               Print(__FUNCTION__, " - ", m_trade.ResultRetcode(), " ", m_trade.ResultRetcodeDescription());
               return(false);
              }
           }
        }
     }

//--- Check completed
   return(true);
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| Check if the distance between TakeProfit/StopLoss and the closing price is greater than SYMBOL_TRADE_STOPS_LEVEL   |
//+--------------------------------------------------------------------------------------------------------------------+
bool Check_SL_TP(string symbol, ENUM_ORDER_TYPE type, double SL, double TP)
  {
//--- Local variables
   bool SL_check = false, TP_check = false;

   ResetLastError();
//--- Gets the last price for current symbol
   double BID = SymbolInfoDouble(symbol, SYMBOL_BID);
   double ASK = SymbolInfoDouble(symbol, SYMBOL_ASK);

//--- Gets the point value for current symbol
   double POINT = SymbolInfoDouble(symbol, SYMBOL_POINT);

//--- Gets the SYMBOL_TRADE_STOPS_LEVEL
   int stops_level = (int)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);

//--- Check if an execution error occurred
   if(GetLastError() != ERR_SUCCESS)
     {
      Print(__FUNCTION__, " - Error getting symbol data: ", GetLastError());
      return(false);
     }

//--- Check the SYMBOL_TRADE_STOPS_LEVEL
   if(stops_level != 0)
     {
      PrintFormat("SYMBOL_TRADE_STOPS_LEVEL=%d: StopLoss and TakeProfit must not be nearer than %d points from the closing price", stops_level, stops_level);
     }

//--- check only two order types
   switch(type)
     {
      //--- Buy operation
      case  ORDER_TYPE_BUY:
        {
         //--- check the StopLoss
         SL_check = (BID - SL > stops_level * POINT);
         if(!SL_check)
           {
            PrintFormat("For order %s StopLoss=%.5f must be less than %.5f (Bid=%.5f - SYMBOL_TRADE_STOPS_LEVEL=%d points)", EnumToString(type), SL, BID - stops_level * POINT, BID, stops_level);
           }
         //--- check the TakeProfit
         TP_check = (TP - BID > stops_level * POINT);
         if(!TP_check)
           {
            PrintFormat("For order %s TakeProfit=%.5f must be greater than %.5f (Bid=%.5f + SYMBOL_TRADE_STOPS_LEVEL=%d points)", EnumToString(type), TP, BID + stops_level * POINT, BID, stops_level);
           }
         //--- return the result of checking
         return(SL_check && TP_check);
        }
      //--- Sell operation
      case  ORDER_TYPE_SELL:
        {
         //--- check the StopLoss
         SL_check = (SL - ASK > stops_level * POINT);
         if(!SL_check)
           {
            PrintFormat("For order %s StopLoss=%.5f must be greater than %.5f (Ask=%.5f + SYMBOL_TRADE_STOPS_LEVEL=%d points)", EnumToString(type), SL, ASK + stops_level * POINT, ASK, stops_level);
           }
         //--- check the TakeProfit
         TP_check = (ASK - TP > stops_level * POINT);
         if(!TP_check)
           {
            PrintFormat("For order %s TakeProfit=%.5f must be less than %.5f (Ask=%.5f - SYMBOL_TRADE_STOPS_LEVEL=%d points)", EnumToString(type), TP, ASK - stops_level * POINT, ASK, stops_level);
           }
         //--- return the result of checking
         return(TP_check && SL_check);
        }
      break;
     }

//--- Verification succeeded
   return(false);
  }
Reason: