Skip to content
All library documents

MQL5 ForEach Macros for Symbols, Objects, Orders, and Positions

Article MQL5 articles

Summary

This programming tutorial shows how to use MQL5 #define macros to imitate foreach-style loops. It builds macros for iterating over Market Watch symbols, chart objects, orders, positions, and historical deals, with examples of reading properties such as symbol spreads and object types. A key implementation detail is that the first collection item must be initialized before the loop body runs; the article explains how loop initialization and increment expressions affect that behavior. It also shows splitting long macro definitions across lines for readability.

The approach can reduce repetitive code and make loops more concise, but it has practical costs: macro expansions are harder to debug, arguments lack tooltips, and hidden variables can collide with names in surrounding code. Some examples also omit error handling, including checks for history selection. The article presents this as a convenience for developers migrating from MQL4 conventions, while noting that the author prefers standard MQL5 practices. These are coding techniques, not trading methods or evidence of strategy performance.

Key ideas

  • MQL5 macros can package repeated collection-loop patterns into foreach-like constructs.
  • Initialize the first item before entering the loop because the increment expression runs after each iteration.
  • The examples cover symbols, chart objects, active orders, positions, and historical deals.
  • Macros can shorten repetitive code but make debugging and variable-scope management more difficult.
  • The examples omit some error checks, so users must decide whether to add handling for failed API calls.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.