Count positions by Magic number in MQL5

 

This is a simple code that worked.

I am just sharing with y ou

The problem with counting is that there are functions that will not count in a for loop.


this actually worked for me . I use magic number for filtering and it worked. Hope you enjoy it.


first declare your magicnumber

let´s say 

init magicnumber=123;


I will call Ctrade:

CTrade       trade;


then OnInit section, I will assign the magic number:

int OnInit()

{

   trade.SetExpertMagicNumber(magicNumber);

   // rest of your code

}


then this fuction that I struggled with multiple versions: 



int CountOrdersMagic(int magicnumber)

  {

   int count = 0;


   for(int i = 0; i < PositionsTotal(); i++)

     {

      if(PositionSelectByTicket(PositionGetTicket(i)))

        {

         if(PositionGetInteger(POSITION_MAGIC) == magicnumber)

           {

            count++;

           }

        }

     }

   return (count);

   }

//+------------------------------------------------------------------+


Enjoy it

Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Execution of trade operations results in the opening of a position, changing of its volume and/or direction, or its disappearance. Trade operations...
 

I am sharing because it worked and I kept doing it badly.

 
  1. Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)


  2.  if(PositionSelectByTicket(PositionGetTicket(i)))
    GetTicket selects that position, why are you selecting it again?
  3. PositionGetTicket

    The function returns the ticket of a position with the specified index in the list of open positions and automatically selects the position to work with using functions PositionGetDouble, PositionGetInteger, PositionGetString.

 
William Roeder #:
  1. Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)


  2. GetTicket selects that position, why are you selecting it again?
can´t findthe button