- bool CloseOrders(int orderMode,string myType)
- {
- int OrderCount=0, gle=0;
- int cnt,mode;
- int TicketArray[100];
- double ClosePrice=0;
- string stringOrderMode;
-
- if (orderMode==OP_BUY) stringOrderMode="BUY";
- if (orderMode==OP_SELL) stringOrderMode="SELL";
- // first, we retrieve all ticket IDs for existing orders to close out
- for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
- {
- if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
- {
- mode=OrderType();
- if (isOrder(OrderSymbol(), OrderMagicNumber(), OrderComment(), myType))
- {
- if (mode==orderMode)
- {
- TicketArray[OrderCount]=OrderTicket();
- Print("OrderCount: ",OrderCount,", Ticket: ",TicketArray[OrderCount]," Selected for closure.");
- OrderCount++;
- }
- }
- }
- else
- {
- gle=GetLastError();
- Print("Error selecting an order in CloseAllOrders!!! Error #",gle,": ",ErrorDescription(gle));
- return(false); //Since returning false, the caller will retry this function again
- }
- }
- // second, we close out all applicable orders in the array. this two step method prevents problems closing out all orders successfully at once.
- int retries=0;
- while(retries<20)
- {
- for(cnt=0;cnt<OrderCount;cnt++)
- {
- if (TicketArray[cnt]>0)
- {
- if (OrderSelect(TicketArray[cnt], SELECT_BY_TICKET, MODE_TRADES))
- {
- mode=OrderType();
- GetTradeContext(); RefreshRates();
- if (mode==OP_BUY) ClosePrice=NormalizeDouble(Bid,Digits);
- if (mode==OP_SELL) ClosePrice=NormalizeDouble(Ask,Digits);
- if (mode == (orderMode+2) || mode == (orderMode+4))
- {
- if (OrderDelete(OrderTicket()))
- {
- TicketArray[cnt]=0;
- }
- else
- {
- gle=GetLastError();
- Print("Error closing pending order #",TicketArray[cnt],": Error #",gle,": ",ErrorDescription(gle));
- }
- }
- else
- {
- if (CloseOrder(OrderTicket(), OrderLots(), OrderType()))
- {
-
- TicketArray[cnt]=0;
- }
- else
- {
- gle=GetLastError();
- Print("Error closing order #",TicketArray[cnt],": Error #",gle,": ",ErrorDescription(gle));
- }
- }
- }
- else
- {
- gle=GetLastError();
- Print("Error selecting order #",TicketArray[cnt],": Error #",gle,": ",ErrorDescription(gle));
- }
- }
- }
- retries++;
- }
-
- bool CloseAllSuccess=true;
- for(cnt=0;cnt<OrderCount;cnt++)
- {
- if (TicketArray[cnt]>0)
- {
- CloseAllSuccess=false;
- Alert("Could not close ticket #",TicketArray[cnt],"! Will keep retrying.");
- }
- }
-
- if(CloseAllSuccess)
- {
- return(true);
- }
- else
- {
- Print("There was a critical error closing one or more ",stringOrderMode," orders when trying to CLOSE ALL!");
- return(false); //Since returning false, the caller will retry this function again
- }
- }
复制代码
|