EA opening too many trades

 
//+------------------------------------------------------------------+
//|                                       Newbie programming 3.2.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//---
//+------------------------------------------------------------------+
//| This program looks for high breaking a previous high looks to    |
//| see if it continues to a new high close or pulls back            |
//+------------------------------------------------------------------+
//--- Variables
int  i;
int a = 1;
int b = 2;
int CandleNumber = 0;
int CandleHighFail = 0;
int CandleHighSuccess = 0;
double CandleHighFailTotalCount =0;
double CandleHighSuccessTotalCount =0;
int HighestCandleNumberCountedSoFar =0;
double CandleHigh [];
double NewCandleHigh [];


double       Pips;


double StopLoss;
double TakeProfit;
double LotSize   = 0.01;
int MagicNumber = 001;
int buy;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--Find out server tick size on this chart.
   double ticksize = MarketInfo(Symbol(),MODE_TICKSIZE);


   if(ticksize == 0.00001  || Point == 0.001)
      Pips = ticksize*10;
   else
      Pips = ticksize;

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   double FinallyCount =MathAbs(((CandleHighSuccessTotalCount+CandleHighFailTotalCount)-CandleHighFailTotalCount)*10);
   Print(" How many highs continued " + DoubleToString(FinallyCount,0),"%");
   Print("total fails"+DoubleToString(CandleHighFailTotalCount,0));
   Print("Total Success"+DoubleToString(CandleHighSuccessTotalCount,0));
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

   if(IsThisANewCandle())

//-- Conditions for entry--------------------------------------------\\
      for(i=0.0; i<Bars; i++)
        {
//-- Condition 1 ----------------------------------------------------\\       
         if(High [a] < High [b])
           {
            Print("No new high");                                    // print
            CandleHighSuccess =0;                                    // reset counter
            CandleHighFail = 0;                                      // reset counter
            AdjustStops();                                           // if trade open adjust stops
           }
//-- Condition 2 ----------------------------------------------------\\       
         if(High[a] > High[b]&& Close [a] < Close[b])
           {
            CandleHighFail += 1;                                    // Add to count of fails in succession
            CandleHighFailTotalCount+=1;                            // add to over all count of all fails
            OrderEntry();                                           // entry of orders
            CandleHighSuccess =0;                                   // reset count for succesive runs
            AdjustStops();                                          // if trade open adjust stops
            Print("Candle made new high and failed"                 // if trade open adjust stops
                   + IntegerToString(CandleHighFail,0));
            string name="UpArrow"+(string)Time[a];                  // Draw arrow to mark
            if(ObjectFind(0,name)!=0)
              {
               ObjectCreate(name,OBJ_ARROW_UP,0,Time[a],
                            Low[a]-(Period()*Point*1));              
               ObjectSet(name,OBJPROP_COLOR,clrRed);
               ObjectSet(name,OBJPROP_WIDTH,1);
               ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_BOTTOM);
              }
            else
               if(ObjectFind(0,name)==0)
                 {
                  Print("ObjectFind error",GetLastError());
                 }
           }
//-- Condition 3 ----------------------------------------------------\\       
         if(High[a] > High[b]&& Close [a] > Close[b])
           {
            CandleHighSuccess +=1;                                    // Add to count of succesfull in succession
            CandleHighSuccessTotalCount +=1;                          // add to over all count of all succeses
            CandleHighFail = 0;                                       // reset count for succesive runs
            OrderEntry();                                             // entry of orders
            AdjustStops();                                            // adjust stops
            Print("Candle"," made new high and Succeded" 
                   + IntegerToString(CandleHighSuccess,0));           // Draw arrow to mark
            string name="UpArrow"+(string)Time[a];
            if(ObjectFind(0,name)!=0)
              {
               ObjectCreate(name,OBJ_ARROW_UP,0,Time[a],
                            Low[a]-(Period()*Point*1));              
               ObjectSet(name,OBJPROP_COLOR,clrGreen);
               ObjectSet(name,OBJPROP_WIDTH,1);
               ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_BOTTOM);
              }
            else
               if(ObjectFind(0,name)==0)
                 {
                  Print("ObjectFind error",GetLastError());
                 }
           }

        }
  }

