EA - closing all positions at once.

 

I'm trying to run the following subroutine to close all my short positions at once. It works great with the backtester as it closes all short positions as expected. But when I run against a Demo account and leave the EA on all the time, it only appears to close 1 open order at each bar (since I only analyze charts when a new bar appears). Also, I don't see the !!!Warning message in the journal. So I'm thinking it's only executing the routine once or not looping properly.

Any ideas what I'm doing wrong.

void CloseAllShort() {

int total = OrdersTotal();

for (int cnt = 0 ; cnt < total ; cnt++) {

int order_type;

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

order_type = OrderType();

if(order_type == 1) {

if (!(OrderClose(OrderTicket(),OrderLots(),Ask,0,Blue))) {

Print("!!!Warning - Order could not be closed, " + OrderTicket() + " " + GetLastError());

}

}

}

total = OrdersTotal();

Alert("<<<Short - All short orders were closed - " + total + " - $" + iClose(NULL,0,0));

}

 

This is a bad way of counting.

for (int cnt = 0 ; cnt < total ; cnt++)

you should count down instead...

for (int cnt <= total-1 0 ; cnt = 0 ; cnt--)

Also, make sure it checks for the symbol and magic number. Do a search on this forum for other close routines and you will come up with some.

Just a few ideas for your use.

Good luck.

 

where is your spread?

 
phoenix:
where is your spread?

How do I define the spread? I though so long as I code "Ask" or "Bid" as part of my order close, it will take into account the 2 pip spread. Am I wrong?

 
Maji:
This is a bad way of counting.

for (int cnt = 0 ; cnt < total ; cnt++)

you should count down instead...

for (int cnt <= total-1 0 ; cnt = 0 ; cnt--)

Also, make sure it checks for the symbol and magic number. Do a search on this forum for other close routines and you will come up with some.

Just a few ideas for your use.

Good luck.

Do you count down because orders get closed? Also shouldn't it be cnt<0 so that the 0 element gets processed:

for (int cnt <= total-1 ; cnt < 0 ; cnt--)

 

here's closeall script

one is close all the whole floating

another one is close all specific symbol

Files:
 
phoenix:
here's closeall script

one is close all the whole floating

another one is close all specific symbol

Thank you, I have a better understanding of the Order functions. I thought any calls to the Order functions would handle things like spread, etc.

Also, why would I need the magic number? I thought that was for only running multiple EAs or running multiple pairs. Am I wrong?