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 />

Chapter 4<br />

Working with Functions<br />

We're going to convert the code that we've discussed in the previous chapters into reusable<br />

functions. This will save us a lot of work, as we can focus on the details of our trading system instead<br />

of the mechanics of trading.<br />

The idea behind creating functions is to create a block of code that carries out a very specific task.<br />

The code should be flexible enough to be reused in a variety of trading situations. Any external<br />

variables or calculations will need to be passed to the function. We can't assume that any necessary<br />

values will be available to our function otherwise, since the function may reside in an external include<br />

file or library.<br />

For consistency, we will keep the same names for any external variables that we have used so far.<br />

We'll preface these variables with "arg", to indicate that they are function arguments.<br />

Lot Sizing Function<br />

Let's start with our lot size calculation, as defined on page 51:<br />

double CalcLotSize(bool argDynamicLotSize, double argEquityPercent, double argStopLoss,<br />

double argFixedLotSize)<br />

{<br />

if(argDynamicLotSize == true)<br />

{<br />

double RiskAmount = AccountEquity() * (argEquityPercent / 100);<br />

double TickValue = MarketInfo(Symbol(),MODE_TICKVALUE);<br />

if(Point == 0.001 || Point == 0.00001) TickValue *= 10;<br />

double LotSize = (RiskAmount / argStopLoss) / TickValue;<br />

}<br />

else LotSize = argFixedLotSize;<br />

}<br />

return(LotSize);<br />

The first line is our function declaration. We call this function CalcLotSize(). Compare this to the<br />

code on page 51. Notice that DynamicLotSize, EquityPercent, StopLoss and FixedLotSize are<br />

all function arguments now. The external variables with these names still exist in our program, we<br />

will just pass them to the function as arguments now.<br />

64

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

Saved successfully!

Ooh no, something went wrong!