Static Magic Number

 
Hello coders! I coded my EA to use the time I place it on chart, converted to integer, as the Magic number. This helps to keep my Magic different each time I place it on a different chart. Problem is, the EA does not recognize it's deals after I switch time frames. 
Does this mean that the EA is initialized every time I change the chart period
Any suggestions on how to code a dynamic Magic which is not affected by period change?
 

Using global variables in OnInit()

  • Check if the GV exists, then read the value of the GV.
  • Else, calculate a new MagicNumber and create GV to store the MagicNumber
 
 
Fernando Morales:

Using global variables in OnInit()

  • Check if the GV exists, then read the value of the GV.
  • Else, calculate a new MagicNumber and create GV to store the MagicNumber
 

That's a fine hint. Thanks!

 
Fernando Morales:

Using global variables in OnInit()

  • Check if the GV exists, then read the value of the GV.
  • Else, calculate a new MagicNumber and create GV to store the MagicNumber
 

Yes, this could work, e.g. by calling in OnInit something like

if (!GlobalVariableCheck("magic_id")){GlobalVariableSet("magic_id",12345678);}

or to stick to the example

if (!GlobalVariableCheck("magic_id")){GlobalVariableSet("magic_id",(int)TimeCurrent());}
// note: global terminal variables are double by default --> needs to be casted as long or ulong in order not to cause warnings if used as magic id

.. as global terminal(!) variables have a lifetime of 4 weeks since last access. But isn't it the whole purpose of magic numbers to be unique identifiers for every EA?

This method on the other hand means that several instances of the same EA (e.g. running on different currency pairs) share the same magic id.


@Nelson Wanyama: I think it's better to avoid using the startup time for creating the magic number in the first place and chose something that is both unique for this instance of the EA, but also constant over time.

There are of course dozens of methods how this can be done.

Just to give you an example how I do it (other methods are just as good):

I use a string of max. 8 characters that is meaningful and unique for exactly this instance of an EA and then use this function to encrypt it to a ulong type variable for the magic id:

//+------------------------------------------------------------------+
//|      create magic number                                         |
//+------------------------------------------------------------------+
ulong StringToMagic(string eight_char_string)
  {
   ulong magic=0;
   for (int i=0;i<MathMin(StringLen(eight_char_string),8);i++)
     {
      magic=magic<<8; //=left shift of binary representation by 8 bits
      magic+=(uchar)StringGetCharacter(eight_char_string,i);
     }
   return magic;
  }

(excess characters >8 don't cause errors but are ignored because no more than 8 bytes (here: char variables) can be represented as a ulong variable)