Top Menu

Feedburner

Right-Side Top Menu

Forex Blog
My Forex experience and some Forex related information that might be useful to other traders

Trailing Stop in MetaTrader 4

April 7th, 2009

Trailing stop allows you to automatically protect the profits with your positions. It adjusts itself according to the current market rate and the amount of pips you give it to trail behind. Trailing stop is a great tool for the conservative and long term traders as it easily creates protective «airbag» for the trades. There are two basic ways to set the trailing stop in your MetaTrader 4 platform — use the built-in tool and attach a special EA that will apply a single trailing stop to all orders. But before going into describing these ways I’d like to tell you how the correct trailing stop should work:

  1. It should go into the action only when the position is in profit (or at a break even point).
  2. It should apply itself only when the difference between the current stop-loss and the current market price is greater than the trailing stop value.
  3. Trailing stop should never «decrease» the stop-loss level.
  4. If used without the initial stop-loss, trailing stop doesn’t protect your position from the excess losses; it only provides a good profit-following tool.

Here are the details on these two ways:

The most easy and convenient way to set the trailing stop-loss is to click with the right mouse button on the order in the Terminal window and select the Trailing Stop submenu. There you’ll be able to either choose some of the preset amount of pips or enter a custom number:

Trailing Stop Order

Trailing Stop Select

This way of setting your trailing stop-loss is very convenient but it has two important disadvantages. The first con is that it doesn’t allow trailing stop lower than 15 pips. That’s probably not a problem for long-term traders, but it’s a great trouble for scalpers and short-term traders. And the second disadvantage of this method is that it doesn’t work properly with the brokers that provide extended quotes (5 and 3 digits after the dot instead of 4 and 2 digits). Trailing stop confuses the pips in this case and acts incorrectly.

The second method is to add a special expert advisor to some chart in your MetaTrader 4 platform and it will follow all open orders trying to apply the trailing stop value you give it in the input parameter. This is a very simple expert advisor that doesn’t load up your system resources and can be turned on and off anytime. Here is its code:

#property copyright "Copyright © 2009, EarnForex.com"
#property link      "http://www.earnforex.com"
 
extern double TrailingStop = 5;
 
// Set it to some value above 0 to activate stop-loss
extern double StopLoss = 0; 
 
int init()
{
   return(0);
}
 
int deinit()
{
   return(0);
}
 
int start()
{
  double PointValue;
  for (int i = 0; i < OrdersTotal(); i++) 
  {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      //Calculate the point value in case there are extra digits in the quotes
      if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
      else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
      //Normalize trailing stop value to the point value
      double TSTP = TrailingStop * PointValue;
 
      if (OrderType() == OP_BUY)
      {
         if ((Bid - OrderOpenPrice()) > TSTP)
         {
            if (OrderStopLoss() < (Bid - TSTP))
            {
               OrderModify(OrderTicket(), OrderOpenPrice(), Bid - TSTP, OrderTakeProfit(), Red);
            }
         }
         else if ((OrderStopLoss() != Bid - StopLoss * PointValue) && (StopLoss != 0))
            OrderModify(OrderTicket(), OrderOpenPrice(), Bid - StopLoss * PointValue, OrderTakeProfit(), Red);
      }
      else if (OrderType() == OP_SELL)
      {
         if ((OrderOpenPrice() - Ask) > TrailingStop * PointValue)
         {
            if ((OrderStopLoss() > (Ask + TrailingStop * PointValue)) || (OrderStopLoss() == 0))
            {
               OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red);
            }
         }
         else if ((OrderStopLoss() != Ask + StopLoss * PointValue) && (StopLoss != 0))
            OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red);
      }
	}
 
   return(0);
}

As you see, the code is really simple. You can also download this trailing stop EA and use it freely with your orders.

While, it lacks the disadvantages of the first MetaTrader trailing stop method, unfortunately, it also has two of its own important disadvantages. First, it works for all currently open orders. So, if you want attach it to only one order and leave another one without a trailing stop this method is not for you (but, of course, you can alter this EA to work with some specific orders). Second, it utilizes the same trailing stop value for all orders, you can’t set 10 pips trailing stop for one position and 50 trailing stop for another one. In case you want to use different stop-loss values for different orders you’ll have to heavily alter the code of this MT4 expert advisor.

Update: Added stop-loss option, which might be useful if you want to complement some expert advisor that doesn’t set stop-losses on its positions.


63 Responses to “Trailing Stop in MetaTrader 4”

  1. Saeid naghizad

    hi dear
    how to use your trailling stop?
    please send me more guidliine
    thanks a lot

    Reply

    Andrei Reply:

    Doesn’t this article explain exactly what you ask?

    Reply

    Alex Reply:

    This is exactly the same problem what I have too..
    How to use this trailing stop…?
    Where can I place this code?
    Should it be in a single text file?
    Where do I have to place the file?
    What filetype should it be? I am sure if it is a .txt file, it will not work.

    Alex

    Reply

    Andrei Reply:

    This code should be inserted into .mq4 file and compiled with MQL Editor and then attached to the chart where you trade. But if you don’t know that then this code will probably be of no use to you since it requires some modifications to work properly with your orders.
    In your case I’d recommend sticking to MetaTrader’s built-in trailing stop solution.

    Reply

    razuki Reply:

    tell me how to use tsl,stop lose at 50pip or 100pip…or…..

    Reply

  2. Anton Peters

    Great info you got here. It’s really been helpful. Thanks!

    Reply

  3. Esemayon

    Thank you so much. I am beginning to get confidence with the use of the indicators.

    Once again, thanks.

    Reply

    Andrei Reply:

    No problem. If you have any problems with trailing stop, just ask.

    Reply

  4. Zem

    how do i edit the EA to the amount of pips i want my trailing stop to be?

    Reply

    Andrei Reply:

    If your EA supports trailing stop, it’s usually configurable via the input parameters. If it doesn’t support trailing stop, you’ll have to either modify the EA’s code to add such support (which is quite difficult, especially if you don’t know how to code in MQL) or to manually set the trailing stop on the positions opened by this EA.

    Reply

  5. Brian

    Hey! Thank you so much for this code. I was wondering, if I wanted to take this trailing stop and make it a part of one of my robots, could you tell me which part of the code I need, and where to paste it in my robot’s code?

    Reply

    Andrei Reply:

    Everything in the start() function except “return(0);” line. Paste it anywhere in your EA’s start() function. But if you couldn’t figure that on your own you’ll probably have some problems with that.

    Reply

  6. Forex Links for the Weekend | Forex Crunch

    [...] Andrei explains how to set a trailing stop in MetaTrader 4. [...]

  7. Adewale

    I am quite comfortable with the Trailing Stops article.

    Thanks a lot.

    But where and I do I place the code for the Trailing Stops.
    Will appreciate your reply.

    Reply

    admin Reply:

    In your EA, but if you aren’t a coder you don’t need it.

    Reply

  8. daveM

    This is great…..!!

    Would it be hard to do the same for stoploss and take profit.

    I had not thought of a separate EA for Trailing Stop until I read your post….. and now I am wondering it could also be applied to the other two… ie would Metatrader allow same.

    Thanks for your great resources in your site…….!

    daveM

    Reply

  9. Sarath

    Thank you very much for your kind service. Wish you all to be success…..!

    Reply

  10. Rick

    Thanks for the nice work around. I downloaded, edited and installed correctly. However, when I try to use the trailing stop indicator it did not show up in my chart. How do I know if it’s working?

    Reply

    admin Reply:

    It should expert advisor, not indicator. If you attach it as an expert advisor you will see its name appearing in the top-right corner of the chart with either “X” or a “smiling face” symbol. Enable EAs to turn it on (it should show a “smiling face”).

    Reply

    Rick Reply:

    Thank you. This EA works great. My question, The stop does not exist until the position is at least at breakeven, is this correct? In any event, I really like your trailing stop EA.
    If you have a PayPal account I will send you five bucks as a token of my appreciation.

    Reply

    admin Reply:

    Yes, the stop-loss isn’t added until that. You can add stop manually if you want it before the breakeven.

    Thanks, but your appreciation is enough for me :). Just telling your friends about my site would be great.

    Reply

  11. Rick

    If I add a stop manually, will it go away when the trailing stop EA kicks in?
    I will tell my friends about your site.

    Reply

    admin Reply:

    Yes, the trailing stop will change it.

    Reply

  12. Alex

    My broker told me that 15 points actually is 1.5 pips e.g. 10points= 1pip.

    Reply

    admin Reply:

    Yes, some brokers use fractional pips, where 1 fractional pip = 0.1 normal pip.

    Reply

  13. What is a trailing stop?

    [...] http://www.earnforex.com/blog/2009/04/trailing-stop-in-metatrader-4 Posted in Articles [...]

  14. Giorgi

    Hello, I can not make my trailing stop EA work, although I installed and lunched it correctly, there are no any errors in MT4 experts or journal. I am testing various of values in property’s input now. If you have any other suggestions, tell me please.

    Reply

    admin Reply:

    Do you have any open positions?

    Reply

    Giorgi Reply:

    No, I don’t have opened positions now. And why are you interested? Do you have any suggestions?

    Reply

    admin Reply:

    Then what do you expect from this EA? It only applies a trailing stop to the currently open positions, it won’t open them for you…

    Reply

    Giorgi Reply:

    I know how EA works, when I told you that I can not make it work, I was meaning that I can not make it work on opened positions…. I am opening and closing many positions, the trailing stop EA is turned on, but it doesn’t apply any trailing stops.
    Thank you for answers, I estimate your effort but I feel that you shall not be able to help me..

    Reply

    admin Reply:

    If the EA is really working (the smiling face is displayed in the top-right corner of the chart) and the currently open positions qualify for stop-loss change and EA does nothing – then I really can’t help you, sorry…

    Reply

  15. Pooler

    Hi,

    I applied your trailing stop ea. I see its default setting is 5.0. Does that mean its set at 5 pips? Does the ea only kick in when the break even is reached? i.e If I open a long trade at 1.0020 with my stop loss at 1.0000–will the ea only kick when the trade hits 1.0040? And then if the trade turns down to 1.0035 will the trade then close with a profit of 15 pips (with the default setting of 5.0)?

    What I’m looking for is a trailing stop ea that with the above scenario will move the stop loss up by 1 pip to 1.001 when the trade moves up by 1 pip to 1.0041 and so on–so if the trade turns down then I’ll make one pip.

    Why I’m asking is because too many of my trades turn before they reach break even (say at 1.0032) then I don’t make any profit and get kicked out at 1.000 at -20 pips without the trailing stop ever coming into play. I want the ea to lock in any profit as soon as the trade moves up.

    Could you tell me where I could find something like this?

    Much obliged

    Reply

    admin Reply:

    The listed trailing stop EA comes to play only when the position has at least TrailingStop pips of profit. If you open a trade at 1.0020 with TrailingStop = 5, it will move your stop to 1.0021 (1 pip of profit), once the price reaches 1.0026.

    Reply

  16. GrahamB

    Thanks for that code, I will try it out.

    IBFX have a realy neat adjustable EA that allows you to set a variety of fixed Stop Losses as the trade progresses into profit. For example you might set it to +1 PIP when the trade is 8 PIPS into profit, then increase the stop to 10 PIPs when it is 20 PIPS up. There are 4 stages available, and totally adjustable for each Trade (based on the ID number of the trade.)

    The only problem I have found is that it will not work on any MT4 platform except IBFX! And that is a bit restrictive if you want to try other MT4 brokers for various reasons.

    Is there anyone with a similar but ‘open’ EA?

    Reply

    admin Reply:

    Do they provide .mq4 file of the EA or just .ex4? In the second case, it won’t be possible to modify it to work with other brokers. But it’s probably not that difficult to code such EA. Can you describe its algorithm in details?

    Reply

  17. Ronnie K

    Thank you very much for the useful information and the timely responses to peoples’ questions.

    I had wanted to ask, is there a way of using this script to loosen/tighten trailing stops? Like for example once x pips have been reached in favour, increasing the amount that the stop trails by, and subsequently once y pips have been reached in favour, decreasing the amount that the stop trails by back to the original amount.

    Do you know of any way or of any EAs that i can use to achieve this?

    Thanks for your time

    Reply

    admin Reply:

    So, you basically need a varying trailing stop, right? By what rules should it vary? Can you offer an example?

    Reply

  18. Ronnie K

    Hi,

    Essentially yes I am looking for a trailing stop that I can vary the trailing distance once a specified amount of points are reached, and also want it to trail point for point (frequency of 1).

    I am specifically talking about Gold Futures (GCM1) as the underlying instrument and I would like to achieve the following:

    1. Entry price = X with hard stop loss order 200 points behind entry,
    and set Trailing Stop of 100 points to newly opened position.

    2. Once 200 points of profit reached, loosen Trailing Stop to 200 points (meaning BreakEven if it is triggered)

    3. Once 300 points of profit reached, loosen Trailing Stop to 300 points.

    4. Once 700 points of profit reached, tighten Trailing Stop back to 100 points and leave as it.

    Any help with this is greatly appreciated, thanks.

    Reply

    admin Reply:

    But there will be a problem with steps 2 & 3:

    Before reaching 200 points of profit you’ll have 100 points TSL, which will continue setting SL up after break even. When you’ll have 199 points of profit, it will set SL to BE + 99. But then, when you have 200 points of profit it will have to set back the SL back to BE. Isn’t that strange? The same will happen with step 3. At step 4, your SL will jump up steeply.

    Reply

  19. Ronnie K

    Yes you are correct, this is the setup that I desire.

    It is my intention to have a 300 point TSL ultimately, but in smaller increments allowing me to break even at any given point until this 300 point TSL is achieved.

    Once the 100 point TSL is triggered I want to maintain breakeven status the entire time as each subsequent increment of increasing the trailing distance is achieved, which is why I want to allow

    I want to allow the profit to actually reach 200 points BEFORE setting the 2nd TSL to 200 points, rather than setting it to 200 points once I have reached only 100 points of profit, which would actually result in a -100 point position (loss) if the TSL is triggered.

    I hope this is clear, it may sound strange however was well thought through; essentially I want to be able to subsequently increase the trailing distance as certain profit levels are reached; can you please provide assistance with respect to script(s) or an EA for MT4.

    Thanks

    Reply

  20. Ronnie K

    The nature of Gold Futures is different from that of Forex Currency pairs which is why initially the setup may sound untraditional

    Reply

  21. admin

    Add the following lines just below “extern double TrailingStop = 5;”:

    extern int TS2 = 200;
    extern int TS2profit = 200;
     
    extern int TS3 = 300;
    extern int TS3profit = 300;
     
    extern int TS4 = 100;
    extern int TS4profit = 700;

    Add the following lines just before “if (OrderType() == OP_BUY)”:

    if ((OrderType() == OP_BUY) && (Bid - OrderOpenPrice() >= TS4profit * PointValue) 
    || ((OrderType() == OP_SELL) && (OrderOpenPrice() - Ask > TS4profit * PointValue)))
       TSTP =  TS4 * PointValue;
    else if ((OrderType() == OP_BUY) && (Bid - OrderOpenPrice() >= TS3profit * PointValue) 
    || ((OrderType() == OP_SELL) && (OrderOpenPrice() - Ask > TS3profit * PointValue)))
       TSTP =  TS3 * PointValue;
    else if ((OrderType() == OP_BUY) && (Bid - OrderOpenPrice() >= TS2profit * PointValue) 
    || ((OrderType() == OP_SELL) && (OrderOpenPrice() - Ask > TS2profit * PointValue)))
       TSTP =  TS2 * PointValue;

    As you can see it’s quite easy to modify it to add more levels of trailing stop-loss if you need it.

    Reply

  22. Ronnie K

    Thank you very much, I will try it out

    Reply

  23. Ronnie K

    .

    Ok, so I have tried out this EA multiple times over the last couple of weeks at different price points using both buy and sell orders, and it isn’t working correctly however I still believe it was well coded and you are extremely knowledgeable as a programmer.

    The problem that I have is that even with this code, the trailing stop kicks in once I am only 5 points/pips in profit instead of the 100/200/300 point setup I would like as discussed above.

    Is it possible that this is due to the OrderTakeProfit() part of the function in OrderModify? It looks like a small, simple fix however I am unable to figure it out.

    Some assistance would be greatly appreciated

    Thanks again

    Reply

    admin Reply:

    1. Don’t insert such huge pieces of code into comments. Share your file on some hosting and just post the link here next time.
    2. From what you’ve posted, it looks like you didn’t follow my instructions to insert the additional code for your trailing stop loss levels. Please download the clean version again and insert the pieces of code as described in my previous comment.

    Reply

  24. chris

    I disagree that the trail should only activate when the position is in a profit. Don’t we also want to limit our loss? The point of a trailing stop?

    Reply

    admin Reply:

    Yeah, you are right, the classical trailing stop should be working from the start. I don’t want to modify the EA that’s in the post, but you can easily change it to work even without profit. Just remove the following conditions:

    if ((Bid - OrderOpenPrice()) > TSTP)
    if ((OrderOpenPrice() - Ask) > TrailingStop * PointValue)

    Reply

  25. ola

    Hello,
    please send the trailing stop that i can set to minimum of 3 pips after breaking even and can also work with ( 2nad 4 , also work with 3 and 5 after the decimal point )
    to my e-mail box
    and please explain how i will install it and use it. please i am waiting seriously and where i can place it for usage.
    thanks

    Reply

    admin Reply:

    Sorry, but this post isn’t for EA coding requests. You can try asking on our Forex forum:
    http://www.earnforex.com/forum/

    Reply

  26. Charles

    Hi, thanks for this information. How would you modify the code to be a percentage of the profit?
    extern double trailing_stop_percentage = 40 //—–40%
    and also a starting pips amount – say 10 pips in profit.

    and then in the start function could you do:
    something along the lines of
    stop loss = (current price -order open price) * trailing stop percentage.

    Thanks

    Reply

    admin Reply:

    You’ve almost got it right:

    1. Declare the input parameter as you’ve wrote.
    2. Find these lines:

             if ((Bid - OrderOpenPrice()) > TSTP)
             {

    Replace with these:

             if ((trailing_stop_percentage > 0) && (Bid - OrderOpenPrice() >= TSTP))
             {
                TSTP = NormalizeDouble((Bid - OrderOpenPrice()) * trailing_stop_percentage / 100, Digits);

    3. Find these lines:

             if ((OrderOpenPrice() - Ask) > TrailingStop * PointValue)
             {

    Replace with these:

             if ((trailing_stop_percentage > 0) && (OrderOpenPrice() - Ask >= TSTP))
             {
                TSTP = NormalizeDouble((OrderOpenPrice() - Ask) * trailing_stop_percentage / 100, Digits);

    This way, you’ll be able to set percentage stop loss in your new input parameter, while the old TrailingStop input parameter is used to set the minimum value in pips for profit to use the percentage trailing stop. In your example, you’d have to set it to 10.

    Reply

  27. Charles

    Thanks for this. I tried so long to try and implement something like this in my EA. I was getting stuck on the (Bid – OrderOpenPrice() >= TSTP)) components. I have been learning coding from existing EAs and the order functions are alot difficult for me than bools and indicators.
    Cheers

    Reply

  28. Charles

    This is the trailing stop % EA I got working.

    extern double TrailingStop = 8;	
    extern double trailing_stop_percentage = 20;
    // Set it to some value above 0 to activate stop-loss	
    extern double StopLoss = 0; 	
     
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {double PointValue;
      for (int i = 0; i  0) && (Bid - OrderOpenPrice() >= TSTP))
             { TSTP = NormalizeDouble((Bid - OrderOpenPrice()) * trailing_stop_percentage / 100, Digits);
             {
                if (OrderStopLoss()  0) && (OrderOpenPrice() - Ask >= TSTP))
             { TSTP = NormalizeDouble((OrderOpenPrice() - Ask) * trailing_stop_percentage / 100, Digits);
             {
                if ((OrderStopLoss() > (Ask + TrailingStop * PointValue)) || (OrderStopLoss() == 0))
                {
                   OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red);
                }
             }
            } else if ((OrderStopLoss() != Ask + StopLoss * PointValue) && (StopLoss != 0))
                OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red);
          }
    	}
     
     
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------

    Reply

  29. Charles

    I’m going to try and program a percentage trailing stop with different trail stop levels.
    Eg – 20% @ 10 pips
    40% @ 30 pips
    50% @ 60 pips

    etc

    Reply

  30. Charles

    I prepared an EA on the idea I had above and based on the information you gave to ronnie k regarding different trailing stop levels. I believe this code works however it does give some funny information when its calculating the stop loss. the stop loss appears to be the same as the other currency pairs at times. However eventually it settles on the correct stop loss. The other thing is that if there is a starting stop loss then the trailing stop would calculate from this stop loss (eg 40 pips as below) rather than the price at the initial trade. I am not sure how to stop this. it would be good if you could verify the code as the stop loss seems to move backwards with the price at times as well.

    //+------------------------------------------------------------------+
    //|                                                    Blueprint.mq4 |
    //|                                                 |
    //+------------------------------------------------------------------+
    extern double InitialTrailingStop = 10;	
    extern double trailing_stop_percentage = 20;
    extern double SecTrailingStop = 20;
    extern double sec_trailing_stop_percentage = 40;
    extern double ThirdTrailingStop = 30;
    extern double thr_trailing_stop_percentage = 50;
    extern double FourthTrailingStop = 40;
    extern double fourth_trailing_stop_percentage = 60;
    extern double FifthTrailingStop = 60;
    extern double fifth_trailing_stop_percentage = 70;
     
    // Set it to some value above 0 to activate stop-loss	
    extern double StopLoss = 40; 	
     
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {double PointValue;
      for (int i = 0; i  0) && (Bid - OrderOpenPrice() >= TSTP))
             { TSTP = NormalizeDouble((Bid - OrderOpenPrice()) * trailing_stop_percentage / 100, Digits);
             { if (OrderStopLoss()  0) && (Bid - OrderOpenPrice() >= TSTP2)) 
              { TSTP2 = NormalizeDouble((Bid - OrderOpenPrice()) * sec_trailing_stop_percentage / 100, Digits); 
              { if (OrderStopLoss()  0) && (Bid - OrderOpenPrice() >= TSTP3))
             { TSTP3 = NormalizeDouble((Bid - OrderOpenPrice()) * thr_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) && (Bid - OrderOpenPrice() >= TSTP4))
             { TSTP4 = NormalizeDouble((Bid - OrderOpenPrice()) * fourth_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) &&  (Bid - OrderOpenPrice() >= TSTP5))
              { TSTP5 = NormalizeDouble((Bid - OrderOpenPrice()) * fifth_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) && (OrderOpenPrice() - Ask >= TSTP))
             { TSTP = NormalizeDouble((OrderOpenPrice() - Ask) * trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() > (Ask + InitialTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             {OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red);
           }
           }
           }
     
             if ((sec_trailing_stop_percentage > 0) && (OrderOpenPrice() - Ask >= TSTP2))
             { TSTP2 = NormalizeDouble((OrderOpenPrice() - Ask) * sec_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() > (Ask + SecTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP2, OrderTakeProfit(), Red);
           }
           }
           }
     
     
          if ((thr_trailing_stop_percentage > 0) && (OrderOpenPrice() - Ask >= TSTP3))
             { TSTP3 = NormalizeDouble((OrderOpenPrice() - Ask) * thr_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() > (Ask + ThirdTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP3, OrderTakeProfit(), Red);
            }
            }
            }
     
        { if ((fourth_trailing_stop_percentage > 0) && (OrderOpenPrice() - Ask >= TSTP4))
             { TSTP4 = NormalizeDouble((OrderOpenPrice() - Ask) * fourth_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() > (Ask + FourthTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP4, OrderTakeProfit(), Red);     
            }
            }
            }
            } 
         if ((fifth_trailing_stop_percentage > 0) && (OrderOpenPrice() - Ask >= TSTP3))
             { TSTP4 = NormalizeDouble((OrderOpenPrice() - Ask) * fifth_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() > (Ask + FifthTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP5, OrderTakeProfit(), Red);
            }
     
            }
            }
     
           else if ((OrderStopLoss() != Ask + StopLoss * PointValue) && (StopLoss != 0))
                OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red);
     }
    }
     
    //----
     
    //----
       return(0);
    }
    //+------------------------------------------------------------------

    Reply

  31. Charles

    Hi – I think the logic in the above post is right. The only problem is that the trailing stop will move backwards if price moves backwards. How can I stop the price moving backwards? I am trying a few variations with no luck. I won’t post any more code as it clutters the thread however I can send the EA when its finally working right to you to post on your site.

    Reply

    Charles Reply:

    I meant how can i stop the trailing stop from moving backwards…

    Reply

    admin Reply:

    To stop the trailing stop from moving backwards with the price, you have to check if the stop-loss you are trying to apply is higher (lower for short positions) than the existing one, and call OrderModify() only if it is.

    To prevent cluttering the post with the code, you can either upload your EA to some file sharing site (like DropBox) and just post the links here, or switch to our EA forum and attach the .mq4 files to your posts directly.

    Reply

  32. Rick

    Does this always keep the SL to the value I set StopLoss to when moving in the profit direction all the time? I have this implemented and it doesn’t look like it is. So if I set the S/L to 10 right when this script starts it does set 10 pips away from current price. But it doesn’t seem to be updating itself as the price moves in the profit direction. I’m looking for something that keep the S/L 10 pips at all times but only when moving in the profit direction. Am I missing something?

    Reply

    Rick Reply:

    Note that I put your code in my own script that does an infinite loop in the start(). So not sure if something needs to be refreshed or something?

    Reply

    admin Reply:

    I really don’t know if running an infinite loop inside start() function is a good idea.

    Reply

    admin Reply:

    The input parameter “StopLoss” is used to set a fixed stop-loss only once. You should use the input parameter “TrailingStop” if you want it to trail your profit.

    Reply

Leave a Reply

required
required (will not be published)
optional

Subscribe to Monthly Forex Newsletter