Hey there, fellow traders! Today, we're diving into how to detect the beginning of a new candle in MetaTrader 4, a handy skill for anyone using an Expert Advisor (EA). Unlike ticking quotes, which trigger the OnTick() function, there’s no built-in function for when a new bar starts. But don’t worry; I’ve got you covered!
To figure out when a new bar opens, we need to keep an eye on the opening time of the most recent candle. Once that changes, we know a new bar has started, and we can take action. Below is a sample code that works for both MQL4 and MQL5:
// 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 ... };
In this code, the static variable tracks the bar's opening time, keeping its value even after we leave the OnTick() function. This is crucial for spotting when the current bar's opening time shifts.
Don't forget, when you first place the EA on a chart, the code will act as if a new bar has just opened, so make sure to handle that condition if it needs a different approach.
And just a heads up, you can now find all my CodeBase publications' source code in the "Public Projects" tab of MetaEditor under the name "FMIC". Happy trading!
연관 포스트
- Unlocking Positive Swaps: Your Guide to Market Watch in MetaTrader 4
- Mastering Divergence and RSI: Your Go-To Guide for MetaTrader 4
- Mastering Trailing Stop Loss for All Your Trades in MetaTrader 4
- Mastering the MT4 EA Template: A Trader's Guide to Expert Advisors
- Streamline Your Trading with a Fixed Interval Close Order EA for MetaTrader 4