MQL4 On New Bar

When you are programming an Indicator or an Expert Advisor you want in many cases execute some task at the opening of a new bar.  For many beginners this can seem like a difficult operation but you will see that it is not. In this article you will see with the MQL4 On New Bar code that it is a very simple operation. MQL4 On New Bar

MQL4 On New Bar

In trading automation often you want to run some tasks or checks when a bar closes and a new bar begins. Some example of operations to run at the start of a new candle are:
  • Send a notification regarding the status of the last closed bar
  • Assess an indicator to check if you should open an order
  • Assess an indicator to check if you should close an order
  • Update of take profit and or stop loss prices
These are very frequent tasks that many times can be done once per candle when a new bar starts. Coding this type of behaviour is not hard and only requires a few lines of code. We are going to see here the required code. You can see how removing all the comments you really only need a few lines The logic of the script is:
  1. Create a variable and store the current server time
  2. Create a function that checks the time and returns true if it is a new candle and false if not
  3. Compare the start time of the last candle with the start time of the current candle
  4. If the time is the same then it is the same candle, if it is different then we are in a new candle
  5. If it is a new candle return true and update the time
  6. In the OnCalculate or OnTick  function use a if(IsNewCandle()){ }  to execute the task you want in the new candle
It is worth remembering that the IsNewCandle() would return true every time the function is initialized. For example the first time it runs or when you change the symbol or timeframe.

Conclusion of MQL4 On New Bar

As you can see in the code above, checking if the candle is new is not hard at all. With only a few changes you can adapt the code to what you need. MQL4 On New Candle is simple and can resolve several headaches.

If you want to save hours of research and coding and you want to see some professional code check this out! You can use it to build your own EA!

Leave a Comment