# Am I using 'while' properly here?

1347

I want the code to ensure all trades are closed.  Will this while loop function?  Do I run the risk of becoming stuck?

```bool result=false;
while(!result && !IsStopped())
{
result=true;
for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
{
if(!OrderSelect(cnt,SELECT_BY_POS))
continue;
if(!OurMagicNumber(OrderMagicNumber()))
continue;
if(OrderSymbol()==pair || (pair=="none"))
if(OrderMagicNumber()==magic || magic==-1)
if(!CloseOrder(OrderTicket()))
result=false;
}
}```
496

Ian Tavener:

I want the code to ensure all trades are closed.  Will this while loop function?  Do I run the risk of becoming stuck?

if you want to know is all the trades are close,you need to see if there are positions.

to do it,you can use :

```if(PositionsTotal() == 0)
{
//there aren't positions .
}```
1347

Bilal Said:

if you want to know is all the trades are close,you need to see if there are positions.

to do it,you can use :

Sorry, I didn't explain myself properly.  I meant all trades that I'm targeting (Magic number).

496

Ian Tavener:

Sorry, I didn't explain myself properly.  I meant all trades that I'm targeting (Magic number).

```bool istherepositions(int magic)
{

if(PositionsTotal() == 0)
{
return false;
}

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

ulong ticket = PositionGetTicket(i);
bool selected = PositionSelectByTicket(ticket);

if(selected)
{
if(PositionGetInteger(POSITION_MAGIC) == magic)
{
return true;
}
}
}
return false; // if there're positions but the magic number doesn't match.
}```

Hi,check this method ,i think this resolve your problem.
it will only return true if there's position open and the position's magic number is what you targeting.

(the code wasn't compiled)

1347

Bilal Said:

Hi,check this method ,i think this resolve your problem.
it will only return true if there's position open and the position's magic number is what you targeting.

(the code wasn't compiled)

Thank you brother

Moderator
29908

Bilal Said:

Hi,check this method ,i think this resolve your problem.
it will only return true if there's position open and the position's magic number is what you targeting.

(the code wasn't compiled)

That's mql5 code, that original code is mql4.
496

Alain Verleyen:
That's mql5 code, that original code is mql4.

Sorry i didn't know cause the topic wasn't in the mt4 session