Expert Advisor Programming by Andrew R. Young
Expert Advisor Programming by Andrew R. Young
Expert Advisor Programming by Andrew R. Young
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Advanced Order Placement<br />
if(BuyStopLoss > 0 && BuyStopLoss > LowerStopLevel)<br />
{<br />
BuyStopLoss = LowerStopLevel - MinStop;<br />
}<br />
if(BuyTakeProfit > 0 && BuyTakeProfit < UpperStopLevel)<br />
{<br />
BuyTakeProfit = UpperStopLevel + MinStop;<br />
}<br />
// Place pending order<br />
if(IsTradeContextBusy()) Sleep(10);<br />
BuyTicket = OrderSend(Symbol(),OP_BUYSTOP,LotSize,PendingPrice,UseSlippage,<br />
BuyStopLoss,BuyTakeProfit,"Buy Stop Order",MagicNumber,0,Green);<br />
// Error handling<br />
if(BuyTicket == -1)<br />
{<br />
ErrorCode = GetLastError();<br />
ErrDesc = ErrorDescription(ErrorCode);<br />
ErrAlert = StringConcatenate("Open Buy Stop Order - Error ",ErrorCode,<br />
": ",ErrDesc);<br />
Alert(ErrAlert);<br />
}<br />
ErrLog = StringConcatenate("Ask: ",Ask," Lots: ",LotSize," Price: ",PendingPrice,<br />
" Stop: ",BuyStopLoss," Profit: ",BuyTakeProfit);<br />
Print(ErrLog);<br />
SellTicket = 0;<br />
First, we calculate the upper stop level. We then calculate and verify our pending order price, which<br />
is stored in PendingPrice. We then recalculate UpperStopLevel and calculate the LowerStopLevel<br />
so that they are relative to the pending order price. Note that we do not need to use the Ask or Bid<br />
prices, or figure in the spread when verifying the stop loss and take profit prices.<br />
Finally, we place our pending order using OrderSend(), placing the stop loss and take profit along<br />
with it. We have the standard error handling function to deal with order placement errors.<br />
Despite all the extra code, these expert advisors are using the same strategy as the one at the end of<br />
chapter 2. This code simply has extra features for calculating and verifying lot size, stop levels, stop<br />
loss, take profit and pending order prices. We've also added trade context checks and error handling<br />
code. In the next chapter, we'll learn how to create functions so we can reuse and simplify this code.<br />
63