Shutdown by timeout issue-infinite loop. Please help ?

 

Hi there, I'm having an issue with part of my code :

I'm trying to close all open and pending orders, unfortunately it deletes the pending orders and closes only the first open order.

Would a Refreshrates() inserted in the functions solve the problem ?? Thanks.

while(MyOrdersTotal(Magic)!=0)
{
CloseOrders(Magic);
DeletePendingOrders(Magic);
}

Here are the functions:

int DeletePendingOrders(int Magic)
{
int total = OrdersTotal();

for (int cnt = total-1 ; cnt >= 0 ; cnt--)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber() == Magic && OrderSymbol()==Pair && (OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT))
{
while(IsTradeContextBusy()||!IsTradeAllowed())Sleep(2000);
OrderDelete(OrderTicket());
}
}
return(0);
}

int CloseOrders(int Magic)
{
int total = OrdersTotal();

for (int cnt = total-1 ; cnt >= 0 ; cnt--)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber() == Magic && OrderSymbol()==Pair)
{
if (OrderType()==OP_BUY)
{
while(IsTradeContextBusy()||!IsTradeAllowed())Sleep(2000);
OrderClose(OrderTicket(),OrderLots(),Bid,3);
}

if (OrderType()==OP_SELL)
{

while(IsTradeContextBusy()||!IsTradeAllowed())Sleep(2000);
OrderClose(OrderTicket(),OrderLots(),Ask,3);
}
}
}
return(0);
}

 

Can you show MyOrdersTotal() function as well?

Also make sure your code is not placed in init() or deinit() as their execution time is limited to 2.5 seconds.

 

Here is the MyOrdersTotal() function:

int MyOrdersTotal(int Magic)
{
int z=0;

for (int cnt = 0 ; cnt < OrdersTotal() ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber() == Magic && OrderSymbol()==Pair) z++;
}
return(z);
}

And it is not in init() or deinit().

Thanks for your help.

 

For a WHILE loop where there is no guarantee the loop will exit gracefully (unlike a FOR loop), you should include an additional counter to make sure the loops exits.

Also be considerate of other users on the server, include a Sleep.

eg:

counter=0;
too_many=50;
while(MyOrdersTotal(Magic)!=0 && counter<too_many)
{
CloseOrders(Magic);
DeletePendingOrders(Magic);
Sleep(2000);
counter++;
}

 
bouchepat:

Would a Refreshrates() inserted in the functions solve the problem ?? Thanks.

You must use refresh everytime you sleep and between multiple actions (close/delete) so Bid/Ask is correct
Reason: