Need help with code: the EA does not CLOSE pending orders when # of open trades = above 0

 

Hi,

I have created an EA using EAbuilder.

Mye goal is to close / delete ALL pending orders WHEN numbers of open trades are above 0 (1 or more open trades).

The EA works almost as it should: it closes ALL pending orders on the same type as the open trade. 

If I have an open trade i EURUSD, alle pending orders on EURUSD are deleted, and NOT the other symbols.

(P.S The EA does other things too, but this works as it should.)

Hope someone can help :)

Thanks.

//+------------------------------------------------------------------+
//|                                       Strategy: exitCloseMT5.mq5 |
//|                                       Created with EABuilder.com |
//|                                             http://eabuilder.com |
//+------------------------------------------------------------------+
#property copyright "Created with EABuilder.com"
#property link      "http://eabuilder.com"
#property version   "1.00"
#property description "exit when close beyond trendline"


int LotDigits; //initialized in OnInit
int MagicNumber = 0;
double TradeSize = 0.1;
int MaxSlippage = 3; //adjusted in OnInit
int MaxSlippage_;
input bool Send_Email = true;
bool Audible_Alerts = true;
double myPoint; //initialized in OnInit
double Close[];

void myAlert(string type, string message)
  {
   if(type == "print")
      Print(message);
   else if(type == "error")
     {
      Print(type+" | exitCloseMT5 @ "+Symbol()+","+Period()+" | "+message);
     }
   else if(type == "order")
     {
      if(Audible_Alerts) Alert(type+" | exitCloseMT5 @ "+Symbol()+","+Period()+" | "+message);
      if(Send_Email) SendMail("exitCloseMT5", type+" | exitCloseMT5 @ "+Symbol()+","+Period()+" | "+message);
     }
   else if(type == "modify")
     {
     }
  }

int TradesCount(ENUM_ORDER_TYPE type) //returns # of open trades for order type, current symbol and magic number
  {
   if(type <= 1)
     {
      if (PositionSelect(Symbol()) && PositionGetInteger(POSITION_MAGIC) == MagicNumber && PositionGetInteger(POSITION_TYPE) == type)
         return(1);
      else
         return(0);
     }
   else
     {
      int result = 0;
      int total = OrdersTotal();
      for(int i = 0; i < total; i++)
        {
         if(OrderGetTicket(i) <= 0) continue;
         if(OrderGetInteger(ORDER_MAGIC) != MagicNumber || OrderGetString(ORDER_SYMBOL) != Symbol() || OrderGetInteger(ORDER_TYPE) != type) continue;
         result++;
        }
      return(result);
     }
  }

void myOrderDelete(ENUM_ORDER_TYPE type, string ordername) //delete pending orders of "type"
  {
   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED)) return;
   int err;
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   MqlTradeResult result;
   ZeroMemory(result);
   int total = OrdersTotal();
   for(int i = total-1; i >= 0; i--)
     {
      ulong ticket;
      if((ticket = OrderGetTicket(i)) <= 0) continue;
      MqlTradeRequest request;
      ZeroMemory(request);
      request.action = TRADE_ACTION_REMOVE;
      request.order = ticket;
      if(OrderGetInteger(ORDER_MAGIC) != MagicNumber || OrderGetString(ORDER_SYMBOL) != Symbol() || OrderGetInteger(ORDER_TYPE) != type) continue;
      OrderSend(request, result);
      if(!OrderSuccess(result.retcode))
        {
         err = GetLastError();
         myAlert("error", "OrderDelete"+ordername_+" failed; error #"+err);
        }
     }
   string typestr[8] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop", "Buy Stop Limit", "Sell Stop Limit"};
   if(OrderSuccess(result.retcode)) myAlert("order", "Orders deleted"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+MagicNumber);
  }

void myOrderClose(ENUM_ORDER_TYPE type, int volumepercent, string ordername) //close open orders for current symbol, magic number and "type" (ORDER_TYPE_BUY or ORDER_TYPE_SELL)
  {
   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED)) return;
   if (type > 1)
     {
      myAlert("error", "Invalid type in myOrderClose");
      return;
     }
   bool success = false;
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   if (!PositionSelect(Symbol())) return;
   if(PositionGetInteger(POSITION_MAGIC) != MagicNumber || PositionGetInteger(POSITION_TYPE) != type)
      return;
   MqlTick last_tick;
   SymbolInfoTick(Symbol(), last_tick);
   double price = (type == ORDER_TYPE_SELL) ? last_tick.ask : last_tick.bid;
   MqlTradeRequest request;
   ZeroMemory(request);
   request.action = TRADE_ACTION_DEAL;
   request.position = PositionGetInteger(POSITION_TICKET);
   
   //set allowed filling type
   int filling = (int)SymbolInfoInteger(Symbol(),SYMBOL_FILLING_MODE);
   if(request.action == TRADE_ACTION_DEAL && (filling & 1) != 1)
      request.type_filling = ORDER_FILLING_IOC;

   request.magic = MagicNumber;
   request.symbol = Symbol();
   request.volume = NormalizeDouble(PositionGetDouble(POSITION_VOLUME)*volumepercent * 1.0 / 100, LotDigits);
   if (NormalizeDouble(request.volume, LotDigits) == 0) return;
   request.price = NormalizeDouble(price, Digits());
   request.sl = 0;
   request.tp = 0;
   request.deviation = MaxSlippage_;
   request.type = 1-type; //opposite type
   request.comment = ordername;
   MqlTradeResult result;
   ZeroMemory(result);
   OrderSend(request, result);      
   success = OrderSuccess(result.retcode);
   if(!success)
     {
      myAlert("error", "OrderClose"+ordername_+" failed; error: "+result.comment);
     }
   string typestr[8] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop", "Buy Stop Limit", "Sell Stop Limit"};
   if(success) myAlert("order", "Orders closed"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+MagicNumber);
  }

double TrendlinePriceUpper(int shift) //returns current price on the highest horizontal line or trendline found in the chart
  {
   int obj_total = ObjectsTotal(0);
   double maxprice = -1;
   for(int i = obj_total - 1; i >= 0; i--)
     {
      string name = ObjectName(0, i);
      double price;
      if(ObjectGetInteger(0, name, OBJPROP_TYPE) == OBJ_HLINE && StringFind(name, "Horizontal Line", 0) >= 0
      && (price = ObjectGetDouble(0, name, OBJPROP_PRICE)) > maxprice)
         maxprice = price;
      else if(ObjectGetInteger(0, name, OBJPROP_TYPE) == OBJ_TREND && StringFind(name, "Trendline", 0) >= 0)
      {
         datetime Time[];
         ArraySetAsSeries(Time, true);
         CopyTime(Symbol(), Period(), 0, 1, Time);
         price = ObjectGetValueByTime(0, name, Time[0], 0);
         if(price > maxprice)
            maxprice = price;            
      }
     }
   return(maxprice); //not found => -1
  }

double TrendlinePriceLower(int shift) //returns current price on the lowest horizontal line or trendline found in the chart
  {
   int obj_total = ObjectsTotal(0);
   double minprice = MathPow(10, 308);
   for(int i = obj_total - 1; i >= 0; i--)
     {
      string name = ObjectName(0, i);
      double price;
      if(ObjectGetInteger(0, name, OBJPROP_TYPE) == OBJ_HLINE && StringFind(name, "Horizontal Line", 0) >= 0 
      && (price = ObjectGetDouble(0, name, OBJPROP_PRICE)) < minprice)
         minprice = price;
      else if(ObjectGetInteger(0, name, OBJPROP_TYPE) == OBJ_TREND && StringFind(name, "Trendline", 0) >= 0)
      {
         datetime Time[];
         ArraySetAsSeries(Time, true);
         CopyTime(Symbol(), Period(), 0, 1, Time);
         price = ObjectGetValueByTime(0, name, Time[0], 0);
         if(price < minprice)
            minprice = price;            
      }
     }
   if (minprice > MathPow(10, 307))
      minprice = -1; //not found => -1
   return(minprice);
  }

bool NewBar()
  {
   datetime Time[];
   ArraySetAsSeries(Time, true);
   CopyTime(Symbol(), Period(), 0, 1, Time);
   static datetime LastTime = 0;
   bool ret = Time[0] > LastTime && LastTime > 0;
   LastTime = Time[0];
   return(ret);
  }

bool OrderSuccess(uint retcode)
  {
   return(retcode == TRADE_RETCODE_PLACED || retcode == TRADE_RETCODE_DONE
      || retcode == TRADE_RETCODE_DONE_PARTIAL || retcode == TRADE_RETCODE_NO_CHANGES);
  }

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {   
   MaxSlippage_ = MaxSlippage;
   //initialize myPoint
   myPoint = Point();
   if(Digits() == 5 || Digits() == 3)
     {
      myPoint *= 10;
      MaxSlippage_ *= 10;
     }
   //initialize LotDigits
   double LotStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);
   if(LotStep >= 1) LotDigits = 0;
   else if(LotStep >= 0.1) LotDigits = 1;
   else if(LotStep >= 0.01) LotDigits = 2;
   else LotDigits = 3;
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   ulong ticket = 0;
   double price;   
   bool isNewBar = NewBar();
   
   if(TrendlinePriceUpper(0) < 0 && TrendlinePriceLower(0) < 0) return;
   if(CopyClose(Symbol(), PERIOD_CURRENT, 0, 200, Close) <= 0) return;
   ArraySetAsSeries(Close, true);
   
   //Close Long Positions, instant signal is tested first
   if(isNewBar //Send order when new bar opens
   && Close[0] < TrendlinePriceLower(0) //Candlestick Close < Lower Trendline
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderClose(ORDER_TYPE_BUY, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Delete Pending Buy Orders
   if(TradesCount(ORDER_TYPE_BUY) + TradesCount(ORDER_TYPE_SELL) > 0 //Open Trades > fixed value
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderDelete(ORDER_TYPE_BUY_LIMIT, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Delete Pending Buy Orders
   if(TradesCount(ORDER_TYPE_BUY) + TradesCount(ORDER_TYPE_SELL) > 0 //Open Trades > fixed value
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderDelete(ORDER_TYPE_BUY_STOP, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Short Positions, instant signal is tested first
   if(isNewBar //Send order when new bar opens
   && Close[0] > TrendlinePriceUpper(0) //Candlestick Close > Upper Trendline
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderClose(ORDER_TYPE_SELL, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Delete Pending Sell Orders
   if(TradesCount(ORDER_TYPE_BUY) + TradesCount(ORDER_TYPE_SELL) > 0 //Open Trades > fixed value
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderDelete(ORDER_TYPE_SELL_LIMIT, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Delete Pending Sell Orders
   if(TradesCount(ORDER_TYPE_BUY) + TradesCount(ORDER_TYPE_SELL) > 0 //Open Trades > fixed value
   )
     {   
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED))
        myOrderDelete(ORDER_TYPE_SELL_STOP, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
  }
//+------------------------------------------------------------------+
Reason: