Top Menu

Feedburner

Right-Side Top Menu

Trailing Stop in MetaTrader 4

April 7, 2009 (Last updated on July 31, 2013)

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-2013, EarnForex.com"
#property link      "http://www.earnforex.com"
 
/*
   Kicks in when position reaches at least TrailingStop pips of profit.
*/
 
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)
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - TSTP, OrderTakeProfit(), Red))
                  Print("Error setting Buy trailing stop: ", GetLastError());
            }
         }
         else if ((OrderStopLoss() != Bid - StopLoss * PointValue) && (StopLoss != 0) && (OrderStopLoss() == 0))
            if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - StopLoss * PointValue, OrderTakeProfit(), Red))
               Print("Error setting Buy stop-loss: ", GetLastError());
      }
      else if (OrderType() == OP_SELL)
      {
         if (OrderOpenPrice() - Ask > TSTP)
         {
            if ((OrderStopLoss() > Ask + TSTP) || (OrderStopLoss() == 0))
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red))
                  Print("Error setting Sell trailing stop: ", GetLastError());
            }
         }
         else if ((OrderStopLoss() != Ask + StopLoss * PointValue) && (StopLoss != 0) && (OrderStopLoss() == 0))
            if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red))
               Print("Error setting Sell stop-loss: ", GetLastError());
      }
	}
 
   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. This version will start trailing stop-loss when position reaches profit, which is greater or equal to your given trailing stop value. You can also download a trailing stop EA that will start working when any positive profit has been reached or the one that will trail stop-loss immediately whenever current stop-loss lags behind the current price for the given trailing stop value. The latter version does not have a common stop-loss function for obvious reasons.

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.

Update 2013-02-28: Added two other versions of MT4 trailing stop. Please see the paragraph below the source code for more details. The original version has been also updated for some error reporting capability.

Update 2013-07-31: Fixed stop-loss modification error, which could potentially move the SL level backwards. Thanks to Reynald for reporting this bug.

If you have some questions, suggestions or bug reports regarding the presented trailing stop code, please feel free to share them using the form below.

