Saeed Areffard
Saeed Areffard

Reputation: 179

How to Navigate through all Positions and get the Type of them in MQL5

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

             string id=PositionGetString(POSITION_COMMENT);
           int type = PositionGetInteger(POSITION_TYPE);

I have an Expert Advisor that I want to get the type of Positions and navigate through the information of Positions .... this two lines of code does not work for me the don't return value

Upvotes: 3

Views: 3852

Answers (1)

TheLastStark
TheLastStark

Reputation: 800

First, you need to select the position before calling PositionGetDouble(), PositionGetInteger(), PositionGetString() functions.

You can select a position by PositionSelect() in netting accounts and also by calling the function PositionGetTicket() it returns the ticket number and also select the current positions (but this is unreliable). You can also use PositionSelectByTicket() if you know the ticket number.

To ensure that you always get fresh set of data, it is recommended to call the PositionSelectByTicket() after getting the ticket from PositionGetTicket() function, before calling PositionGetDouble(), PositionGetInteger(), and PositionGetString() functions.

Here is an example, it prints the position type and its ticket.

for(int i = PositionsTotal() - 1; i >= 0; i--) {
      ulong ticket = PositionGetTicket(i);
      if(ticket>0){
          PositionSelectByTicket(ticket);
          ENUM_POSITION_TYPE posType = PositionGetInteger(POSITION_TYPE);
          Print(EnumToString(posType) + " : " + (string)ticket);
      }
}

Upvotes: 2

Related Questions