Join our fan page
- Views:
- 1000
- Rating:
- Published:
- 2025.04.03 11:16
-
Need a robot or indicator based on this code? Order it on Freelance Go to Freelance
For an Expert Advisor (EA), when a new quote ("tick") is received by MetaTrader, the standard OnTick() event handling function is called by the terminal. However, there is no standard event handling function for when a new bar (candle) starts.
To detect this, you need to monitor the opening time of the most recent bar. When it changes, it signifies the start of a new bar, and you can react to the situation and handle the event. The following code example, compatible with both MQL4 and MQL5, demonstrates one of the methods of how this can be achieved:
// Standard tick event handler void OnTick() { // Check for a new bar (compatible with MQL4 and MQL5). static datetime dtBarraCorrente = WRONG_VALUE; datetime dtBarraPrecedente = dtBarraCorrente; dtBarraCorrente = iTime( _Symbol, _Period, 0 ); bool bEventoBarraNova = ( dtBarraCorrente != dtBarraPrecedente ); // React to the event of a new bar and deal with the situation. if( bEventoBarraNova ) { // Detect if this is the first tick received and deal with the situation. /* For example, when it is first applied to the graph and the bar is somewhere in the middle of its progress and is not really the start of a new bar. */ if( dtBarraPrecedente == WRONG_VALUE ) { // Do something on the first tick or in the middle of a bar ... } else { // Do something when a normal bar appears ... }; // Do something independent of the previous condition ... } else { // Do something else ... }; // Do other things ... };
In the previous code, the static variable keeps track of the bar's opening time, even when returning from the OnTick() function. Unlike a normal local variable, it memorises its data content and does not release it when leaving the function. This is the key to detecting a change in the current bar's opening time.
It is also important to note that when the EA is placed on a chart for the first time, the previous code reacts as if the bar had just opened. This condition requires special treatment if the situation needs to be handled differently.
Please note that the source code for all my CodeBase publications is now also available via MetaEditor 's "Public Projects" under the name "FMIC".
Translated from Portuguese by MetaQuotes Ltd.
Original code: https://www.mql5.com/pt/code/41601

Calendar - fundamental analysis on history and real-time.

Tester's single pass data.

This Bot detects the open of a new candle on any set timeframe, thereby making it easier to run a one-time code, place trades and call other functions. The code is written in the OnTick() function.

Algorithm cycle: when there are no open positions, open two opposite positions. Wait for both positions to close.