Counting Buy/Long and Sell/Short Positions in MQL5

 

I have searched and found the code below for counting Buy/Long and Sell/Short Positions in MQL5. But it seems not to make what it should do.

      int  countBuy =0;
      int countSell =0;

      for(int i=PositionsTotal()-1; i>=0; i--)
        {
         string csymbol=PositionGetSymbol(i);
         ulong  magic=PositionGetInteger(POSITION_MAGIC); // MagicNumber der Position
         long PositionDirection= PositionGetInteger(POSITION_TYPE);

         if(magic==Magic && Symbol()==csymbol)

            if(PositionDirection==POSITION_TYPE_BUY)
              {
               countBuy=countBuy+1;
               Alert(countBuy, "\n Buy Position is open.");
              }
         if(PositionDirection==POSITION_TYPE_SELL)
           {
            countSell=countSell+1;
            Alert(countSell, "\n Sell Position is open.");
           }
        }
      PrintFormat("New bar: %s",TimeToString(TimeCurrent(),TIME_SECONDS));

If Positions should be closed by:

if(countBuy==1)

(and other conditions) open Buy-Positions is not closed. This only works if I use:

if(PositionsTotal()>0)

which is not what I want, as only one of open trading direction should be closed.

I do not see where there is an error. I am not aware if the minimum number of criteria are used to correctly select Positions and close them. It seems that the countings is not stored correctly or not retrieved correctly when it checks at every new bar.

Can anyone help please?

 
riofenix:

I have searched and found the code below for counting Buy/Long and Sell/Short Positions in MQL5. But it seems not to make what it should do.

If Positions should be closed by:

(and other conditions) open Buy-Positions is not closed. This only works if I use:

which is not what I want, as only one of open trading direction should be closed.

I do not see where there is an error. I am not aware if the minimum number of criteria are used to correctly select Positions and close them. It seems that the countings is not stored correctly or not retrieved correctly when it checks at every new bar.

Can anyone help please?

ja wir sprechen hier deutsch, 

du musst schon die Position auswählen welche du auslesen willst sonst wird das nix

positionselect

 

Wenn man nicht weiter weiß erstmal hier: (https://www.mql5.com/de/docs/function_indices) suchen, da die viele Funktionen Beipsiele beinhalten.

Danach über die Lupe oben rechts suchen nach zB. "PositionsTotal"  und dann würdest Du den beispielcode von amando finden: https://www.mql5.com/de/code/27635.

Da findest Du, wie man offenen Positionen findet.

Dokumentation zu MQL5: MQL5 Funktionenliste
Dokumentation zu MQL5: MQL5 Funktionenliste
  • www.mql5.com
MQL5 Funktionenliste - Nachschlagewerk MQL5 - Nachschlagewerk über die Sprache des algothitmischen/automatischen Handels für MetaTrader 5