How to detect a new bar

 

Hi All,

I'm a complete newbie to MQL5 but I've done a fair bit of coding for other platforms.

I'm wondering why it is so difficult for an EA to execute only on a new bar. I've had a look at some of the articles, including the "new bar" event handler, and it seems very difficult. 

If that won't work and I have to use the "new bar" event handler, is it possible to just donwload the relevant files and copy them to the Files(?) folder, and then #include them? Is there anywhere where this is documented for people like me who basically have no idea what they are doing?

I'm working through the tutorial in https://www.mql5.com/en/articles/100, and the first thing I noticed was that the "Bars" function is used to ensure there are enough bars to perform calculations on, but the next piece of code is apparently designed to detect a new bar and is (to my understanding anyway) a very complex piece of code. Couldn't the Bars function be used to detect a new Bar? Something like if(Bars > int LastBarCount) {bool IsNewBar = true; LastBarCount = Bars;} else {IsNewBar = false;}. Would something like that work?.

One for the wishlist. Wouldn't it be good if there was an OnNewBar event that we could override, instead of OnTick? Since every indicator I've ever seen works on bars, not ticks, I think it would make everybody's lives a lot easier.

Just found another possibility: "BarsCalculated". Again not entirely sure what this means from the description but it looks like the number of bars that the EA has processed already. If that were true then all I would need to check is if(Bars > BarsCalculated), if true then go and do my processing, otherwise return? Am I missing something?

Thanks,

Ian

Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners
  • 2010.06.09
  • Samuel
  • www.mql5.com
The Expert Advisors programming in MQL5 is simple, and you can learn it easy. In this step by step guide, you will see the basic steps required in writing a simple Expert Advisor based on a developed trading strategy. The structure of an Expert Advisor, the use of built-in technical indicators and trading functions, the details of the Debug mode and use of the Strategy Tester are presented.
 


 

 Try this in your EA, at the beginning of the OnTick function.

 

// We will use the static Old_Time variable to serve the bar time.

// At each OnTick execution we will check the current bar time with the saved one.

// If the bar time isn't equal to the saved time, it indicates that we have a new tick.


   static datetime Old_Time;

   datetime New_Time[1];

   bool IsNewBar=false;


// copying the last bar time to the element New_Time[0]

   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);

   if(copied>0) // ok, the data has been copied successfully

     {

      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time

        {

         IsNewBar=true;   // if it isn't a first call, the new bar has appeared

         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);

         Old_Time=New_Time[0];            // saving bar time

        }

     }

   else

     {

      Alert("Error in copying historical times data, error =",GetLastError());

      ResetLastError();

      return;

     }


//--- EA should only check for new trade if we have a new bar

   if(IsNewBar==false)

     {

      return;

     }

 

//--- Do we have enough bars to work with

   int Mybars=Bars(_Symbol,_Period);

   if(Mybars<60) // if total bars is less than 60 bars

     {

      Alert("We have less than 60 bars, EA will now exit!!");

      return;

     } 

 

 


 

Hi oneillj,

I thought I'd replied already, but it seems to have vanished into the internet ether.

The code fragment you provided is pretty much the one I was complaining about in the first place. Why so complex? I just figured there had to be an easier way. I came up with this one, which seems to work. Please correct me if I'm wrong. (I also tried using BarsCalculated, but it was always equal to Bars, so the test always evaluated to false.)

   static int   LastBarCount = 0;
   if (Bars(_Symbol, _Period) > LastBarCount)
      LastBarCount = Bars(_Symbol, _Period);
   else
      return;

;-) Ian
Documentation on MQL5: Timeseries and Indicators Access / BarsCalculated
  • www.mql5.com
Timeseries and Indicators Access / BarsCalculated - Documentation on MQL5
 
I use this...
static int BARS;
//+------------------------------------------------------------------+
//| NewBar function                                                  |
//+------------------------------------------------------------------+
bool IsNewBar()
   {
      if(BARS!=Bars(_Symbol,_Period))
        {
            BARS=Bars(_Symbol,_Period);
            return(true);
        }
      return(false);
   }
 
"New Bar" Event Handler
  • 2010.10.11
  • Konstantin Gruzdev
  • www.mql5.com
MQL5 programming language is capable of solving problems on a brand new level. Even those tasks, that already have such solutions, thanks to object oriented programming can rise to a higher level. In this article we take a specially simple example of checking new bar on a chart, that was transformed into rather powerful and versatile tool. What tool? Find out in this article.
 
ssn:
I use this...
The risk with this method is if the price data for your symbol does not begin from January 4th 1971 then any loaded historical data while the expert is attached to the chart will be read as a new bar...
 
Comments that do not relate to this topic, have been moved to "Can mql5 be used in MT4 ?".
 

The iTime function gives the time of the bar.

When it changes it is a new bar.

 
Nathan5:

The iTime function gives the time of the bar.

When it changes it is a new bar.

This topic is about mql5. There is no iTime() function.
 

You can also try this:


// Rates structure array for last two bars 
   MqlRates mrate[2];                 
   CopyRates(Symbol(), Period(), 0, 2, mrate);

// NEW BAR CHECK.
//---------------
   static double   dBar_Open;     
   static double   dBar_High;
   static double   dBar_Low;
   static double   dBar_Close;
   static long     lBar_Volume;
   static datetime nBar_Time;

// Boolean for new BAR confirmation. 
   bool bStart_NewBar = false;

// Check if the price data has changed tov the previous bar.   
   if(mrate[0].open != dBar_Open || mrate[0].high != dBar_High || mrate[0].low != dBar_Low || mrate[0].close != dBar_Close || mrate[0].tick_volume != lBar_Volume || mrate[0].time != nBar_Time)
         {
         bStart_NewBar = true; // A new BAR has appeared!        

// Update the new BAR data.     
         dBar_Open   = mrate[0].open;      
         dBar_High   = mrate[0].high;
         dBar_Low    = mrate[0].low;
         dBar_Close  = mrate[0].close;                 
         lBar_Volume = mrate[0].tick_volume;
         nBar_Time   = mrate[0].time;
         }

// Check if a new bar has formed.   
   if(bStart_NewBar == true)
         {
         
// Your code.          
         
         }
 
Stephen Njuki:
I use this...
Sadly this does not seem to work in MQL5.
Reason: