How to pull price of **CURRENT/NEW** candle using mql4?

 

Hello there,


So I've been trying to use mql4 to create a little automated system.  I have a bunch of code that should recognise when there's a new candle present by simply comparing the open of the two most recent candles, and if they're different then voila.  This isn't exactly what this post is about though.


Say for example, I'm running the EA on a 5m chart, I can pull the open price of the candle that was present when I initiated/set the EA to run. I cannot figure out how to pull the open price from the CURRENT candle.  I've been testing a bit of code:


int OnInit()
  {
   //currentOpenPrice5m = Open[0];
   OnTick();
   return(INIT_SUCCEEDED);
  }
  
void OnTick()
  {
   currentOpenPrice5m = Open[0];
   MessageBox("currentOpenPrice5m = " + DoubleToStr(currentOpenPrice5m));
   OnTick();
  }

As you can see, I'm simply calling the OnTick() function over and over during this test and outputting the open price in a message box.

The issue I'm getting, is when a new candle occurs, it doesn't pull the open price for that.  It simply keeps pulling the open price from the candle that was present when the EA was set to run.  Would anybody know how I can retrieve the open price for the CURRENT/MOST RECENT candle?


This is my first time using MQL4, so I appreciate if I'm just doing something silly here.


Thanks!

 
// Uncompiled, Untested, simply typed out — MQL4 Only

int OnInit()
{
   return(INIT_SUCCEEDED);
};
  
void OnTick()
{
   // Display Comment in top-left of chart   
      Comment( "Current Prices: Open = ", Open[ 0 ], ", Close = ", Close[ 0 ] );
};
Don't call OnTick() (or any other event handler) from anywhere. It is an event handler called by the terminal.
 
Fernando Carreiro #:
Don't call OnTick() (or any other event handler) from anywhere. It is an event handler called by the terminal.

So that's where I was going wrong!  Very good to know.  That works great.  Thanks a lot :)

 

Exactly.

In addition, you wanted to compare the last two opens. For that, you need to wait for the start of a new bar. 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. A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum (2011)