MQL4 BASICS - CREATE YOUR OWN AUTOTRADING EXPERT ADVISORS FOR FREE

What is a Magic Number in MQL4

Introduction

In the context of automated trading on the MetaTrader 4 platform, a "Magic Number" is a unique identifier for trades which allows Expert Advisors (EAs) to distinguish between different trades.

Why is it Important?

When multiple EAs or manual trades are running on the same account, it becomes essential to track which trade belongs to which strategy. Magic numbers play a crucial role in this:

  • They help EAs identify which trades they should manage.
  • They prevent EAs from interfering with trades they did not open.
  • They facilitate effective trade management and reporting by associating trades with specific strategies.

How is it Used?

When opening a trade via the OrderSend() function, the magic number can be set. It can later be retrieved using the OrderMagicNumber() function when a trade is selected.


              
int MyMagicNumber = 12345;
int ticket = OrderSend(Symbol(), OP_BUY, 1.0, Ask, 3, 0, 0, "", MyMagicNumber);


            

Now lets filter for that magic number:


  
///Pretending that we have already ran through open trades using OrderSelect...



  
if( Some condition here && OrderMagicNumber()==MyMagicNumber) 

/// OrderMagicNumber() will grab the magicnumber(if any) of the selected order and will compare if it is the same number as "MyMagicNumber"... If so, the condition will be considered true...
 
{
 
Some action here

}

            

The above code demonstrates how to set and then retrieve a magic number for a trade.

Things to Note

  • It's essential to ensure that each EA or strategy has a unique magic number.
  • Manual trades have a default magic number of 0. Be cautious if your EA uses this value.
  • While the magic number can be any integer, it's a good practice to use a systematic approach to assign these numbers, especially if you run multiple strategies.

Conclusion

The magic number is an integral aspect of MQL4 programming, especially for traders who utilize automated strategies on MT4. Understanding and properly implementing magic numbers can streamline trade management and improve the robustness of automated trading operations.