>MQL4: Trailing stop-loss

>This program is written in the MQL4 programming language. This language is domain-specific and is used on the MetaTrader 4 trading platform. The syntax and semantics of this language are, to put it quite simply, just like C. Like C, its a nice language, and is easy to learn. All you need to do is put in the time. But I digress.

The following program in MQL4 doesn’t do a lot. I consider this a good thing, since I believe one can find effectiveness and efficiency most easily in the Unix philosophy of “Do one thing and do it well”.

Since reading Dr. Van Tharp’s book “Trade your way to financial freedom”, I have accepted his claim that the best stop-losses are volatility stops. And so I don’t intend my programs from now on to do anything more than use the ATR (Average True Range) as a rule for trailing stop-losses.

Down below is the code. If you know anything about C-programming (Or programming in any of the C-variants out there (They certainly do seem to be prolific)) you should find it easy to understand. The functions (Like OrderSelect, etc.) are explained in the MQL4 website.

extern int ordernumber; /* The user of the program provides this information, after getting it from the trading platform. */

/* Objective of this program:
Exit: Trailing 3 * ATR(20) stop-loss.

int start()
if(OrderSelect(ordernumber, SELECT_BY_TICKET) == true /* Are you able to select the order? If yes, do so. */
&& OrderCloseTime() == 0) /* Is the order still open? */
switch(OrderType()) /* Check the order type */
case OP_BUY: /* If it is a buy order, do the following. */
if(OrderStopLoss() < Bid - 3 * iATR(Symbol(), 0, 20, 1))
OrderModify(OrderTicket(), OrderOpenPrice(), Bid - 3 * iATR(Symbol(), 0, 20, 1), 0, 0, Blue);
case OP_SELL: /* If it is a sell order, do the following. */
if(OrderStopLoss() > Ask + 3 * iATR(Symbol(), 0, 20, 1))
OrderModify(OrderTicket(), OrderOpenPrice(), Ask + 3 * iATR(Symbol(), 0, 20, 1), 0, 0, Red);
else /* If we have not been able to select the order or the order is not open anymore. */
Print("OrderSelect has not been able to find the order ", ordernumber, ":", GetLastError());

I hope I have done a good job of providing comments, enough that the purpose of the code is easy to understand. I’ve read that that is a mark of good programming (Amongst others).

As one can see, this program only takes care of the exit part of a trading system. It contributes absolutely nothing to entry decisions and position-sizing. Those will have to be taken care of by the trader at their own discretion.

Leave a Reply