152 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

    Clóvis Reply:

    hello if possible would like your help,
    I would like to make the trailing stop is activated for example 20 pips after being positive and to remain a margin of 5 pips if it returns in the opposite position, eg:

    open order to buy EURUSD 1.21600
    the order is rising and has reached the 1.2180 trailing stop starts and gets in 1.21750 stop if it will continue to rise increasing the stop of a 1 pip in the event of a downturn it gets 15pips.

    thank you in advance.

    excuse me but it was translated into English via google!

    Reply

    admin Reply:

    It is very simple. In the code that I show in the post above change:

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

    to:

    if ((Bid - OrderOpenPrice()) >= 15 * PointValue)

    and change:

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

    to:

    if ((OrderOpenPrice() - Ask) >= 15 * PointValue)

    You can substitute 15 with some input parameter name to make it variable. But do not forget to declare the input parameter in the beginning of the EA.

    Reply

    Clóvis Reply:

    how do I make this change you suggested, what name should I put, I know nothing of programming.

    “You can substitute 15 with some input parameter name to make it variable. But do not forget to declare the input parameter in the beginning of the EA.”

    Reply

    admin Reply:

    You can choose any name you want. For example, MinTrailingProfit. But don’t forget to declare it first as:

    extern int MinTrailingProfit;

    Reply

    Clóvis Reply:

    I tried to use the way you instructed but the trailing stop is varied for less, is what I need it to be fixed as above exemplifiquei when 20 pips higher than expected it hangs on the stop 15 pips cso continue to rise it rises to 01 01 pip if he goes back to at least 15 pips or as rose was increased from 01 to 01 pip, is it possible?

    Reply

    admin Reply:

    I don’t quite understand what you are trying to suggest.

  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. 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

  14. 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

    Hussain Reply:

    Ok but i want to ask here :

    MT4 gives quotes of 5 digits lets say in the example above trade at 1.00205 ok ? I have MT4 with minimum 20 points and i have noticed it counts the last digits as points meaning when the price goes up 1.00215 it is 10 points and when 1.00225 it is 20 points and when 1.00235 it is 30 points whereby the trailing stop then sits at 1.00215 . This is great for scalping but manier times i have noticed with 1 lot 1 pip up is $ 10 ok and lets follow the above example the price went up to 1.00230 which is 25 points up and 25 $ up with 1 lot correct . So technically the trailing stop should move up by 5 points now that the profit is 25 points greater then the preset value of 20 so the take profit now should sit at 1.00210 if price returned and should give me a profit of 5$ expected BUT NO THE TRAILING STOP DOESNT SIT THERE AND IT HITS THE STOP LOSS THAT I SET 10 PIPS DOWN THE HARD STOP LOSS i dont understand sometimes it does and i get profits and bag much more BUT AT CERTAIN TIMES ID DOESNT WHY IS THAT I AM STILL USING DEMO FOR INFO , please answer if anybody can add some info . Thank you .

    Reply

    admin Reply:

    It uses standard pips as input parameters. If you want it to work with fractional (5-digit) pips, just set the values divided by 10. So, it should 2 instead of 20 in your example.

    Reply

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. Ronnie K

    Thank you very much, I will try it out

    Reply

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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) &amp;&amp; (Bid - OrderOpenPrice() &gt;= TSTP))
             { TSTP = NormalizeDouble((Bid - OrderOpenPrice()) * trailing_stop_percentage / 100, Digits);
             {
                if (OrderStopLoss()  0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP))
             { TSTP = NormalizeDouble((OrderOpenPrice() - Ask) * trailing_stop_percentage / 100, Digits);
             {
                if ((OrderStopLoss() &gt; (Ask + TrailingStop * PointValue)) || (OrderStopLoss() == 0))
                {
                   OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red);
                }
             }
            } else if ((OrderStopLoss() != Ask + StopLoss * PointValue) &amp;&amp; (StopLoss != 0))
                OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red);
          }
    	}
     
     
    //----
     
    //----
       return(0);
      }
    //+------------------------------------------------------------------

    Reply

  28. 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

  29. 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) &amp;&amp; (Bid - OrderOpenPrice() &gt;= TSTP))
             { TSTP = NormalizeDouble((Bid - OrderOpenPrice()) * trailing_stop_percentage / 100, Digits);
             { if (OrderStopLoss()  0) &amp;&amp; (Bid - OrderOpenPrice() &gt;= TSTP2)) 
              { TSTP2 = NormalizeDouble((Bid - OrderOpenPrice()) * sec_trailing_stop_percentage / 100, Digits); 
              { if (OrderStopLoss()  0) &amp;&amp; (Bid - OrderOpenPrice() &gt;= TSTP3))
             { TSTP3 = NormalizeDouble((Bid - OrderOpenPrice()) * thr_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) &amp;&amp; (Bid - OrderOpenPrice() &gt;= TSTP4))
             { TSTP4 = NormalizeDouble((Bid - OrderOpenPrice()) * fourth_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) &amp;&amp;  (Bid - OrderOpenPrice() &gt;= TSTP5))
              { TSTP5 = NormalizeDouble((Bid - OrderOpenPrice()) * fifth_trailing_stop_percentage / 100, Digits);
              { if (OrderStopLoss()  0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP))
             { TSTP = NormalizeDouble((OrderOpenPrice() - Ask) * trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() &gt; (Ask + InitialTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             {OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP, OrderTakeProfit(), Red);
           }
           }
           }
     
             if ((sec_trailing_stop_percentage &gt; 0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP2))
             { TSTP2 = NormalizeDouble((OrderOpenPrice() - Ask) * sec_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() &gt; (Ask + SecTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP2, OrderTakeProfit(), Red);
           }
           }
           }
     
     
          if ((thr_trailing_stop_percentage &gt; 0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP3))
             { TSTP3 = NormalizeDouble((OrderOpenPrice() - Ask) * thr_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() &gt; (Ask + ThirdTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP3, OrderTakeProfit(), Red);
            }
            }
            }
     
        { if ((fourth_trailing_stop_percentage &gt; 0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP4))
             { TSTP4 = NormalizeDouble((OrderOpenPrice() - Ask) * fourth_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() &gt; (Ask + FourthTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP4, OrderTakeProfit(), Red);     
            }
            }
            }
            } 
         if ((fifth_trailing_stop_percentage &gt; 0) &amp;&amp; (OrderOpenPrice() - Ask &gt;= TSTP3))
             { TSTP4 = NormalizeDouble((OrderOpenPrice() - Ask) * fifth_trailing_stop_percentage / 100, Digits);
             { if ((OrderStopLoss() &gt; (Ask + FifthTrailingStop * PointValue)) || (OrderStopLoss() == 0))
             { OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TSTP5, OrderTakeProfit(), Red);
            }
     
            }
            }
     
           else if ((OrderStopLoss() != Ask + StopLoss * PointValue) &amp;&amp; (StopLoss != 0))
                OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * PointValue, OrderTakeProfit(), Red);
     }
    }
     
    //----
     
    //----
       return(0);
    }
    //+------------------------------------------------------------------

    Reply

  30. 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

  31. 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

  32. guruKrish

    BID and ASK only bring the current chart Pair price. You should use MarketInfo(pariname, MODE_BID) for each pair price.

    Reply

  33. Jasmine

    hi ..
    I think that using trailing stops is something most traders especially new traders tend to ignore although i consider it as a security tool for my account .. the truth is that many traders don’t accept to get out of the market hoping for further profits however they will leave the trades till it become negative !

    I just liked to share my opinion about trailing stops in real trading and hope the best for all

    Thanks for the author of this post .. ☺

    Reply

  34. Tom

    Am I right in thinking you can’t set 2 or more take profit levels in MT4?

    I use the bullpips method with great results and have noticed that using take profit at 1:1 and second at 2:1 reward/risk ratios is even more profitable.

    Unfortunately I have to do this manually at the moment as I can’t see how to set it up in MT4 other than open 2 separate trades. Any ideas?

    Reply

    admin Reply:

    In MT4, you’ll have to use either 2 separate trades for that or opt to use an EA that would close positions partially.

    In MT5, you can set as many TPs on a position as you wish.

    Reply

  35. Tom

    This is exactly what I was looking for. I’m still new with FOREX and MT4 so thanks for the post. It has helped a lot.

    Reply

  36. gabriel

    Sir,
    Please can trailing stop work when my computer is off.I mean after entering trades activate the trailing stop,let say i off my system.can the trailing stop be working while the system is off?

    Reply

    admin Reply:

    No, you would have to use VPS for that.

    Reply

  37. Aaron

    Thanks for this. I compiled it and added it to my custom list.
    I assume until I actually place an order I will not see anything to show the trailing stop indicator will work correctly. For example, the smiling face only appears on your chart when there is an open trade, is that correct?
    Also, when I make a trade, do I have the ability to set it as a trailing stop trade, or do I just set it as a stop loss trade and the indicator takes over from there.
    Thanks again

    Reply

    admin Reply:

    You need to attach the EA to the chart for it to work. It should be showing the smiling face all the time, otherwise it is not active.

    The EA applies trailing stop to all orders, irrespective of whether it has a preset SL or not.

    Reply

    Aaron Reply:

    Actually after I edited the stop I see it in the corner of my graph now :)

    Reply

  38. Tanoo

    Now I am pretty much cleared about the trailing stops. Thanks for this informative post.

    Reply

  39. Jerry Clasby

    The code for this trailing stop is (because of the two disadvantages) INCOMPLETE!

    Why didn’t the individual correct these flagrant deficiencies?

    Reply

    admin Reply:

    What disadvantages do you mean?

    Reply

  40. aftab

    Hi!

    I wanna ask you that when we apply this EA to the chart having already running trades with positive as negative points, lets say +96 or with some loss as -66, in that case how this EA will work.

    Reply

    admin Reply:

    It won’t do anything with a losing trade. It will apply trailing stop to the profitable one – it well set stop-loss to (Current Price – Trailing Stop) value.

    Reply

  41. lionel

    Hello!

    Enquiry: how come you are monitoring Bid for running Buy order and not Ask,
    and Ask for running Sell order and not Bid? Shouldn’t it be the other way round?

    Reply

    admin Reply:

    You are right, but Buy is closed at Bid, so if we set TrailingStop to 20 pips and expect to get at least 20 pips of profit when it is activated, we have to wait for Bid – OpenPrice to be >= 20 pips. If we would monitor Ask – OpenPrice, the resulting profit would be Spread size less than 20 pips. The same is true for Sell orders.

    Reply

  42. Demeestere

    Hello, or and how to download it? Thank you.

    Reply

    admin Reply:

    There is a download link in the post – just below the source code.

    Reply

  43. jon

    hi, to change the trailing stop value, I should change the ’5′ at the very beginning of the code to the amount of pips I want? is that all thats required for this? thanks

    Reply

    admin Reply:

    Yes, that and re-compile the file in MQL Editor.

    Reply

    Jon Reply:

    Great, thanks! this one’s handy!

    Reply

  44. sylvester jerry

    please what is the meaning of pip adjust in an EA

    Reply

    admin Reply:

    Where did you find that “pip adjust”?

    Reply

  45. sylvester jerry

    WHAT is the meaning of slippage

    Reply

    admin Reply:

    Slippage is the difference between the request order execution price and the actual order execution price. For example, you sent a trading order to buy EUR/USD at 1.3072, but it got executed at 1.3074 – that is 2 pips slippage.

    You can find more Forex terms definitions in our glossary:
    http://www.earnforex.com/forex-glossary

    Reply

  46. Saeed

    I want to write an EA so that it reopens a buying order when the price is 10 pip less than the previous closed buying order price and to reopen a selling order when the price is 10 pip more than the previous closed selling order price

    Reply

    admin Reply:

    Good for you!

    Reply

    Saeed Reply:

    I was hoping you would help me with it.

    Reply

    admin Reply:

    Then you would do better by asking me to help you with something specific. Moreover, what does it have to do with “Trailing Stop in MetaTrader 4”?

    Reply

    Saeed Reply:

    I didn’t know where esle I can put. Is there a specific thread where I can put my queries??

    Reply

    admin Reply:

    There is a whole forum: http://www.earnforex.com/forum/f13/

    Reply

  47. junaid

    bundle of thanks,,i appreciate your work and am looking forward for some other useful EA’s

    Reply

  48. Thomas

    Hello,

    I’m looking for months for the following solution and maybe you could help me with this. I want to have a trailing stop that starts with a sensitiveness of 5 when the position moves 20 pips in my direction. At the same time the stop loss should move to 15 pips past the breakeven point. I’d like to give you an example.

    I buy and go long at 1.0000; Position goes to 1.0019 => nothing happens
    Position goes to 1.0020 => Stop loss (Take profit) is moved to 1.0015;
    Position goes to 1.0021 => Stop loss is moved to 1.0016;
    Position goes to 1.0022; Stop loss is moved to 1.0017;
    Position moves to 1.0018 => Stop loss STAYS at the last high in this case 1.0017;
    Should the position go up again past 1.0022 then stop loss moves accordingly.

    The principal is the following: If position moves up, then there stop loss moves along. If it goes down there is the security of 5 pips according to the last high before we are stopped out. I hope I could explain this.

    Is there are a way to implement this in the source code given above? Would be nice if you could help me with this.

    Greetings,
    Thomas

    Reply

  49. bashar

    i know its an old thread … but i tried to combine the code to my code but i guess it would be hard for me since i dont have any experience… i would appreciate any help to add the trail stop code in this thread to my below code :

    -code striped by admin-

    Reply

    admin Reply:

    Please upload the mq4 file to some file sharing website and post your link here. There is no need to insert such large pieces of code in the comments. Thanks!

    Reply

  50. Reynald

    Hello admin, I’ve tried your EA recently, but it didn’t work if I put Stop Loss on my trades.
    It will just keep changing the stop loss all the time so they will work as no stop losses.
    but it works fine if I didn’t put any stop loss.

    Do you have any idea?
    Thank you

    Reply

    admin Reply:

    Which version did you try?

    Reply

    Reynald Reply:

    Metatrader 4

    Reply

    admin Reply:

    I mean which version of the Trailing Stop EA did you try? There are three of them in the post.

    Reply

    Reynald Reply:

    the first version (in your main post)

    Reply

    admin Reply:

    That is quite strange, because it cannot remove stop-loss from an order that already has SL on it. Are you sure that the problem is caused by this EA?

    Reply

    Reynald Reply:

    Yes, I’m sure… I’m testing it with Strategy Tester, and it cause the Stop Loss moving backwards if we’re trying to modify it manually at the start of a trade

    or maybe because of…

    double PointValue;
    for (int i = 0; i < OrdersTotal(); i++)
    {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

    I replaced variable "i" with other character because it's already defined in my EA, is that the problem?

    admin Reply:

    Now, this gets really confusing. Does it remove stop-loss or does it move it backward? Please provide full details on what is going on with a trade – what level is it open at, what SL is applied by you, what SL is applied by EA and at what time?

  51. Reynald

    Okay, it doesn’t remove it, but it does move it backward (I think remove or move backward are still related :P)
    Here, I provide you with images so you won’t confused anymore…

    http://images.snoork.com/images/1101167541_stforex.JPG

    sorry, badly edited

    Reply

    admin Reply:

    Thank you very much for this detailed explanation. I have found the bug and fixed it. Please try downloading the EA again (or copying it from the text if that is what you did) and see if the fix works for you.

    Reply

    Reynald Reply:

    You’re welcome :) and thanks for your plugin too… it’s awesome! :D

    Reply

  52. Stephen

    Thank you very much for such an awesome piece of work. I have two issue that I would greatly appreciate if you can assist me.

    1. Is it possible to launch the EA using a script. I have a script that I use to place trades at a certain entry point with respective TP and SL. Originally I wanted a code to add to this script for TSL but after testing your Trailing Stop I fell in love with it. So that’s one.

    2. Could you also kindly assist me with modifying the Trailing Stop version to work with varying Trailing Stop Loss with 3 levels TSL1, TSL2 and TSL3. The original Stop Loss that is placed with the script is variable; lets say it’s 10pips from entry position.

    TSL1 = If the market moves 20pips in favor the Trailing Stop should move to breakeven
    TSL2 = If the market moves above 30pips the Trailing Stop should trail at 10pips until it gets to 50pips
    TSL3 = If the market moves above 50pips the Trailing Stop should trail at 5pips for the rest of the trade.

    I use a five digit broker, though I’m not proficient with coding yet I’m sure I will be able to do the additional coding for the EA to work with the five digits as opposed to the norm.

    Much appreciated…

    Stephen

    Reply

    admin Reply:

    1. As far as I know, it is not possible to launch EAs from within MT4 scripts.

    2. No.

    The EA works with both 4- and 5-digit quotes. It accepts input parameters in standard pips.

    Reply

    Stephen Reply:

    Thanks, I studied the other recommendation on an earlier post and made some modifications to the code. It looks like it working but still performing more tests to verify if it’s working as expected.

    Thanks

    Reply

  53. Diji

    Hi, thanks for the EA. I have tried using the EA but it doesnt really work. I have tried both “trailing stop/ trailing stop on profit” but the EAs refuse to kick in even after profits rises. I combined your EA with a EA i used (which is based on MA crosses) but the trailing stop refuse to kick in. I did the compilation on META EDITOR and it shows “0 errors”. Though i have 2 stop losses on the new combined EA, i leave the “STPLoss” that is associated with your EA at 0, while i set the “StopLoss” of my MA crosses between 5-10.
    I even tried your EA singularly on open trades but it kick in.
    what could be wrong?
    Please kindly help

    Reply

    admin Reply:

    Are there any errors in Experts or Journal tabs of the Terminal window? What do you set TrailingStop input parameter to?

    Reply

  54. Diji

    The alert on the EA while trading keeps buzzing “Wrong stops, Retrying”.
    What am i doing wrong?

    Reply

    admin Reply:

    Sorry, but this EA does not issue such messages. Please check other attached EAs.

    Reply

  55. Diji

    Sorry, i tried your EA singularly but refused to Trail.
    If i attach your EA to a particular currency pair, will it work for other currency pairs that their trades are open? Or will it only work for that particular pair?
    Please kindly help out!

    Reply

    admin Reply:

    If attached to at least one chart, it will work on trades on all currency pairs.

    Reply

  56. Diji

    Hi, Just noticed my new combined EA does not take profit even after surpassing the TP mark. Now i really really need your help!!!

    Reply

    admin Reply:

    If TP was set on the order in MT4, then it should trigger disregarding your EA. It is applied by the broker’s server.

    Reply

  57. Diji

    well, the first issue i had with the MA cross EA was that i did not close trade after signal reversal, so i tried adding a trailing stop to augment for it. Please where can i paste the EA so that you can kindly help?

    Reply

    admin Reply:

    I don’t quite understand… What does it have to do with my Trailing Stop EA?
    Please create a separate thread on forum if you have some problems with some other EA.

    Reply

  58. Stephen

    Hi,

    If I attach the EA on separate charts with different parameters say; on seven pairs each with its own settings, will the EA apply the parameters of each chart accordingly? I haven’t been able to notice if it applied the parameters differently on all tests I have done.

    Thanks

    Reply

    admin Reply:

    Do not do that. One Trailing Stop EA attached to one chart will try to modify orders on all symbols.

    Reply

  59. Stephen

    I’m really liking this EA. All along I have been using it on its own and it worked well. I’m planning of using it along with another EA concurrently (let’s call it EA2). This EA2 will be attached to different charts.

    Since I need only to attach this Trailing Stop EA (we will call it EA1) on one chart and it applies the TSL settings on all charts with open orders.

    1. Can EA1 work with this other EA2. This EA2 has nothing to do with TSL its got a totally different function altogether.

    2. Let’s say I want to trade the following pairs, EURUSD, USDCHF, GBPUSD,USDCAD, AUDUSD and NZDUSD and I open orders of all these pairs. All these pairs would have EA2 attached with unique settings for each pair. Will EA1 work if I attached it to another pair say EURGBP without any open orders on it?

    Thank you

    Reply

    admin Reply:

    Yes, EA1 will be affecting all orders independently on the chart it is attached to. Of course, it will use the same settings (TS size) to all these orders too. If your EA2 is only opening orders (without further modifications of SL), there should be no conflict in your situation.

    Reply

  60. kolex

    Hi! thank you so much for your informative post on trailing stop, some of my question has been answered but i still have 2 more question for more clarification.
    1 after installing the EA “tsl” , i just pasted it straight to my open trade, i used the default setting just to test if i had done the right thing, i discovered that it automatically placed my stop loss at 1.35893, at opening of 1.35890 and i actually set my tp @ 1.35990 being 100 pips if i am correct. my question is that how can i set tsl parameter to always lock my profit at my set tp and possibly extend my tp
    2 lets assume that after getting a good entry signal from whatever system and i place a trade, but since i don’t know the extent at which the trend will last but i am sure it will get to my tp level, is there a software that one can use keep the trading on like a varying tp and a the same time a varying tsl to maximize profit. i hope you get my question.
    thanks in anticipation for your quick response

    Reply

    Andriy Moraru Reply:

    Sorry, but I do not get your questions.

    1. How can a trailing stop lock profit at TP? Stop-loss cannot be set to the same level as TP because TP is always at the “other side” of the entry level.

    2. Are you talking about partially closing a trade at some TP and applying trailing stop to the rest of the trade?

    Reply

  61. kcfve

    Dear Friend,
    exactly where i can add this code in my existing ea.

    Reply

    Andriy Moraru Reply:

    Adding the TS code to the existing EA is not a straightforward process. You should understand how your EA’s code is working.

    Reply

  62. Ishtiaq

    Dear Admin !
    Very helpful information is provided here . Please help me in my query.
    If i open and order at price 100.500 . if i want that Trailing stop of 20 points should be applied if price reach at 100.570 (i.e StopLoss will be selected at 100.550 and 50 points profit will be locked). Till reaching the price 100.570 the EA should not be triggered.
    Please provide me complete EA code. I will be very thankful to you.

    Reply

    Andriy Moraru Reply:

    If you read the blog post carefully you will notice that the default TS EA version does just that:
    “This version will start trailing stop-loss when position reaches profit, which is greater or equal to your given trailing stop value.”

    Reply

  63. Ishtiaq

    1. Sir should i compile the “Trailing Stop.mq4″ file and then attach “Trailing Stop.ex4″ file to my chart or i should copy “Trailing Stop.mq4″ file to \experts\ and attach it to my chart without compiling ?

    2. I am using MT4 and my broker is providing 3 and 5 digits after decimal points . What (codes) should i amend in the source code to Start “trailing Stop” of 20 points at that time when 50 points of profit is achieved?

    Reply

    Andriy Moraru Reply:

    1. How will you compile “Trailing Stop.mq4″ without copying it to \experts\ folder? That’s a necessary step.

    2. Sorry, I have misread your request. I though you were asking for a TS to activate when Profit=TS, not when Profit=SomeValue+TS. You would need to modify the code lines 38 and 52 by replacing TSTP with TSTP + (5 * PointValue).

    As for the decimal places problem, you would need to use 2 and 5 instead of 20 and 50 in your case. Because this EA uses standard pip definition, not fractional.

    Reply

  64. Ishtiaq

    Line 8 :extern double TrailingStop = 2;

    Reply

    Andriy Moraru Reply:

    No need to changed that in code. You could change that as an input parameter of the EA upon attachment.

    Reply

  65. Ishtiaq

    Sir, I am using MT4 of broker providing 3 and 5 digits after decimal point.
    To activate the Trailing Loss of 20 pips when my profit reached has reached 50 pips, i changed the codes (in Trailing Stop.mq4 after copying the file to \experts\ folder and compiled the file) as following:

    Line 8 : extern double TrailingStop = 2;
    Line 38: if (Bid – OrderOpenPrice() > TSTP + (5 * PointValue))
    Line 52 : if (OrderOpenPrice() – Ask > TSTP + (5 * PointValue))

    Now my open trade is going in 1.89$ in profit. that is my 0.01 lot is opened any my profit is 1.89 but no Stop Loss has been activated . I have attached Trailing Stop EA to the chart and Smiling face is also appearing at right upper corner of chart. Please help now

    Reply

    Andriy Moraru Reply:

    What’s the output in the Experts tab? My best guess is that 2 and 5 pips is just to close for your broker to handle (check their stop levels for the currency pair you are trading).

    Reply

  66. Ishtiaq

    Sir you were right. I changed the values 2 and 5 to 4 and 9 and EA started working. Thanks a lot. Now, please clear me following:

    1. If i attach Trailing Stop EA the chart of USDCAD, will it work for all the open trades of USDCAD?

    2. Will it work for all the Chart (that are opened at that time) i.e USDCAD, GBPUSD. NZDUSD? or will it work for that chart only to whom it is attached (in our case USDCAD)?

    3. Can i have different Trailing Stop EAs with different (Trailing Stop) settings and attach them to different charts at the same time?

    Reply

    Andriy Moraru Reply:

    1. It will all for all open trades, no matter if it is USD/CAD or some other currency pair.

    2. It will work for all open positions. It does not distinguish between currency pairs.

    3. Having two or more different TS EAs will create unpredicted behavior as they will interfere with each other. If you need to run two or more TS EAs, you either have to modify their code to exclude such interference or run them on two separate accounts.

    Reply

  67. Ishtiaq

    Dear Admin !
    My first target was that “when my profit reach 90 pips , a Trailing Stop of 40 pips is to be activated/triggered”. You guided me and i achieved this target.
    Now my second target to attach this EA on a VPS. How i will do this?

    Reply

    Andriy Moraru Reply:

    Install your broker’s platform on a VPS. Copy this EA to this VPS and attach it to a chart there.

    Reply

  68. Nick

    Hey,

    Thanks for the EA! It’s working out rather nicely, and I found a neat little work-around to get each individual open order to have different Stop Losses by maintaining a certain distance behind a rising (for buy’s) or falling (for sell’s) rate. I haven’t had much opportunity to really test it out yet and see what it can do, but I’m fairly optimistic. But anyway, thanks again!
    -Nick

    Reply

    Andriy Moraru Reply:

    You are welcome.

    Reply

Leave a Reply

required
required (will not be published)
optional

Follow EarnForex Blog on Google Plus