Detecting New Candle Bars Efficiently in MetaTrader 5

Mike 2024.04.11 21:05 18 0 0
Attachments

Hey fellow traders! Today, we're diving into a nifty way to detect a new candle or bar using bar counts instead of relying solely on time. This method is not only lighter on your system but also faster, which means you can stay ahead of the game!

Here’s a quick rundown of how to implement this:

  • Declare Variables: Start by declaring your variables as integer data types to store the bar counts.
  • Initialization: During initialization, assign the bar count to the variable BarsTotal_OnInt.
  • Live Updates: Use the iBars(); function to update the bar count for the variable BarsTotal_OnTick every tick on the live chart.
  • Check Accuracy: Utilize comments and alerts to verify that your code is running as intended.

Here’s the code snippet to get you started:

int BarsTotal_OnInt; 
int BarsTotal_OnTick;
//+------------------------------------------------------------------+
//| Expert initialization function                                      |
//+------------------------------------------------------------------+
int OnInit()
  {  
   BarsTotal_OnInt = iBars(NULL,PERIOD_CURRENT); // Assign the total bars at initialization
   return(INIT_SUCCEEDED);
  }
  
void OnTick() // OnTick Function
  {   
   BarsTotal_OnTick = iBars(NULL,PERIOD_CURRENT); // Stores the latest amount
   
   if(BarsTotal_OnTick > BarsTotal_OnInt) // New bar has arrived
   {
    BarsTotal_OnInt = BarsTotal_OnTick; // Updates the history.
    Alert("New Bar has arrived");
    Comment("Bars Count in history -: ", BarsTotal_OnInt, "\n", "Bars Count in Live -: ", BarsTotal_OnTick);

     // Your Code goes here. --------------------------
    
    // You can update a "flag" / variable to use it on later too. 

   }
  }

Give this a whirl in your own trading setup and watch how smoothly you can detect new bars. Happy trading!

List
Comments 0