What is the function of Magic Number on OrderSend function ?

 

Dear Friends,

What is the function of Magic Number parameter on OrderSend function ?

OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)

Thank you very much.

Sincerely,

Roby Widjaja.

 
 
roby_widjaja:

Dear Friends,

What is the function of Magic Number parameter on OrderSend function ?

OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=xxxxxx, datetime expiration=0, color arrow_color=CLR_NONE)

Thank you very much.

Sincerely,

Roby Widjaja.

 

it is similar to the comment string in that you use it to identify (group or tag) certain trades that belong together (usually trades of the same EA). While the comment is usually used for a human being to quickly see which trades belong to which EA, the magic number serves the same purpose when this grouping should be done programmatically. (Historically integer comparisons have always been orders of magnitude faster than string comparisons, therefore it is still common practice to use integer numbers instead of strings for indexing and keys)

Practically you will assign each EA (and each instance) a unique number and each trade opened by this EA can then be tagged with this number. When your EA later wants to close its trades or count the open trades or otherwise needs to identify its own trades it will loop through all trades and easily find the ones with its own number by comparing OrderMagicNumber() of each order in the list against its own magic number.

The easiest way to assign each of your EAs such a number is calculating a 32 bit hash over the string WindowExpertName() + Symbol() + Period() or a similar unique string. An example of such a hash function and the usage of magic numbers can be found here: makeMagicNumber() in the free common_functions.mqh functions library. There are also a lot of utility functions in this library for order handling that make heavy usage of the magic number. I suggest studying this lib, its very educational.

 
My question is answered very well. Thank you very much, 7bit :-)
 
    for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
        OrderSelect(pos, SELECT_BY_POS)            // Only my orders w/
    &&  OrderMagicNumber() == Magic.Number         // my magic number
    &&  OrderSymbol()      == Symbol() ){          // and symbol
        // Trail stops etc.
    }
 

Thank you very much for the code example, WHRoeder :-)

Reason: