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.

Working with Functions<br />

Order Closing Function<br />

Lastly, let's create a function for closing a single order. We'll use the order closing block from the code<br />

on page 58. In the next chapter, we'll examine ways of closing multiple orders of the same type,<br />

which is a simpler method of closing orders. But in case you need to close just one order, this<br />

function will do the trick:<br />

bool CloseBuyOrder(string argSymbol, int argCloseTicket, double argSlippage)<br />

{<br />

OrderSelect(argCloseTicket,SELECT_BY_TICKET);<br />

if(OrderCloseTime() == 0)<br />

{<br />

double CloseLots = OrderLots();<br />

while(IsTradeContextBusy()) Sleep(10);<br />

double ClosePrice = MarketInfo(argSymbol,MODE_ASK);<br />

bool Closed = OrderClose(argCloseTicket,CloseLots,ClosePrice,argSlippage,Red);<br />

if(Closed == false)<br />

{<br />

int ErrorCode = GetLastError();<br />

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

string ErrAlert = StringConcatenate("Close Buy Order - Error: ",ErrorCode,<br />

": ",ErrDesc);<br />

Alert(ErrAlert);<br />

}<br />

}<br />

string ErrLog = StringConcatenate("Ticket: ",argCloseTicket," Ask: ",<br />

MarketInfo(argSymbol,MODE_ASK));<br />

Print(ErrLog);<br />

}<br />

return(Closed);<br />

For the ClosePrice variable, we use MarketInfo() to retrieve the current Ask price for the currency<br />

indicated <strong>by</strong> argSymbol. We use the function arguments argCloseTicket and argSlippage for the<br />

closing order ticket and the slippage, respectively. If the order was not closed successfully, we run<br />

the error handling block, which prints the ticket number and current Ask price to the log.<br />

The code to close a sell order will be identical, except that you'd use the Bid price for the<br />

ClosePrice variable. You can view the sell market close function in Appendix D.<br />

69

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

Saved successfully!

Ooh no, something went wrong!