Limit one open buy/sell position at a time

 

I'm using the below code to limit the buy/sell position at a time but I'm not sure why MetaTrader5 could open more than 1. I just can't figure it why. Could someone shed a light here? 


 bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variable to hold the result of Sell opened position

   if(PositionSelect(_Symbol) ==true)   // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
        {
         Buy_opened = true;  //It is a Buy
        }
      else
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            Sell_opened = true; // It is a Sell
           }
     }

Later, we will decide whether to open a position or not base on Buy_opened and Sell_opened. I'm suspecting the methods that used in the above block don't always work right. Any thoughts?

 

PositionSelect(_Symbol) is a construct for a NETTING trading account.

Use the generic construct:

//+------------------------------------------------------------------+
//| Calculate all positions Buy and Sell                             |
//+------------------------------------------------------------------+
void CalculateAllPositions(int &count_buys,int &count_sells)
  {
   count_buys=0;
   count_sells=0;
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               count_buys++;
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               count_sells++;
           }
//---
   return;
  }
 

I was not aware of this NETTING trading account. Thanks for showing me a new thing and sharing the detailed code, Vladimir. 

Reason: