Search code examples
mql5metatrader5

MQL5 PositionSelect(_Symbol) call freezes test


I'm hoping someone else has experienced this issue. I'm new to MQL5 (coming from pinescript) and finding my way around the language.

Following the guidelines of the documentation, it's recommended to call PositionSelect() before calling PositionGetInteger(), eg:

int openPositions(ENUM_POSITION_TYPE type) {
   int count = 0;
   
   //if (PositionSelect(_Symbol)) {
      for (long i = 0; i < PositionsTotal(); i++) {
          if (PositionGetInteger(POSITION_TYPE, i) == type) {
              count++;
          }
      }
   //}
   return count;
}

If I enable that PositionSelect(_Symbol) condition, the MT5 back test "freezes" and does nothing after placing a few trades. I then have to click on Stop to restore functionality.

The code seems to work fine without that check, but the docs recommend that call and I've seen other tutorials using it too... so what the heck?

Any ideas on what's going on here?

Thanks


Solution

  • Got help via the MQL5.com forum. The answer is:

    int openPositions(ENUM_POSITION_TYPE type) {
        int count = 0;
        
        for (int i = 0; i < PositionsTotal(); i++) {
            if (!PositionGetTicket(i)) {
                Print("ERROR: PositionGetTicket() failed, error code: ", GetLastError());
                continue;
            }
            if (PositionGetInteger(POSITION_TYPE) == type) 
                count++;
        }
        return count;
    }
    

    The docs are confusing in this regard: both PositionGetTicket() and PositionSelect() are supposed to be used before PositionGetInteger(), but one freezes, and the other works.

    oh well.