Seems a bit complicated for identifying new bar and taking some action.
I've always used this
datetime bartime; void OnTick(){ if(bartime==iTime(_Symbol,_Period,0))return; bartime=iTime(_Symbol,_Period,0); // action on new bar Comment(Close[1]," ",Close[2]); }
Detecting the start of a new bar or candle - expert for MetaTrader 4
Fernando Carreiro, 2022.04.24 00:46
Detecting the start of a new bar or candle, in the OnTick() event handler of an expert advisor.#property copyright "Copyright \x00A9 2022, Fernando M. I. Carreiro, All rights reserved" #property link "https://www.mql5.com/en/users/FMIC" #property version "1.001" #property strict // Default tick event handler void OnTick() { // Check for new bar (compatible with both MQL4 and MQL5). static datetime dtBarCurrent = WRONG_VALUE; datetime dtBarPrevious = dtBarCurrent; dtBarCurrent = iTime( _Symbol, _Period, 0 ); bool bNewBarEvent = ( dtBarCurrent != dtBarPrevious ); // React to a new bar event and handle it. if( bNewBarEvent ) { // Detect if this is the first tick received and handle it. /* For example, when it is first attached to a chart and the bar is somewhere in the middle of its progress and it's not actually the start of a new bar. */ if( dtBarPrevious == WRONG_VALUE ) { // Do something on first tick or middle of bar ... } else { // Do something when a normal bar starts ... }; // Do something irrespective of the above condition ... } else { // Do something else ... }; // Do other things ... };
You can't know when a candle closes. Only when a new tick arrives that starts a new bar is the old bar closed, and that tick could arrive almost at the end of a bar's duration.
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)

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hi,
How would I amend the below code to perform an action (for example Alert new Close Price 1 and 2 only) after the opening of the subsequent bar?
I will be grateful for your help.