MT4 coding help please: cancelling pending orders

 

Can anybody help? All I need to do is cancel a pending order if its counterpart is triggered. Example: BuyStop & SellStop placed. The Buy gets triggered, need to cancel the SellStop. I don't see why my code below doesn't work?

Thanks if anyone can help.

for(int z=OrdersTotal()-1;z>=0;z--)

{

OrderSelect(z,SELECT_BY_POS);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_BUY)

{

OrderSelect(z,SELECT_BY_POS);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_SELLSTOP)

{

OrderDelete(OrderTicket(),DarkGoldenrod);

return(0);

}//if sellstop

// else Print("Failed due to error ",GetLastError());

}//if symbol

}//if buy

}//if symbol

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_SELL)

{

OrderSelect(z,SELECT_BY_POS);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_BUYSTOP)

{

OrderDelete(OrderTicket(),DarkGoldenrod);

return(0);

}//if buystop

// else Print("Failed due to error ",GetLastError());

}//if symbol

}//if sell

}//if symbol

}//end loop

 

I think I may have found the problem thanks to the thread "Need help" by Antone - need to test it, if anyone can confirm this may work :

for(int z=OrdersTotal()-1;z>=0;z--)

{

OrderSelect(z, SELECT_BY_POS, MODE_TRADES);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_BUY)

{

OrderSelect(z, SELECT_BY_POS, MODE_TRADES);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_SELLSTOP)

{

OrderSelect(z, SELECT_BY_POS, MODE_TRADES);

OrderDelete(OrderTicket(),DarkGoldenrod);

return(0);

}//if sellstop

// else Print("Failed due to error ",GetLastError());

}//if symbol

}//if buy

}//if symbol

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_SELL)

{

OrderSelect(z, SELECT_BY_POS, MODE_TRADES);

if(OrderSymbol()==Symbol())

{

if (OrderType()==OP_BUYSTOP)

{

OrderSelect(z, SELECT_BY_POS, MODE_TRADES);

OrderDelete(OrderTicket(),DarkGoldenrod);

return(0);

}//if buystop

// else Print("Failed due to error ",GetLastError());

}//if symbol

}//if sell

}//if symbol

}//end loop

 

You'll need to scan the orders twice: first to discover whether or not there is the OP_BUY or OP_SELL trades that you want should cause canceling of pending orders. The second loop is to carry out the canceling. Something like the following:

bool has_sell = false;

bool has_buy = false;

for (int i = OrdersTotal()-1; i >= 0; i-- ) {

if ( ! OrderSelect( i, SELECT_BY_POS ) )

continue;

has_sell |= OrderType() == OP_SELL;

has_buy |= OrderType() == OP_BUY;

}

for ( i = OrdersTotal()-1; i >= 0; i-- ) {

if ( ! OrderSelect( i, SELECT_BY_POS ) )

continue;

if ( has_sell && OrderType() == OP_BUYSTOP )

OrderDelete( OrderTicket(), DarkGoldenrod );

if ( has_buy && OrderType() == OP_SELLSTOP )

OrderDelete( OrderTicket(), DarkGoldenrod );

}

 

Thanks Ralph. Didn't know |=, what does that signify?

You're right, my problem was not re-scanning through the orders. Thanks