25.10.2016 Views

Expert Advisor Programming by Andrew R. Young

Expert Advisor Programming by Andrew R. Young

Expert Advisor Programming by Andrew R. Young

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

EXPERT ADVISOR PROGRAMMING<br />

specified <strong>by</strong> MaxOrders are placed. This method allows us to specify as many orders as we want<br />

using the MaxOrders variable, guaranteeing that every order we place will have a stop loss and a<br />

take profit.<br />

Global Variables<br />

In this book, we've been referring to variables with a global scope as "global variables." MetaTrader<br />

has a set of functions for setting variables at the terminal level, which means that these variables are<br />

available to every expert advisor that is currently running, assuming that we know the name of the<br />

variable to start with.<br />

The MQL documentation refers to these as "global variables", although a more appropriate name<br />

might be "terminal variables." We use the global variable functions in the MQL Reference under<br />

Global variables to work with these types of variables. The current list of global variables in the<br />

terminal can be viewed <strong>by</strong> selecting Global Variables from the Tools menu, or <strong>by</strong> pressing F3 on the<br />

keyboard.<br />

One way to use these variables is to store certain globally scoped or static variables to the terminal,<br />

so that if an expert advisor is shut down, we can pick up where we left off. Not all expert advisors<br />

require this, but more complex expert advisors will maintain a certain state that, if interrupted, will<br />

throw off the expert advisor's operation.<br />

The best way to prevent this is to avoid creating expert advisors that require such a level of<br />

complexity. But if it can't be avoided, then using global variable functions to store the current state to<br />

the terminal may be helpful in case of accidental shutdown. Note that this method is not foolproof,<br />

but it is likely the best method to achieve this.<br />

To declare a global (terminal) variable, use the GlobalVariableSet() function. The first argument is<br />

a string indicating the name of the global variable, and the second argument is a value of type double<br />

to assign to it.<br />

GlobalVariableSet(GlobalVariableName,DoubleValue);<br />

To keep your variable names unique, you may wish to create a global variable prefix. Declare a<br />

globally scoped variable in your expert advisor, and set the value in the init() function, using the<br />

current symbol, period, expert advisor name and magic number to create a unique variable prefix.<br />

136

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!