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

We check for possible errors <strong>by</strong> examining the output of functions such as OrderSend(),<br />

OrderModify() and OrderClose(). If the function did not complete successfully, the function will<br />

return -1 for OrderSend(), or false for OrderModify() and OrderClose().<br />

In this section, we will create an error handling routine for the OrderSend() function. If the return<br />

value of OrderSend() is -1, we will run an error handling routine to display an alert to the user, and<br />

print relevant trade parameter and price information to the log.<br />

First, we must first retrieve the error code. This is done using the GetLastError() function. We<br />

need to store the return value of GetLastError() in a variable, because once GetLastError() has<br />

been called, the error code will be cleared and the next call of GetLastError() will return 0. We'll<br />

declare a global variable called ErrorCode and use it to store the value of GetLastError().<br />

Next, we'll need to get some descriptive information on the error. The include file stdlib.mqh<br />

contains a function called ErrorDescription(). This function returns a string with a description of<br />

the error. It's actually not very descriptive, but it's better than nothing. We'll need to add an<br />

#include statement for stdlib.mqh at the top of our file.<br />

Then we'll print an alert to the user's screen using the built-in Alert() function. This information will<br />

also be printed to the log. The alert will include the error code, the error description, and a short<br />

description of the operation we just attempted to carry out. This way you'll know exactly which<br />

section in your program generated the error.<br />

Finally, we will print relevant price information to the log using the Print() function. Along with the<br />

current Bid & Ask prices, we will include trade parameters such as the lot size and the order price.<br />

// Preprocessor section<br />

#include <br />

// Global variable<br />

int ErrorCode;<br />

// Order placement<br />

int Ticket = OrderSend(Symbol(),OP_BUYSTOP,LotSize,PendingPrice,UseSlippage,0,0,<br />

"Buy Stop Order",MagicNumber,0,Green);<br />

if(Ticket == -1)<br />

{<br />

ErrorCode = GetLastError();<br />

string ErrDesc = ErrorDescription(ErrorCode);<br />

string ErrAlert = StringConcatenate("Open Buy Stop Order - Error ",<br />

ErrorCode,": ",ErrDesc);<br />

Alert(ErrAlert);<br />

54

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

Saved successfully!

Ooh no, something went wrong!