EA placing too many trades even with order counting loop

 

Hello,

This EA is designed to place a number of buy and sell pending limit trades, using the TradesAboveBelow parameter. When the EA loads, it gets the current Bid price and places the specified number of trades above and below that Bid price, all spaced according to other variables. This part works just fine. It's supposed to keep a count of the trades so that when either the buys or the sells count goes lower than the variable, it finds the last trade from history, gets that trade's OpenOrderPrice, and places a new pending buy or sell limit order to replace the trade that closed with profit. Basically, there should always be the specified number of trades above and below the Bid price on the board at any one time.

Where I'm running into problems is when the EA replaces a trade, it does so correctly, but it often places too many trades causing my count to be above the specified variable, which then causes other EA functions not to work properly.

Can anyone suggest anything that may be causing this? I don't claim to know everything about coding, but i've never run into this before. Thanks.

#define DECIMAL_CONVERSION 10

//======================= Params ===============================
extern int MagicNumber        = 165443;
extern int TradesAboveBelow   = 30;
int StopLoss                  = 0;
extern double TakeProfit      = 6;
extern string OrderSpacing1   = "==========================";
extern bool UseADRPercentage  = false;
extern double ADR_Percentage  = 20;
extern int PipsBetweenOrders  = 30;
extern string OrderSpacing2   = "==========================";
extern bool UseAutoLots       = true;
extern double FixedLots       = 0.10;
extern int AutoLotLeverage    = 10;
extern int ADR_Period_Days    = 30;
int Slippage                  = 3;
int PercentMultiplier         = 100;

int      InitialBuyOrder, InitialSellOrder, ticket, TotalOrders, total, ordertotal, buy_total, sell_total;
double   OrderSpacing, BasePrice, buy_price, sell_price, ADR, ADRange, ADR_Percent, R30, TP, Lots, lotmin, lotmax;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {

      if (Digits == 3 || Digits == 5)
      {
        Slippage           *= DECIMAL_CONVERSION; 
        StopLoss           *= DECIMAL_CONVERSION;
        TakeProfit         *= DECIMAL_CONVERSION;
        PipsBetweenOrders  *= DECIMAL_CONVERSION;
        PercentMultiplier  /= DECIMAL_CONVERSION;
      }

   lotmin = MarketInfo(Symbol(), MODE_MINLOT);
   lotmax = MarketInfo(Symbol(), MODE_MAXLOT);
   
   TakeProfit = TakeProfit*Point;
   ADR_Percent = ADR_Percentage/PercentMultiplier;
   
   if(!GlobalVariableCheck("ADR")){
      ADR=GetADR();
      GlobalVariableSet("ADR",ADR);
      }

   if(!GlobalVariableCheck("BasePrice")){
      GlobalVariableSet("BasePrice",NormalizeDouble(Bid,Digits));}

   BasePrice = GlobalVariableGet("BasePrice");
   ADRange = GlobalVariableGet("ADR");
   
   if(UseADRPercentage)
      OrderSpacing = (ADRange*ADR_Percent)*Point;
   else OrderSpacing = PipsBetweenOrders*Point;

   buy_price = BasePrice - OrderSpacing;
   sell_price = BasePrice + OrderSpacing;
   InitialBuyOrder = 0;
   InitialSellOrder = 0;

   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   CancelPendingOrder();
   if(total==0){
   GlobalVariableDel("ADR");
   GlobalVariableDel("BasePrice");
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {


   total = 0;
   buy_total = 0;
   sell_total = 0; 
   
   for(int i = 0; i < OrdersTotal(); i++){
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if( OrderType() == OP_BUY || OrderType() == OP_SELL ) { 
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){
            total += 1; 
         }
      }

      if( OrderType() == OP_BUY || OrderType() == OP_BUYLIMIT ) { 
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){
            buy_total += 1; 
         }
      }
      if( OrderType() == OP_SELL || OrderType() == OP_SELLLIMIT ) { 
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){
            sell_total += 1; 
         }
      }
   }


   if(buy_total==TradesAboveBelow){
      InitialBuyOrder=1;
      }
      
   if(sell_total==TradesAboveBelow){
      InitialSellOrder=1;
      }

   if(buy_total<TradesAboveBelow && InitialBuyOrder==0){
         PlaceBuy(NormalizeDouble(buy_price,Digits), TakeProfit);
         buy_price -= OrderSpacing;
         }

   if(buy_total<TradesAboveBelow && InitialBuyOrder==1){
      for(int j=(OrdersHistoryTotal()-1);j>=0;j--){
         OrderSelect(j,SELECT_BY_POS,MODE_HISTORY);
            if(OrderType() == OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){ 
               PlaceBuy(NormalizeDouble(OrderOpenPrice(),Digits), TakeProfit);
            }
         }   
      }
  
   if(sell_total<TradesAboveBelow && InitialSellOrder==0){
         PlaceSell(NormalizeDouble(sell_price,Digits), TakeProfit);
         sell_price += OrderSpacing;
         }

   if(sell_total<TradesAboveBelow && InitialSellOrder==1){
         for(int l=(OrdersHistoryTotal()-1);l>=0;l--){
            OrderSelect(l,SELECT_BY_POS,MODE_HISTORY);
            if(OrderType() == OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){ 
               PlaceSell(NormalizeDouble(OrderOpenPrice(),Digits), TakeProfit);
            }
         }   
      }
   
   Comment("Buy Orders = ", buy_total, "\n", "Sell Orders = ", sell_total);
  
   return(0);
  }



//+------------------------------------------------------------------+
//| additional trade functions                                       |
//+------------------------------------------------------------------+
double GetADR(){
   
   R30=0;
   int i=0;

   for(i=1;i<=ADR_Period_Days;i++)
   R30 = R30 + (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/Point;

   R30 = NormalizeDouble(( (R30/ADR_Period_Days)/10 ),1);

   return(R30);
   }
//+------------------------------------------------------------------+
double GetLots(){
   
      if(UseAutoLots)
         double Lots = ((AccountBalance()*AutoLotLeverage)/100000);
         else {Lots = FixedLots;}
         
      if(Lots<lotmin) Lots=lotmin;
      if(Lots>lotmax) Lots=lotmax;
      
      return(Lots);
   }
//+------------------------------------------------------------------+
void PlaceBuy(double entry, double TP){

      Lots = GetLots();

      ticket=OrderSend(Symbol(), OP_BUYLIMIT, Lots, entry, Slippage, 0.0, (entry+TP), "", MagicNumber, 0, CLR_NONE);
      if(ticket<=0) Print("Error = ",GetLastError());
//      else { 
//         Print("Ticket #", ticket, " -- Order Open Time ", TimeToStr(OrderOpenTime(),TIME_SECONDS)); 
//         if (OrderSelect(ticket, SELECT_BY_TICKET)){
//         OrderModify( ticket, OrderOpenPrice(), sl, tp, 0, CLR_NONE );}
//      }
      
      
return;
  }
//+--------------------------------------------------------------------------------
void PlaceSell(double entry, double TP){

      Lots = GetLots();
   
      ticket=OrderSend(Symbol(), OP_SELLLIMIT, Lots, entry, Slippage, 0.0, (entry-TP), "", MagicNumber, 0, CLR_NONE);
      if(ticket<=0) Print("Error = ",GetLastError());
//      else {  
//         if (OrderSelect(ticket, SELECT_BY_TICKET)){
//         OrderModify( ticket, OrderOpenPrice(), sl, tp, 0, CLR_NONE );}
//      }
      
      return;
   }
//+--------------------------------------------------------------------------------
void CancelPendingOrder()
{

   for(int i = 0; i < OrdersTotal(); i++)
   {
    OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
    if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    { 
      int type   = OrderType();
      bool result = false;
      switch(type)
      {
         //Close pending orders
         case OP_BUYLIMIT  :
         case OP_BUYSTOP   :
         case OP_SELLLIMIT :
         case OP_SELLSTOP  : result = OrderDelete( OrderTicket() );
      }
      if(result == false)
      {
         Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
         Sleep(3000);
      }
    }  
  }
  
return(0);
}

//+-------------------------------------------------------------------------------- 
 
You have a thread about this already.
Reason: