Welcome Forex EA downloads & MT4/MT5 auto-trading resources — EAs, Gold EAs, quant tools and real-world automation.
Sign In Sign Up

Library of functions and Experts for tracking / Yury Dzyuban - MetaTrader 4 Library

author EAcpu | 5 reads | 0 comments |

As we all know, the algorithm for maintaining and closing a position is almost more important than the rules for opening it. Sometimes changes to the tracking system can result in considerable changes in trading performance - either an increase or decrease in the latter. This is a library for maintaining open positions, which I used when building my system.

The functions presented are based on some of the most popular tracking algorithms, other functions are probably my original developments, or at least I haven't seen them before. These features are easy to include/select, which allows them to be quickly applied to portal systems to test different tracking scenarios. The proposed functions are basic and allow the construction of more complex tracking algorithms on their basis, if desired. These functions are very different and were written to simplify the process of building new EAs.

So, the function itself:

1. Trail the shadows of the last N bars.

 blank shadow trailing( integer votes, integer TMFRM, integer bars_n, 
integer indentation, boolean trillingLoss)

This function implements a trailing stop based on the lowest low (for long positions) or the highest high (for short positions) of the current timeframe or a specified number of bars within the current timeframe.

parameter:

ticket - unique order number (selected before calling function OrderSelect() );
tmfrm - time frame whose bars are used for tracking (options - 1, 5, 15, 30, 60, 240, 1440, 10080, 43200);
bar_n - the number of bars to determine the stop loss level (not less than 1);
Indent - the indent (in points) from the selected high/low price to set the stop loss (not less than 0);
Trillinlos - whether to move the stop loss to the "unprofitable" zone, i.e. the range between the initial stop loss and the opening price (true - trailing, false - trailing is only activated if the new stop loss is "better" than the opening price, "profitable").

This type of tracking originally appeared in V. Barishpolts' strategy description for "Average Breakouts on Daily Charts", which suggested tracking the low (buy) or high (sell) of the latest 2 bars (candles) with a stop loss on the daily time frame. The trajectory of the algorithm is surprisingly "good" (try "looking around" the chart "with eyes"), allowing to survive rollbacks (the depth depends on the specified number of bars, bar_n ) and periods of worsening volatility. (By definition) it triggers at the close of the next bar, even though it is used on every tick. I mainly use it on daily charts to track the 2-4 (most common) latest bars.


2. X-bar trailing fractal.

 blank fractal trailing( integer votes, integer tmfrm, integer frktl_bars,
integer indentation, boolean trillingLoss)

This function tracks the stop loss based on the fractal extremum of a specified size (i.e. the number of bars included in the fractal) within a specified time frame. As we all know, the "classic" fractal (designed by Williams if I remember correctly) is a combination of 5 bars. But then I thought - why not use "other" dimensions - 3 bars or more, including the number of paired bars (in the latter case, when the move "goes into the past", the number of exposures after the extreme will be greater than the number of exposures before the extreme).

parameter:

ticket - unique order number (selected before calling function OrderSelect() );
tmfrm - time frame whose bars are used for tracking (options - 1, 5, 15, 30, 60, 240, 1440, 10080, 43200);
bars_n - the number of bars contained in the fractal (not less than 3);
Indent - the indent (in points) from the latest fractal extremum to set the stop loss (not less than 0);
Trillinlos - whether to move the stop loss to the "unprofitable" zone, i.e. the range between the initial stop loss and the opening price (true - trailing, false - trailing is only activated if the new stop loss is "better" than the opening price, "profitable").

In several Russian Forex related forums it was noted that "fractal-based tracking works well on shorter time frames". Since fractals are essentially local extrema, their trail is also essentially the trail of local extrema. This idea is not new, is quite powerful, and has been used by many famous traders (the aforementioned Williams if I remember correctly). It tolerates rollback well and "picks" noticeable movement, but not so well during flat periods (from personal experience). Like the previous function, this function "traces" on already formed bars. If necessary, parameters can be changed dynamically (using the "Lifetime" position). For example, during periods of rapid profit "growth" (for example, in a strong trend), "roughen" its sensitivity by switching to a higher timeframe or increasing the number of bars in the fractal. Or conversely, increase sensitivity during volatility drops by switching to a smaller timeframe or reducing the number of bars in the fractal. Other options are also possible.


3. Standard trailing - "stepped".

 Blank trailing stairs ( integer votes, integer three distances, integer three steps)

This trailing type is an improvement on the standard type. As far as I know, a similar article is by Kim IV (but since "one's own is more precious"...:) It differs from the standard stop loss in that the stop loss is not moved "point by point" (for example, when tracking to a distance of 30 points, at +31 the stop loss will move +1, at +32 the stop loss will move +2, etc.), but in "steps" of a specified size. For example, when the tracking distance is 40 pips and the "Step" is set to 10, when +40 is reached, the stop loss will move +10, and then until the profit reaches +50 (40 pips + step size), nothing will change (i.e. the price has a certain degree of freedom, which is actually the essence of the algorithm), and only at +50, the stop loss will move from +10 of the step size to +20, and at +60 , the stop loss will move from +10 to +20 in steps. +30 points and so on.

parameter:
ticket -
unique order number (selected before calling function OrderSelect() );
Three distance - the distance from the current price (in points) to start "tracing" (not less than MarketInfo(Symbol(),MODE_STOPLEVEL));
Three Steps - Change the "step size" (in points) of your stop loss (not less than 1).

In three steps = 1 this function does not differ from the standard trailing function. The main "feature" of the algorithm is again to provide the price with a certain "freedom of movement" - the stop loss only moves after the price "wanders, confirms". This trailing algorithm originally appeared in the aforementioned description of the "moving channel" strategy by V. Barishpolts.


4. Standard trailing - "knot".

 blank trailing_udavka( integer votes, integer trl_dist_1, integer level_1,
integer trl_dist_2, integer level_2, integer trl_dist_3)

As we all know, there is no such thing as infinite movement without rollback (ugh...). After a certain "peak" (i.e., the average of which can be determined statistically), prices often consolidate or roll back. The idea of ​​this maintenance algorithm is to reduce the tracking distance as profits increase so that it is possible to "peg" more profits when a possible reversal/consolidation zone is reached. In addition to trading the aforementioned "spikes" (which usually occur during news periods or when historical levels are broken), this feature can also be used to work within a channel by reducing the tracking distance when the opposite (relative to the open) border of the channel is reached.


For example, at the value "ticket#, 30, 50, 20, 70, 10", tracking is initially performed at a distance of 30 pips, and as soon as the price deviates 50 pips from the opening price, it starts to "tighten" the tracking - at a distance of 20 pips, if it manages to exceed 70 pips in the direction of increasing profits, it will "tighten" the tracking distance (hence the name) to 10 pips (with a high probability of causing the position to be closed very quickly).

 Blanks tracked by time ( integer tickets, integer intervals, integer three steps,
boolean trillinglos)

Track over time, regardless of the position's current results and market conditions. At set intervals (whole minutes) it will try (if possible) to move the stop loss by the specified step size. This trailing method isn't very successful on its own (at least for me, maybe it will be different for others), however, it can be useful when combined with other trailing methods or activated by specific conditions.

blank trailing atr( integer tickets, integer atr_timerange, integer atr1_period,
integer atr1_shift, integer atr2_period, integer atr2_shift,
Coefficient of double , boolean TrillingLoss)
ATR - (Average True Range) is one of the volatility indicators; the larger the value, the higher the average volatility over the specified time period (of the indicator); measured in points. In most cases, ATR tracking allows changing stops based on the ("full", "adaptive") price action type - when volatility is high (visible spikes), the price "lets go", when "standing still", the price stays "tighter". Trailing uses 2 ATRs, they should have different periods - one short period (e.g. 5) and the other long period (e.g. 20). The stop loss is always calculated using the larger of the 2 ATRs - this is done to prevent several consecutive low volatility bars (for example, before a news release) from moving the stop loss too close to the current price.

parameter:
ticket -
unique order number (selected before calling function OrderSelect() );
atr_timerange - the time range for calculating the ATR value (options - 1, 5, 15, 30, 60, 240, 1440, 10080, 43200);
atr1_period - the period of the first ATR (greater than 0; can be the same as atr2_period , but it is recommended to set it to a different value, as mentioned above);
atr1_shift - "window" shift of the first ATR, Among them, the ATR value is calculated and the number of backward bars (non-negative integer) relative to the current bar is specified;
atr2_period - the period of the second ATR (greater than 0);
atr2_shift - "window" shift for second ATR Among them, the ATR value is calculated and the number of backward bars (non-negative integer) relative to the current bar is specified;
Coefficient - The stop loss is calculated as ATR* coefficient , which is the coefficient that determines the ATR distance from the current price to set the stop loss;
Trillinlos - > Whether to move the stop loss to the "unprofitable" zone, i.e. the interval between the initial stop loss and the opening price (true - trailing, false - trailing is only activated if the new stop loss is "better" than the opening price, "profitable").

It is also a popular tracking method, unlike the standard which has "adaptability" to current market conditions (advantageous in most cases).


7. "Ratchet" Trailing (by Barishpolts).

 blank trailing ratchetB( integer votes, integer pf_level_1, integer pf_level_2,
Integer pf_level_3, integer ls_level_1,
Integer ls_level_2, integer ls_level_3,
boolean trillinglos)

A ratchet key is a key that "moves in one direction only." The name is mine, in the Barishpolts' description it is called the "second trailing strategy" (as opposed to the "first" with "standard" - further stop loss), in the Barishpolts version Golden IV - the so-called "third level" trailing. The idea: quickly move to the breakeven point and follow it step by step with small profits (after that it is recommended to use a different tracking method, such as the standard method, or my standard "step by step" or any of the above). The feasibility of this kind of tracking - "Absolutely most positions are profitable at least for a while", so the stop loss should be moved to breakeven as soon as possible. If it "closes" early but the opening signal is still present, a re-entry is possible. Generally speaking, there will be a large number of trades that close at breakeven, and there may also be some trades that make a good profit - these trades move significantly in the profitable direction after opening the trade. The author emphasizes that this tracking is not for "spreads" but to achieve a low proportion of unprofitable trades.

parameter:
ticket -
unique order number (selected before calling function OrderSelect() );
pf_level_1 - the profit level (in pips) to move the stop loss to the breakeven point;
pf_level_2 - the distance to move the stop loss from +1 to the profit level (in points) pf_level_1 the opening price in pips;
pf_level_3 - the profit level of the trailing stop (in points) pf_level_1 to pf_level_2 opening price in points (end of function operation);
ls_level_1 - when the position profit reaches +1 (i.e. at +1, the stop loss will be moved to ls_level_1 );
ls_level_2 - the distance to set the stop loss if the price initially falls below the opening price ls_level_1 and then rises (i.e. there is a loss, but starts to decrease - it is not allowed to increase again);
ls_level_3 - sets a stop loss distance of ls_level_2 if the price is initially below the opening price and then rises;
Trillinlos - > Whether to move the stop loss to the "unprofitable" zone, i.e. the interval between the initial stop loss and the opening price (true - trailing, false - trailing is only activated if the new stop loss is "better" than the opening price, "profitable").

The author of this idea recommends using the following values ​​for EURUSD: "5, 10, 25", that is, at +5 (i.e. "compensate" the spread and get 5 more profit points), the stop loss is moved to +1 (during manual trading it is recommended to "remember this number" so as not to tempt the trader), at +10 pips the stop loss is moved to +5, at +25 pips the stop loss is moved to +10 and the price "lets go" (it can be tightened by other methods). The author does not describe a similar part of the loss interval function, which was developed by his followers in discussions. There is evidence that the author (quite successfully) uses this method of trading on his investment projects, and this may be one of the factors that contributes to the very high profit margins in his trades. At the same time, it should be noted that this trailing algorithm is very specific and may not suit everyone.

8. Trailing by price channel (suggested by rebus ).

 Blank tracking by price channel ( integer e-ticket, integer iBars_n, integer i indent)

parameter:
eTicketing -
unique order number (selected before calling function OrderSelect() );
iBars_n - channel period (find the number of bars with the highest and lowest prices respectively - the upper and lower borders of the channel);
Indent - Set the indent of the stop loss from the channel borders (in points).

The results of price channel tracking are actually consistent with the results of candle shadow tracking (see above), and are somewhat similar to fractal tracking, although it differs in "concept" and "feasibility".

9. Behind the moving average.

 blank tracking MA( integer e-ticket, integer iTmFrme, integer iMAP period, integer iMA move,
integer MA method, integer iAppl price, integer move, integer i indent)
This idea is basically “half a step away” from the tracking of price channels. The function is passed the warehouse order, the required time frame, the MA offset (in points) to set the stop loss, and MA parameters (similar to those in standard iMA()). Considering the nature of moving averages, it is easy to guess that this algorithm is capable of producing a reasonably good tightening during trends, although during consolidation it can "confuse" the price and often lead to premature closing of positions. However, tracking parameters (especially the averaging method and period) can be changed appropriately to suit market conditions (e.g. to take volatility into account).

parameter:
eTicketing -
unique order number (selected before calling function OrderSelect() );
iTmFrme - chart period for calculating moving averages; allowed input options: 1 (M1), 5 (M5), 15 (M15), 30 (M30), 60 (H1), 240 (H4), 1440 (D), 10080 (W), 43200 (MN);
iMAPeriod - calculates the average period of the moving average;
iMAShift - movement of the indicator relative to the price chart;
iMA method - averaging method; allowed input options: 0 (MODE_SMA), 1 (MODE_EMA), 2 (MODE_SMMA), 3 (MODE_LWMA);
iAppl price- Applicable prices; input options: 0 (PRICE_CLOSE), 1 (PRICE_OPEN), 2 (PRICE_HIGH), 3 (PRICE_LOW), 4 (PRICE_MEDIAN), 5 (PRICE_TYPICAL), 6 (PRICE_WEIGHTED);
iShift - moves backward by the specified number of periods relative to the current bar;
iIndent - the indent (in points) from the MA value to set the stop loss.


10. "Fifty-five" follows.

 Blank trailing fifty-fifty ( integer ticket, integer iTmFrme, double d coefficient,
Boolean bTrlinloss)

The idea is as follows: when another bar closes, reduce the distance between the stop loss and the current price by dCoeff times (the initial value is 0.5, hence the name). For example, there is an open buy position with a stop loss of 40 pips. When the entry bar closes, the bid price will be 42 points higher than the opening price. If the only "profitable" (bTrlinloss==true) tracking mode is selected, then take the distance from the opening price to the current price - 42 pips, multiply by dCoeff (for example 0.5), get 21 pips, move the stop loss to +21. Assume that at the close of the next bar the profit reaches +71 pips. Then the difference between the current stop loss and the price is 71-21=50, and half of this value is 50*0.5=25, so the new stop loss must be 25 points higher than the previous one (21+25=46 points from the opening price).

