This code will work on both MQL4 and MQL5:
// Check for New Bar static datetime dtBarCurrent = WRONG_VALUE; datetime dtBarPrevious = dtBarCurrent; dtBarCurrent = (datetime) SeriesInfoInteger( _Symbol, _Period, SERIES_LASTBAR_DATE ); bool boolNewBarFlag = ( dtBarCurrent != dtBarPrevious ); if( boolNewBarFlag ) { Print( "... do something ..." ); }
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.
New candle - MQL4 programming forum #3 2014.04.04
I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
Running EA once at the start of each bar - MQL4 programming forum 2011.05.06
Hi, Here is example which I use in mql5 Expert Advisors,
This code identify when new bar is formed and execute the code only once.
Hope it helps you.
int totalBars; void OnTick() { int bars = iBars(_Symbol, PERIOD_D1); if(cBars != bars) { /*** execute your code only once per period ***/ totalBars = bars; } }
If you are looking for something simply explained, check this out.
https://www.youtube.com/shorts/R17IjgiHdis
The code is from this short video.

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use