|
|
|
|
|
|
|
|
First rule of business: protect your investment.
Etiquette Of The Banker, 1775
Until now we used in the Expert Advisor only orders with rigidly set StopLoss and TakeProfit levels. Thus having opened a long position we wail until one of the two levels works out – either we get profit, or we get loss. Tertium non datur. But many traders consider the system of exiting a trade to be more important than the system of entering into a position in a trading system. The most basic technique for establishing an appropriate exit point is the ( Trailing Stop) technique. In this case the stop-loss order is adjusted continually based on fluctuations in the market price, and in case of a sudden reverse it allows to receive a part of paper (unrealized) profit, instead of getting loss if the initial stop-loss order was executed.
Before we write the trailing stop function we will get rid of all the lacks of our expert advisor which trades on the basis of random signals. For this we will have to write it practically over again (we will call it RTS.mq4 – Random Trade + Statistika).
|
|
|
|
I used empty functions, i.e. functions are declared, but nothing is calculated in them, they return empty values. It can be convenient at writing complicated systems if you have a complete algorithm. The expert advisor in such form is compiled without errors (the isNewBar() function isn’t seen simply). Now we can fill each empty function with a code and compile our expert for checking changes that were made for rude mistakes.
Schematically I showed it as follows:
|
|
|
|
The block number 1 has been realized by means of checking a new bar, if isNewBar() returns true (a new bar appeared) , then at first availability of a signal for opening a long position is checked (SignalExist(OP_BUY)), and if there is such signal, an attempt to open a buy order is made (GetOrder(OP_BUY)). Similarly checking for opening a short position is performed. Now signal for long and short positions are divided and don’t influence each other, we have got rid of the lack in the previous version.
Please note that I used reserved words from MQL-4 as parameters (OP_BUY and OP_SELL). This makes it easier to understand the code for you and for those who will read it. If I used instead of them concrete values, you would have to open the Help to remember what the 0 parameter means at calling the GetOrder function(0) .
|
|
|
|
Besides later the consideration of nuances of opening positions OP_BUY and OP_SELL will allow us to optimize the expert advisor in the LongOnly mode and the ShortOnly mode separately.
The block number 2 consists of a simple call of the EveryTick() function, which is also empty so far. In the previous advisor in the deinit() function we used the call of the HistoryCalculate() function, I’ve modified the call a little, in order to calculate statistics only in the tester.
|
|
|
|
While working on-line this function isn’t called now, but there is also optimization. While performing an optimization we don’t need it as well. We will add the IsOptimization() checking.
|
|
|
|
At first we will write the function of receiving a signal, to calculate the time of the last order closing we added a new function – GetLastCloseTime().
|
|
|
|
You may see for yourself that now the calculation of the period of time since the last moment of the order closing is performed more correctly, the period of time between Friday’s evening and Monday’s morning doesn’t include the days off.
Now we write the GetOrder() function on the basis of the previous version. I have only modified the way of filling a commentary so that we can analyze the price movement for the last 3 bars. I.e. we still open positions against the trend, but we want to find a connection between the result of trade and the direction and amplitude of movement just before opening a position. Later you may write in the commentary any information you are interested in for further analysis.
|
|
|
|
The advisor is almost ready. In the previous version we checked the availability of open orders.
|
|
|
|
and concluded that this was wrong. But if we don’t check the availability of open positions we won’t have the possibility to control the number of these orders. That’s why we will add an external variable MaxOpenOrder and theAllowedOpenOrder() function (allowability of opening new orders of certain type).
|
|
|
|
Now we can test once more our hypothesis that when StopLoss=65 points and TakeProfit=130 points it is necessary to open positions against the readings of the indicator MACD. We will save this version as RTS2.mq4. We will launch again testing on EURUSD H1 and will get one of the results.
|
|
|
|
There is no profit, the ratio between profitable and losing trades reflects the ratio between SL and TP. But the number of long and short positions doesn’t depend now on the LongOnly mode and the ShortOnly mode. Now we can write the TrailingStop() function.
The main function of the trailing stop is to protect paper profit by means of adjusting the StopLoss level in the direction of the open position. If we move the stop loss order too quickly an occasional movement against our position may break us out of the trade, after which the price may go in our direction. And we move the stop loss order too slowly then an unfavorable reversal may eat up the most part of our profit. As you see everything depends on the algorithm. That’s why at first we set forth some idea and then we try to program it.
There are a lot of algorithms of trailing stops, I will consider only two of them. I called them for myself dynamic and static. Dynamic trailing – is moving the protective stop each time the price changes; if the price jumped by 100 points in our direction (suppose upwards for buying), then the protective stop at once will be trailed (upwards) also by 100 points. Static trailing – is moving the stop according to certain criteria that don’t depend on the current price. For example, moving stops on each new bar according certain algorithm. It allows to ignore the price fluctuations inside the bar.
At first we will realize the dynamic trailing stop.
|
|
|
|
Everything is simple in this function and doesn’t require any additional description. If TS=50, the current stop will be at 1.2643.
|
|
|
|
We will add the call of trailing in the call for each new bar. In this case modification of orders will be always performed identically (when a new bar appears), independent of the testing mode.
|
|
|
|
I have this version of the expert as RTS+TS.mq4 (TS – Trailing Stop). We compile it and launch it on EURUSD H1.
|
|
|
|
Now we can consider the variant of static trailing. We will introduce the notion of risk. Risk is a potential loss that is equal to the distance that the price goes from the opening level to the level of the stop. This is of course incorrectly, but that’s not the point. The idea will be as follows: the level of risk must decrease as the square of time. If from the moment of opening the position X amount of time has elapsed and the risk is equal to Y, then in X*2 of time the risk must reduce fourfold. Roughly speaking we are trying to realize the trailing stop by analogy with the Parabolic indicator.
|
|
|
|
Many traders try to realize a trailing stop on expert advisors based on the readings of the Parabolic SAR indicator. But this approach has one disadvantage – for the indicator it’s all the same where you entered into a position. That’s why we will write an algorithm which will really adjust the level of the protective stop on the principle of parabola and will be pegged to our point of entry.
Suppose at the moment of opening of the order we put the StopLoss at a distance of S points. At that we consider that if we have opened the position in the right direction, then in N bars we will be flat, i.e. no profit or loss, (the level of the StopLoss can be moved to the level of the opening of the order). From school physics we remember that in case of parabolic motion the distance S=(a*t^2)/2+V*t+C, where а is acceleration, V- is initial velocity, in our case it is equal to zero, and С – initial displacement, it is equal to the value of the stop with minus sign. Then S= (a*t^2)/2 or a=2*S/t^2.
|
|
|
|
If our initial stop is equal to 50 points, while the position must become flat in 5 bars, then a= (2*50)/5^2=100/25=4 points/bar^2. In 1 bar the stop will be 4*1/2-50=-48, i.e. at 48 points from the opening price. In 2 bars the stop will be equal to 4*2^2/2-50=-42 . In three bars the stop will be equal 32 points, in four bar – 18 points, in five bars : 4*5^2/2-50=0 – we may place an order to become flat, if by that time we haven’t been closed by the stop order. We have the algorithm; we only have to write the code.
|
|
|
|
We change a little the start() function:
|
|
|
|
We compile the expert advisor RTS+TS2.mq4 and test it under the same conditions and with the same parameters. Unfortunately this variant of a trailing stop didn’t give us any improvement of results. Perhaps parabolic trailing isn’t an appropriate variant for this strategy. We can change a little the EveryTick() function.
|
|
|
|
Then testing on other models («All ticks», for example) will cardinally change the behavior of the expert. You may experiment yourself. All the variants of expert advisors are here .
Go to article «It catches your eye, but the code can't catch it».
|
|