How to calculate only in the last bar

 

Hi all!

Just my first post here, new to the MQL4 community. Is a very simple question. I have used the search function of the forum, but haven't found the answer.

I have an indicator that only put a Comment in the chart to show if an average is below or above another. Sometimes one of the averages are beyond chart limits. I only want to perform the calculation in the last bar of the chart and keep it updated as the bars progress. What is the more efficient way to do that?

I have used this (limits the calculations to new bars):

int start()
  {
   int counted_bars=IndicatorCounted(),
       limit;
 
   if(counted_bars>0)
      counted_bars--;
   
   limit=Bars-counted_bars;
  
   for(int i=0;i<limit;i++)
   {
      if (condition) Comment("Something");
   }

   return(0);
  }


And this:

int start()
  {
   
   if (condition) Comment("Something");
   
   return(0);
  }

Both of them work, but don't know if the last code performs the calculation only in the last bar or in all.

Thanks in advance,

Sergio

 

Ok, so an indicator typically has a buffer used to display a line or a histogram or some other chart. It sounds as though you don't have any of that.

Therefore your second method is fine and is the most efficient and will update EVERY TICK (every price change). If you want to change it only once per bar then that needs more code and may/may not use less processing power, depending on what the overall code is like.

 

This is the simplest approach to what you want:

int start()
{    
   int start = 0;
   int counted_bars = IndicatorCounted();
   int limit = Bars - 1 - counted_bars;
   if(counted_bars < 0) 
      return(-1);
    
   for(int pos = limit; pos >= start; pos--)
   {   
       // Do here your logic.
       Comment("Hello World!");
   }
}

Calculations are made every tick if start = 0.

Cheers.

 
flaab:

This is the simplest approach to what you want:

Calculations are made every tick if start = 0.

Cheers.

I'm sorry, but WTF? The OP's (second) code is simpler than yours and works fine.

Why would you count bars if there is no buffer in the indicator?

Why, when you start the indicator, would you write the comment for as many bars as there are in the chart?

 
dabbler:

I'm sorry, but WTF? The OP's (second) code is simpler than yours and works fine.

Why would you count bars if there is no buffer in the indicator?

Why, when you start the indicator, would you write the comment for as many bars as there are in the chart?

Right, there are no buffers xD That is my "Hello World" template, he should change my comment :P
Reason: