Exiting Loop according to bar count ?

 

hello

i am trying to exit a loop after number of bars appears


the code is like that 

void OnTick()
  {
  
    int barnum1 = (Bars (_Symbol,_Period));
    int barnum2 = (Bars (_Symbol,_Period))+1;


do
    {
    
    int barnum1 = (Bars (_Symbol,_Period));
  
    // do something here
    
     }
while (barnum2>barnum1);
}


however i am getting a warning  

declaration of 'barnum1' hides local variable


and the code doesnt exit the loop 

any help ?



 

and the code doesnt exit the loop 

any help ?

It exits loops somewhere but OnTick is being called with every incoming tick

 
Mohamed Mostafa Mohamed Sonbol: i am trying to exit a loop after number of bars appears
  1. Nothing is changing inside your loop. Stop trying. Exit and wait for a new tick.

  2. 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.
              MT4: New candle - MQL4 programming forum #3 (2014)
              MT5: Accessing variables - MQL4 programming forum #3 (2022)

    I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum (2011)

 
Yashar Seyyedin #:

It exits loops somewhere but OnTick is being called with every incoming tick

this is just a part of the code

the loop does not exit as i put a Print ("out of loop") after which is never executed. 

 
Mohamed Mostafa Mohamed Sonbol #: the loop does not exit as i put a Print (“out of loop”) after which is never executed. 

What part of “Nothing is changing inside your loop. Stop trying,” was unclear?

 
William Roeder #:

What part of “Nothing is changing inside your loop. Stop trying,” was unclear?

i get it now

thanks a lot !

 
Mohamed Mostafa Mohamed Sonbol: i am trying to exit a loop after number of bars appears

It seems that you have a X/Y problem issue. It is probable that you are in fact trying to detect a new bar event and going about it the wrong way by looking for a change in bar count.

A more correct way of detecting a new bar event is as follows:

Code Base

Detecting the start of a new bar or candle

Fernando Carreiro, 2022.04.24 00:38

Detecting the start of a new bar or candle, in the OnTick() event handler of an expert advisor.
 
Fernando Carreiro #:

It seems that you have a X/Y problem issue. It is probable that you are in fact trying to detect a new bar event and going about it the wrong way by looking for a change in bar count.

A more correct way of detecting a new bar event is as follows:

Thanks Fernando, Always to the rescue 

 i will look into your code for sure