When using the trailing mode described, "Profit" (bTrlinloss==true), the stop is moved only if the new stop is "better" than the opening price. If bTrlinloss is set to false, then tracking will also be performed in the loss zone (i.e. in the interval between the open price and the stop loss, by the way, this value must be defined (not equal to 0) for this element to work). That is, if the above variant is used, at the close of the next bar, the stop loss will be moved to the 0.5 distance between the stop loss and the current price, instead of the distance between the open price and the current price (with a stop loss of 40 pips and a profit of 42 pips, this distance will be equal to (40+42)/2 = 82/2 = 41 pips, and the stop loss will be set at a distance of +1 pip from the open price. At a profit of 71 The second bar of: a) 71 - 1 = 70, b) 70*0.5 = 35, c) 1 + 35 = 36 points. It can be seen that this variant will start at a greater "distance" and will lag behind the first variant. Its main function is to tighten stops during negative developments. For example, if after the first bar is closed, the profit reaches -10 pips, then bTrlinloss==true: a) find the distance from the price to the stop loss, |-40 + (-10)| = 30 pips, b) calculate half of this value - 30*0.5 = 15 pips, c) move the stop loss towards this distance with the profit: -40 + 15 = -25.

Although accounts are protected from large losses, trailing losses results in an increased number of early closures (as well as small losses).

dCoeff - the coefficient that determines the number of times to decrease the distance between the price at the moment the bar closes and the current stop loss;

bTrlinloss - Activate tracking in unprofitable areas.

11. “KillLoss” tailgating.

 Blank kill loss ( integer ticket, double d speed factor)
I came up with the idea for this maintenance in the process of developing combined types of tails, including the ones mentioned above (i.e. Barishpolts' "ratchet" tails and fractals' tails). According to this idea, it is designed to work only in the loss zone (when the position is at a loss). For example, if the entry is obviously wrong, the losses increase rapidly, and the price quickly approaches the initial stop loss, then it is recommended to limit the possible losses by moving the stop loss towards the price at a speed equal to or greater than the price. This is what the kill loss function does. Once started, it "remembers" the distance between the stop loss and the price in a global variable of the terminal, and in the future if the price is close to the stop loss point X, it moves the stop loss to point X * d speed coefficient of its coefficient. The above coefficient can be either a constant (for example, 1 - for every pip the price approaches, the stop loss will move 1 pip, or 1.5 - the stop loss will move towards the price 1.5 times faster than the price speed), or it can be a variable value that changes depending on the market conditions (for example, its volatility - "if the market is volatile and losses are increasing, cut the stop loss faster"). The kill loss function does nothing when the price rolls back towards profits (losses decrease). P.S. Keep in mind that this function uses 2 global variables of the terminal during runtime - Steve and Zepiao, the latter of which is also used in some of the trailing functions above. Be careful to change the name of a global variable in one of these functions if necessary (such as during combined or alternate use of these functions).

All the above functions are concentrated in the TrailingFuncLib.mq4 library file, which is attached to the article title. For me it is more convenient to use a library, although it is a bit slow, but you can include these functions in your program. I have also attached an example of my fractal called EA and the functions included. Someone may also be interested in EA.

August 11, 2007. For those who do "semi-automatic" trading by controlling part of the trade manually (for example, opening positions, simply because some strategies are almost impossible to algorithmize) and using scripts and MQL4 experts to control another part of the trade (for example, position maintenance and closing), I developed an EA based on each of the above-mentioned tracking functions of the library. They are in the TrailingExperts.zip file. So, now, after opening a position manually, you can run the EA with the required tracking type simply by specifying the ticket (a unique number of the position) and setting the necessary parameters. And, if necessary, you can easily change one tracking type to another as market conditions change, simply by running another expert. More detailed instructions can be found in the comments of each EA. I really hope these programs are useful to you in your work.

I started learning the MQL4 language only recently (end of March 2007). Therefore, I am happy to accept any constructive comments, tips, suggestions, ideas, etc. regarding the above features. I hope they are useful to you.

Sincerely,
Yuri Zhuban.


Attachment download

📎MyFractalsgexamplea.mq4 (8.17 KB)

📎 TrailingFuncLib.mq4 (58.4 KB)

Source: MQL5 #7108

Verification code Refresh