Static variable behaviour

 

Hi,

I find that for indicators, the static variable content never hold whenever change of timeframe, this never happen to EA.

Anyone seeing the same, is this a bug in MT4?

 
Try using a global variable. As far as I know, changing timeframe is equivalent to removing and reattaching you EA/indicator to another chart.
 

Changing pair or TF does NOT reattach your EA. It goes through a deinit/init cycle but your statics and globals are not reloaded.

I assume this is the same is true for indicators attached.

 
WHRoeder: I assume this is the same is true for indicators attached.

a simple test would show you, that your assumption is wrong. during TF changes static variables keep there values in EA's but not in indicators.

there are workarounds for indicators but also many pitfalls/bugs/features (however you want to call them).

1) static variables in indicators don't survive TF changes, but they do survive in libraries called from indicators. so you have to wrap your variables in functions contained in a library.

2) in libraries (called from ind.) they do not survice if you declare a static initializer. example:

// all is valid for indicators only
int func_a() {
   static int var_a = 500; // is not static, content is lost at TF changes

   static int var_b;       // works, var_b will survive TF changes
   if (var_b == 0) {
      var_b = 500;
   }
   
   static string var_c[1];
   var_c[0] = "value";     // string variables only survive TF changes when put in an array
}


3) Tester is very special, it surprises with bugs for static string variables in EA's

int myfunc_b() {
   static string var_d[1];
   var_d[0] = Symbol();
}

we would assume, that after EA restart all variables are resetted, but MetaQuotes has another golden egg for us. Static string variables in EA's are not set back, the survive EA-restarts and even symbol changes. so don't wonder if you made a test with EURUSD, after that another one with GBPUSD, and suddenly you see crazy results. the reason is the static EA variables still hold the EURUSD values.

thank you MetaQuotes


 

Thanks emmzettel,

I call that a bug for indicator, static variable does not perform what is suppose to do per C programming.

Reason: