Place only single BuyStop / SellStop for several positions of the same type

Hi,

I use this part of script to place a BuyStop order or SellStop order.

It works fine when I have one position of a type (Buy or Sell).

But when I have 2 position of the same type it places 2 orders at the same time even if I set to not do it with (TotalSellStop<1) (TotalBuyStop<1).

How can I fix that?

Thanks a lot! Please help me!

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()==m_magic)
{
if(m_position.PositionType()==POSITION_TYPE_BUY && (TotalSellStop<1) && (TotalBuyStop==0) && (type1==0))
OpenSellStop(InpLots,0,0);
if(m_position.PositionType()==POSITION_TYPE_SELL && (TotalBuyStop<1) && (TotalSellStop==0) && (type1==1))
OpenBuyStop(InpLots,0,0);
}

Because you are opening them inside a loop. Do your loop and count the types. Then decide, if you should open.

I know. But how whould be the right way to loop thru positions, select his type, and place the order just for the last one and not for the full loop. And I don’t know how to do that…

Make up your mind. You already have a loop, use it.

In future, consider using indentation and braces to make your code more readable.

Based on simido 's suggestion, count the number of open positions in the loop.

long buyCount = 0;
long sellCount = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
    if(m_position.SelectByIndex(i)) 
    {
        if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==m_magic)
        {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
            {
                buyCount++;
            }
            if(m_position.PositionType()==POSITION_TYPE_SELL)
            {
                sellCount++;
            }
        }
    }
}

Next use “buyCount” and “sellCount” in your logic to open (or not open) the stops you desire.

I don´t think count positions is the right way to do it. Instead i’ve used boolean in fixed it.

If SS or BS go true then place just one BuyStop or SellStop.

And there was already a count in this script but when

TotalSellStop<1        TotalBuyStop<1  //This was not working
bool     SS=false;
bool     BS=false;


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()==m_magic)
{
if(m_position.PositionType()==POSITION_TYPE_BUY)
   SS=true;


if(m_position.PositionType()==POSITION_TYPE_SELL)
   BS=true;
}

if(SS=true && (TotalSellStop<1) && (TotalBuyStop==0) && (type1==0))
OpenSellStop(InpLots,0,0);

if(BS=true && (TotalBuyStop<1) && (TotalSellStop==0) && (type1==1))
OpenBuyStop(InpLots,0,0);