Holding values of variables in an EA

 

My EA waits for the MACD to cross and sets a variable to 1, it then looks to see if a bar has opened below the bottom bollinger to take a buy trade or opened above the top bollinger to take a sell trade. I've printed this variable at the start of each bar to check. The reason for this is that if a trade is ended or the EA is opened, it may take a trade straightaway, rather than waiting for the MACD to cross first. The value is being initialised as 0, which is fine, when it crosses it becomes 1, but come the next bar, it becomes 0 again, where it should only be changed back to 0 after a trade has been ended. Essentially at the beginning of each bar it's initialising itself back to 0, rather than holding the value of, set when the MACD crosses. If i declare a value for the variable, ie, -1, it holds the value of -1 at the beginning of each bar instead of 1 when the MACD crosses. Can anyone help me or know a way to get a variable to hold it's value between bars? The EA i'm running is attached. Thanks in advance.

Files:
macd_bol.mq4  3 kb
 

Here two solutions:


///either you declare as global variable:

int FirstCross=0;

int start()
{
double MACD, MACDPrevious, BolLow, BolHigh;
int Total, Ticket, Count;

...
}


/// or you make it persistent in "terminal->tools->global variables"

int start()
{
int FirstCross = GlobalVariableGet("FirstCross");

...

....

...

if(there_is_a_cross)

GlobalVariableSet("FirstCross",1);

...

...

}


Second approach is better because the variable's value survive even if terminal is closed or crashes down.

 
Sorry for the late reply, been busy with work. The global variable works perfectly. I originaly had them set as global but was running into other errors and presumed that was the problem so made them local. Now i've moved them back to global and everything is working well. Thanks for your help
Reason: