Overview

In an Expert Advisor, the OnTick() function is executed automatically every time a new market tick arrives — meaning each time the Bid or Ask price changes. This makes it the central “loop” of your EA, where decisions are evaluated and orders are executed. Every trading algorithm in MQL5 depends on how efficiently OnTick() processes incoming data.

Ad

What You Will Be Able to Do

  • Understand when and how OnTick() is triggered.
  • Use OnTick() to monitor price changes in real time.
  • Implement trading logic and conditions based on price updates.
  • Control log output and processing frequency for efficiency.

Code Example


//+------------------------------------------------------------------+
//|                                                      TickLogger.mq5 |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property version   "1.00"
#property strict

// Called when the EA starts
int OnInit()
  {
   Print("TickLogger started on ", _Symbol);
   return(INIT_SUCCEEDED);
  }

// Called for every new tick
void OnTick()
  {
   string sym = _Symbol;
   double bid = SymbolInfoDouble(sym, SYMBOL_BID);
   double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
   datetime time = TimeCurrent();

   // Print current price data
   Print(StringFormat("[%s] Tick received: Bid=%f, Ask=%f", 
         TimeToString(time, TIME_SECONDS), bid, ask));

   // Example logic: trigger an alert if spread is unusually wide
   double spread = (ask - bid) / _Point;
   if(spread > 10)
      Print(StringFormat("Warning: Spread too wide (%.1f points)", spread));
  }

// Called when EA is removed or terminal closes
void OnDeinit(const int reason)
  {
   Print("TickLogger stopped.");
  }
Ad

Execution Steps

  1. Open MetaEditorFile → New → Expert Advisor (template).
  2. Name it TickLogger and click Finish.
  3. Replace the template code with the example above and press F7 to compile.
  4. Attach the EA to any chart in MetaTrader 5.
  5. Watch the Experts tab to see each tick and spread warning logged in real time.

Key Point

OnTick() is event-driven — it runs automatically for each market update. It’s the heart of every Expert Advisor, where signals, calculations, and trade executions are performed. Keep OnTick() efficient and lightweight to ensure your EA runs smoothly, even on fast-moving markets.

Ad

Next Section

→ Next: Before Using OrderSend