Complete MQL5 guide & code

MQL5 Printf, PrintFormat & Comment: Logging & Chart Displays

Guide to MQL5 printf, PrintFormat, StringFormat, and Comment functions. Format floating-point numbers, output structured logs, and build on-chart dashboards.

What this MQL5 guide covers

In MQL5, printf() is a direct functional alias for PrintFormat(); both print formatted strings into the Experts terminal log.

Use format specifiers such as %.5f for currency quotes, %I64u for 64-bit tickets, %s for text, and %t for datetime timestamps.

StringFormat() formats text into a string variable without printing, making it the standard choice for multi-line status HUDs.

The Comment() function writes text directly into the upper-left corner of the chart, and calling Comment("") clears the display on deinit.

Print vs PrintFormat vs printf in MQL5

The standard Print() function in MQL5 concatenates parameters separated by commas with default type formatting. While simple, it provides little control over decimal precision, alignment, or leading zeros.

PrintFormat() and its alias printf() bring C-style format strings to MQL5. They accept a format specification string followed by argument values, outputting directly to the terminal Experts tab.

Format SpecifierTarget Data TypeExample Output
%d or %iint, short, char14, -200
%uuint, ushort, uchar500
%I64u / %I64dulong (ticket, magic), long12004589211
%.2fdouble (percentage, currency)1250.50
%.5fdouble (forex exchange rate)1.08452
%sstringEURUSD
%tdatetime2026.10.01 14:30

Constructing On-Chart Status Panels with Comment()

The Comment() function projects text onto the upper-left region of the chart window. It serves as an accessible display tool for displaying real-time EA status without creating complex graphical panel objects.

To build multi-line dashboards, combine StringFormat() with newline escape sequences (\n). Update the comment inside OnTick() or on a timer event.

  • Each call to Comment() replaces the previous chart comment completely.
  • Passing an empty string Comment("") clears the chart display.
  • Only one program can control the chart comment; the latest attached EA or indicator overrides it.

Formatting Memory vs Terminal Output: StringFormat

While printf() sends text straight to the log, StringFormat() generates and returns a formatted string without producing terminal I/O. Use StringFormat() whenever you need to save text into files, send Telegram alerts, or render chart labels.

Constructing a string with StringFormat("%s | Spread: %d", symbol, spread) is cleaner and faster than chaining multiple string additions with the plus operator.

Production Logging and Terminal Performance

Calling printf() or PrintFormat() on every single tick in a high-frequency trading bot creates disk write bottlenecks. The MetaTrader terminal writes expert logs to disk files under MQL5/Logs.

Use an input toggle like input bool InpVerboseLogging = false; to suppress non-critical tick messages during live trading or multi-year Strategy Tester optimizations.

Implementation details & mechanics

Core implementation pattern

During OnInit(), use PrintFormat() to output a clean configuration banner recording symbol digits, point size, lot size, and magic number. In OnTick(), build a status summary string with StringFormat() and pass it to Comment() to show live equity, floating PnL, and current signal thresholds on the chart.

Error handling & safety rules

In OnDeinit(const int reason), invoke Comment("") to remove the dashboard text from the chart. When positions close, log the completed deal ticket, realized profit, and exit reason using PrintFormat("Deal #%I64u closed at %.5f | Profit: %.2f", dealTicket, exitPrice, dealProfit).

MQL5 Code Implementation Code

//+------------------------------------------------------------------+
//|                                  PrintfPrintFormatCommentGuide.mq5|
//|                             Copyright 2026, Pineify Guides Series |
//|                                              https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link      "https://pineify.app/mql5/printf-printformat-comment-guide"
#property version   "1.00"
#property strict

//--- Input parameters
input double InpRiskPercent  = 1.5;        // Risk Per Trade (%)
input ulong  InpMagicNumber  = 884400;     // Expert Magic Number
input bool   InpVerboseLog   = true;       // Enable Detailed Logging

//--- State tracking
ulong g_tickCounter = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // printf() and PrintFormat() are identical in MQL5
   printf("=== Pineify EA Initialized: %s ===", _Symbol);
   PrintFormat("Settings -> Risk: %.1f%% | Magic: %I64u | Digits: %d | Point: %.5f",
               InpRiskPercent, InpMagicNumber, _Digits, _Point);

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Clear on-chart HUD comment
   Comment("");

   PrintFormat("EA removed from %s. Cleared HUD. Reason code: %d", _Symbol, reason);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   g_tickCounter++;

   // Gather real-time account and market metrics
   double ask       = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid       = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   int    spread    = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   double balance   = AccountInfoDouble(ACCOUNT_BALANCE);
   double equity    = AccountInfoDouble(ACCOUNT_EQUITY);
   double profit    = AccountInfoDouble(ACCOUNT_PROFIT);

   // Build multi-line on-chart dashboard via StringFormat
   string hudText = StringFormat(
      "------------------------------------------\n" +
      " PINEIFY DASHBOARD: %s\n" +
      "------------------------------------------\n" +
      " Ask: %.*f | Bid: %.*f | Spread: %d pts\n" +
      " Balance: $%.2f | Equity: $%.2f\n" +
      " Floating PnL: $%.2f\n" +
      " Processed Ticks: %I64u\n" +
      " Server Time: %s\n" +
      "------------------------------------------",
      _Symbol,
      _Digits, ask, _Digits, bid, spread,
      balance, equity,
      profit,
      g_tickCounter,
      TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS)
   );

   // Update chart display
   Comment(hudText);

   // Output formatted log on every 100th tick if verbose mode enabled
   if(InpVerboseLog && (g_tickCounter % 100 == 0))
     {
      PrintFormat("[Tick #%I64u] %s Spread: %d pts | Floating: $%.2f",
                  g_tickCounter, _Symbol, spread, profit);
     }
  }

Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.

Generate custom MQL5 code with Pineify AI

Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify produces clean, typed MQL5 source code ready to compile in MetaEditor.

Frequently Asked Questions

Related MQL5 pages

Technical references

Risk and testing note

Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.