//--Is this a new Candle?---------------------------------------------//
bool IsThisANewCandle()
  {
   static int BarsOnChart=10000;    //-- this will be update on initialization, static will stop it reseting
   if(Bars==BarsOnChart)          //-- will update int in GBL with bars on current chart
      return(false);              //-- No new number
   BarsOnChart=Bars;              //-- Is this number higher than the last saved number
   return(true);                  //-- This is a new candle

  }

//-- Order Entry-------------------------------------------------------\\
void OrderEntry()
  {
//--Buy order---------------------------------------------------------------------------//

   double BuyStopLoss;                                                                   //-- this is incase broker is ECN and stop loss is set to '0'Some ECN's automatically move stop loss back to 0 on MT4 if set in settings.
   if(StopLoss==0)
      BuyStopLoss=0;
   else
      BuyStopLoss=High[b];

   double BuyTakeProfit;                                                                 //--this is incase broker is ECN and stop loss is set to '0'Some ECN's automatically move stop loss back to 0 on MT4 if set in settings.
   if(TakeProfit==0)
      BuyTakeProfit=0;
   else
      BuyTakeProfit= Low[a];

   int Buyticket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,3,BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,clrGreen);
// if(Buyticket>0) OrderModify(Buyticket,OrderOpenPrice(),BuyStopLoss,BuyTakeProfit,0,clrNONE);
     {
      Print("Buy order");
     }

  }
//--Adjust stops ----------------------------------------------------------------------//
void AdjustStops()
  {

   for(int buy=OrdersTotal() -1; b>=0; b--)
     {
      if(!OrderSelect(buy,SELECT_BY_POS,MODE_TRADES)||  OrderMagicNumber() != MagicNumber)   //-- If the selected order is NOT 'b' as in buy.
         continue;                                                                           //-- Select by position in order of trades
                                                                                             //-- Order selected from current open or pending orders. MODE_HISTORY would be closed trades
                                                                                             //-- OR
                                                                                             //-- The order magic number..
                                                                                             //--  ..is not the MagicNumber for the trade
                                                                                             //-- Continue means to skip the rest of this run of the funtion and move to the next run of the for loop...
                                                                                             //-- ...this is not like 'break' where the funtion itself would be ended.
      if(OrderType()!=OP_BUY)
         continue;
        {
         if(OrderSymbol()==Symbol())                                                          //-- Failsafe to make sure the MagicNumber is for the right trade
           {
            if(!IsThisANewCandle())
               continue;                                                                       //-- if this is NOT a new candle, continue to next funtion
            if(OrderStopLoss() <Low[a])                                                        //-- If the stop loss is..
               //-- ..less than the Low- PlusAmountPips * Pips)
               OrderModify(OrderTicket(),OrderOpenPrice(),Low[a],OrderTakeProfit(),0,clrNONE);
           }

        }
     }
  }
//+------------------------------------------------------------------+
Hi, I am learning to code. The 

Hi , I am learning to code. The EA above is for practice. it is suppose to open a trade if the condition  2 or  are met and then manage trades by moving stops to bottom of pervious candle. It is opening a trade on every tick and not closing them. The new candle function seems to work in isolation and so does the open trade function as well as the trade entry conditions. But together it does not. Any advise would be appreciated. Thank you in advance.

 

The new candle check is wrong in two ways. First, you can call it only once, if you call it several times it will return false even if it is a new candle. See the static? Second, don't check the bar count, check the time of the current bar, it's more reliable (bar counts may change due to history updates.)

bool IsThisANewCandle()
 {
   static datetime bartime=0;     //-- last time you've seen a new bar
   datetime dt=iTime(_Symbol,_Period,0);
   if(dt==bartime)
      return false;               //-- no new bar
   bartime=dt;                    //-- a new bar opened, great
   return true;
 }

bool IsNewBar;

void OnTick()
 {
   IsNewBar=IsThisANewCandle();
   ...
   // now work with IsNewBar instead of calling the function
 }
 
lippmaje:

The new candle check is wrong in two ways. First, you can call it only once, if you call it several times it will return false even if it is a new candle. See the static? Second, don't check the bar count, check the time of the current bar, it's more reliable (bar counts may change due to history updates.)

Exactly.

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart,) volume is unreliable (miss ticks,) Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.

I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
          New candle - MQL4 programming forum

 
Thank you both for taking the time to answer.   It was a lot of help
Reason: