EA only enters one trade in backtesting and can't update only once per bar

 

Hi,

I'm a complete beginner so apologies in advance. I have created an EA based on a consolidation breakout indicator. Once the conditions are met it sends two pending orders at the high and low of the consolidation. Once one order is entered the other should be cancelled and a trailing stop tracks the trend.

I wanted the stop loss to updated once per bar (see my hashed attempt below NewBar()) but this was sending a whole load of OrderModify() errors. 

Even once I removed the (NewBar()) function.  In back testing it only completes one trade at the beginning and doesn't enter another trade (even thou there are multiple entry conditions).

As a beginner I have exhausted all my efforts, I'm sure I'm missing something pretty basic but just can't see it. 

Can someone point my in the right direction as to what I've missed. 

Also on another note if anyone has any tips about styling or best practice for MQL4 it would be much appreciated. As I mention I'm new, so any pointer would be amazing even thou this forum and the documentation is excellent I have struggled to find any detailed course on the application and common pitfalls for new comers. I would love any suggestions.   


//+------------------------------------------------------------------+
//|                                              SqueezeBreakout.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property show_inputs
//#include <CustomFunctions01.mqh>


int magicNB = 0004;
// ===================
// User Inputs
// ===================
extern int       Boll_Period=20;
extern double    Boll_Dev=2.0;
extern int       highestLowestPeriod=8;
extern int       atrPeriod=14;
extern int       atrFactor=0.1;
extern double    riskPerTrade=0.02;



int openOrderID;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Print("Starting Strategy: Squeeze Breakout");


//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Print("Stopping Strategy: Squeeze Breakout");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//+------------------------------------------------------------------+
//|  Variables                                                       |
//+------------------------------------------------------------------+

   double Pos_Diff0     = iCustom(Symbol(), 0,"Squeeze_Break",0,0);
   double Momentum0     = iCustom(Symbol(), 0,"Squeeze_Break",2,0);
   double Neg_Diff0     = iCustom(Symbol(), 0,"Squeeze_Break",1,0);

   double Neg_Diff1     = iCustom(Symbol(), 0,"Squeeze_Break",1,1);
   double Neg_Diff2     = iCustom(Symbol(), 0,"Squeeze_Break",1,2);
   double Neg_Diff3     = iCustom(Symbol(), 0,"Squeeze_Break",1,3);
   double Neg_Diff4     = iCustom(Symbol(), 0,"Squeeze_Break",1,4);
   double Neg_Diff5     = iCustom(Symbol(), 0,"Squeeze_Break",1,5);
   double Neg_Diff6     = iCustom(Symbol(), 0,"Squeeze_Break",1,6);
   double Neg_Diff7     = iCustom(Symbol(), 0,"Squeeze_Break",1,7);
   double Neg_Diff8     = iCustom(Symbol(), 0,"Squeeze_Break",1,8);

   double MA            = iMA(Symbol(),1440,200,0,MODE_SMA,PRICE_CLOSE,0);
   double Boll_Mid_Band = iBands(Symbol(),0, Boll_Period,Boll_Dev,0,PRICE_CLOSE, MODE_MAIN,0);

//-- Order Varibles

   double updatedTakeProfitLong;
   double updatedTakeProfitShort;
   double updatedStopLossLong;
   double updatedStopLossShort;
   double stopShort = NormalizeDouble(stopLossHighATR(highestLowestPeriod,atrPeriod,atrFactor),Digits);
   double entryShort = NormalizeDouble(stopLossLowATR(highestLowestPeriod,atrPeriod,atrFactor),Digits);
   double stopLong = NormalizeDouble(stopLossLowATR(highestLowestPeriod,atrPeriod,atrFactor),Digits);
   double entryLong = NormalizeDouble(stopLossHighATR(highestLowestPeriod,atrPeriod,atrFactor),Digits);
   double takeProfitPriceLong;
   double takeProfitPriceShort;
   int longOrderID;
   int shortOrderID;
   int deleteLongOrder;
   int deleteShortOrder;

//-- Find Consolidation

   bool consolidation = false;

   if(Neg_Diff1!=0 && Neg_Diff2!=0 && Neg_Diff3!=0 && Neg_Diff4!=0 && Neg_Diff5!=0 && Neg_Diff6!=0 && Neg_Diff7!=0)
     {
      consolidation= true;
     }
   else
     {
      consolidation= false;
     }

//+------------------------------------------------------------------+
//|  Order Entries                                                   |
//+------------------------------------------------------------------+

   if(!checkOpenOrderMagicNB(magicNB))                                           // If there are no Open Order positions
     {
      if(Pos_Diff0 > 0 && consolidation==true)                                  // Entry Conditions
        {
         Print("Long Entry");
         Print("Entry Price = " + entryLong);                                   // Enrty Info
         Print("Stop Loss Price = " + stopLong);
         Print("Neg Diff0 = " + Neg_Diff0);
         Print("Neg Diff1 = " + Neg_Diff1);

         double positionSize =  lotSize(riskPerTrade,entryLong,stopLong);       //Position Size

         longOrderID = OrderSend(NULL,OP_BUYSTOP,positionSize,entryLong,10,stopLong,0,NULL,magicNB,0,clrGreen);
         if(openOrderID < 0)
            Print("Pending order rejected. Order error: " + GetLastError());

         shortOrderID = OrderSend(NULL,OP_SELLSTOP,positionSize,entryShort,10,stopShort,0,NULL,magicNB,0,clrDarkSalmon);
         if(openOrderID < 0)
            Print("Pending order rejected. Order error: " + GetLastError());
        }
     }

//+------------------------------------------------------------------+
//|  Modify Open Orders                                              |
//+------------------------------------------------------------------+
   else                                                                    // If there are open Order positions
     {
      if(OrderSelect(longOrderID,SELECT_BY_TICKET)==true)
        {
         int orderType = OrderType();
         if(orderType ==OP_BUY)                                       //--If long pending order has been filled
           {
            //--Delete pending order
            deleteShortOrder = OrderDelete(shortOrderID);           //--Delete pending order
            if(deleteShortOrder==false)
              {
               Print("Delete Pending order error" + GetLastError());
              }
            else
              {
               Print("Pending order deleted");
              }

            //----Re-calculate Stoploss
            double stopLossLong1 = OrderStopLoss();
            double newStopLossLong = stopLong;
            if(newStopLossLong > stopLossLong1)
              {
               updatedStopLossLong = NormalizeDouble(newStopLossLong,Digits);
              }
            else
              {
               updatedStopLossLong = NormalizeDouble(stopLossLong1,Digits);
              }

            //--Modify Stoploss
            //   if(!NewBar())                                                            //Calculate Once per bar
            //       {
            //      return;
            //        }
            //        else
            //          {
            bool modifyLongOrder = OrderModify(longOrderID,OrderOpenPrice(),NormalizeDouble(updatedStopLossLong,Digits), OrderTakeProfit(),0,clrAntiqueWhite);
            if(modifyLongOrder==true)
              {
               Print("Long Order Stop Loss modified: " + longOrderID);
              }
            else
              {
               Print("Long Stop Loss modify Error: " + GetLastError());
              }
            //          }

            string stopName = "stop" + Time[1];                                          // Draw Stop loss tracker
            ObjectCreate(stopName, OBJ_TEXT, 0, Time[1],updatedStopLossLong);
            ObjectSetText(stopName, CharToStr(159), 14, "Wingdings", clrRed);
           }
        }



      if(OrderSelect(shortOrderID,SELECT_BY_TICKET)==true)
        {
         int orderType = OrderType();
         if(orderType ==OP_SELL)                                                           //--If short pending order has been filled
           {
            //--Delete pending order
            deleteLongOrder = OrderDelete(longOrderID);                                  //--Delete pending order
            if(deleteLongOrder==false)
              {
               Print("Delete Pending order error" + GetLastError());
              }
            else
              {
               Print("Pending order deleted");
              }


            //--Re-calculate Stop loss
            double stopLossShort1 = OrderStopLoss();
            double newStopLossShort = stopShort;

            if(newStopLossShort < stopLossShort1)
              {
               updatedStopLossShort = NormalizeDouble(newStopLossShort,Digits);
              }
            else
              {
               updatedStopLossShort = NormalizeDouble(stopLossShort1,Digits);
              }

            //--Modify order
            // if(!NewBar())                                                                 //Calculate Once per bar
            //      {
            //        return;
            //        }
            //     else
            //         {
            bool modifyShortOrder = OrderModify(shortOrderID,OrderOpenPrice(),NormalizeDouble(updatedStopLossShort,Digits), OrderTakeProfit(),0,clrAntiqueWhite);
            if(modifyShortOrder==true)
              {
               Print("Short Order Stop Loss modified: " + longOrderID);
              }
            else
              {
               Print("Short Stop Loss modify error: " + GetLastError());
              }
            string stopName = "stop" + Time[1];
            ObjectCreate(stopName, OBJ_TEXT, 0, Time[1],updatedStopLossShort);        // Draw Stop loss tracker
            ObjectSetText(stopName, CharToStr(159), 14, "Wingdings", clrRed);
            // }
           }
        }
     }
  }



//---------------------------------------------------------------------------------------------------------------------------

//+------------------------------------------------------------------+
//|  Functions                                                       |
//+------------------------------------------------------------------+


//--   Calulate once per candle

bool NewBar()
  {
   static datetime prevTime = 0;
   datetime        currentTime = iTime(Symbol(), Period(), 0);
   if(currentTime!=prevTime)
     {
      prevTime    = currentTime;
      return(true);
     }
   return(false);
  }


//--Stop Loss of Highest value + Atr

double stopLossHighATR(int highestPeriod,int atrPeriod, double ATRfactor)
  {
   double highest = findHighest(highestPeriod);
   double atr= iATR(NULL,0,atrPeriod,0);
   double stop = highest + (atr*ATRfactor);
   return stop;
  }


//--Stop Loss of Lowest value - Atr

double stopLossLowATR(int lowestPeriod,int atrPeriod, double ATRfactor)
  {
   double Lowest = findLowest(lowestPeriod);
   double atr= iATR(NULL,0,atrPeriod,0);
   double stop = Lowest - (atr*ATRfactor);
   return stop;
  }



//-----Find Highest value in x bars

double findHighest(int highestRange)
  {

   int high_index=iHighest(NULL,0,MODE_LOW,highestRange,0);
   if(high_index!=-1)
     {
      double val=High[high_index];
      return val;
     }
   else
     {
      return high_index;
      Alert("Error in iLowest. Error code:",GetLastError());
     }
  }


//-----Find Lowest value in x bars

double findLowest(int lowestRange)
  {

   int low_index=iLowest(NULL,0,MODE_LOW,lowestRange,0);
   if(low_index!=-1)
     {
      double val=Low[low_index];
      return val;
     }
   else
     {
      return low_index;
      Alert("Error in iLowest. Error code:",GetLastError());
     }
  }


//-- Check EA has no previous open orders

bool checkOpenOrderMagicNB(int magicNB)
  {
   int openOrders = OrdersTotal();

   for(int i = 0; i <openOrders; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==magicNB)
           {
            return true;
           }
        }
     }
   return false;
  }
//+------------------------------------------------------------------+
 

Any help would be appreciated. 

Am I deleting the pending orders correctly should I start looking there?