How to count the number of new candles that appear ?

 

Hi, I'm new in MQL4.

counting the number of new candles.

I need, every time a new candle formed. Add a number to a variable.



I use the following code to find a new candle:
bool NewBar()
  {
   static datetime time=0;
   if(time==0)
     {
      time=Time[0];
      return false;
     }
   if(time!=Time[0])
     {
      time=Time[0];
      return true;
     }
   return false;
  }


and I use the following code to test it and get number of new candles, but not working.

int j=0;
int i=0;
for(i=1;i<3;i++)
{
   if(NewBar()==true)
   {
   j=i;
   Comment(i);
   }
}


any help, I appreciate

Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
  • www.mql5.com
Predefined Macro Substitutions - Named Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
v mail:

and I use the following code to test it and get number of new candles, but not working.

int j=0;
int i=0;
for(i=1;i<3;i++)
{
   if(NewBar()==true)
   {
   j=i;
   Comment(i);
   }
}

any help, I appreciate

Don't call NewBar in a loop.

The first time it may return true, but after that it will return false.

This is better.

   int j=0;
   int i=0;
   if(NewBar()==true)
      {
      for(i=1; i<3; i++)
         {
         j=i;
         Comment(i);
         }
      }
 
Keith Watford:

Don't call NewBar in a loop.

The first time it may return true, but after that it will return false.

This is better.

thank you for reply. when only one new candle appeared. Commented "2". this does not work too.

actually, I need to check 2 rules to find the break out of the Fibonacci line.

 
v mail:

thank you for reply. when only one new candle appeared. Commented "2". this does not work too.

I had no idea what you were trying to achieve with your code, I just corrected it.

Obviously, you will not see any comment except the last one in the loop as the earlier comments will be overwritten.

 
Keith Watford:

I had no idea what you were trying to achieve with your code, I just corrected it.

Obviously, you will not see any comment except the last one in the loop as the earlier comments will be overwritten.

thank you.

I need, every time a new candle formed

Add a number to a variable

 
My problem was solved by putting the word " static" before variable.

And the following code calculates the number of new Bars.

static int number;
    

   if(NewBar()==true)      
   {
   number++;
   }

      Comment(number);
Reason: