MQL4 - Is there a built-in code method to do trailing stop?

 

Looking through the code documentation for creating EAs on https://docs.mql4.com/, I can't seem to find a way to programmatically call trailing stop through the chart. 

Is there a method such as EX: 'ChartSetTrailingStop()'? 

MQL4 Reference
MQL4 Reference
  • docs.mql4.com
MetaQuotes Language 4 (MQL4) is a built-in language for programming trading strategies. This language is developed by MetaQuotes Ltd. based on their long experience in the creation of online trading platforms. Using this language, you can create your own Expert Advisors that make trading management automated and are perfectly suitable for...
 
miguelzn:

Looking through the code documentation for creating EAs on https://docs.mql4.com/, I can't seem to find a way to programmatically call trailing stop through the chart. 

Is there a method such as EX: 'ChartSetTrailingStop()'? 

Hello Miguel,


I don't think so.


Here is my code for trailing stop controled by ATR, maybe it can help you and others.


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool Trailing_Stop (int ticket, int timeframe, int ATRperiod, int ATRx) // returns false if order closed
{
   double   stopmini       = MarketInfo(Symbol(),MODE_STOPLEVEL); // On lit la distance stoploss/takeprofit minimum autorisé par le broker
   double   atr            = iATR(NULL,timeframe,ATRperiod,0);
   int      atr_in_points  = (int)round(atr/_Point);
   double   TrailingStop   = atr_in_points * ATRx;  // Multiplicateur d'ATR ex 1.5 pour Daily


   if (OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
      {
         if (TrailingStop > 0)
            {
               iTrailingStop = TrailingStop; // Trailing stop interne à la fonction

               if (TrailingStop < stopmini) iTrailingStop = stopmini; // si la trailing stop définit est trop petit on ajuste sur le minimum autorisé

               Trail = iTrailingStop * Point;

               double tsbuy  = NormalizeDouble(Bid-Trail,Digits);
               double tssell = NormalizeDouble(Ask+Trail,Digits);

               if (OrderType() == OP_BUY)
                  {
                     double profit = ((Bid - OrderOpenPrice()) / pips_for_prices);
                     DrawStatus("Profit en pips : "+  DoubleToStr(profit,2));
            //         if (profit > 10  &&  OrderStopLoss() < OrderOpenPrice())
            //            ticket = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Blue);
                  }
               if (OrderType() == OP_SELL)
                  {
                     double profit = ((OrderOpenPrice() - Ask) / pips_for_prices);
                     DrawStatus("Profit en pips : "+  DoubleToStr(profit ,2));
            //         if (profit > 10  &&  OrderStopLoss() > OrderOpenPrice())
            //            ticket = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Blue);
                  }

               if (OrderType() == OP_BUY  &&  Bid - OrderOpenPrice() > Trail  &&  Bid - OrderStopLoss() > Trail)
                 {
                     int iticket = OrderModify(OrderTicket(),OrderOpenPrice(),tsbuy,OrderTakeProfit(),0,Blue);
                 }

               if (OrderType() == OP_SELL  &&  OrderOpenPrice() - Ask > Trail  &&  (OrderStopLoss() - Ask > Trail  ||  OrderStopLoss() == 0))
                 {
                     int iticket = OrderModify(OrderTicket(),OrderOpenPrice(),tssell,OrderTakeProfit(),0,Blue);
                 }
              }
            return (true);
        }
   else
      {
            return (false);
      }
}
 
miguelzn:

Is there a method such as EX: 'ChartSetTrailingStop()'? 

In short, no.

  • MT4's trailing stops are implemented by the client terminal. Unlike other platforms, MT4 doesn't have server-side trailing stops which continue to be applied to the account when your trading software is not running.
  • There's no way for third-party code such as EAs to see or change the trailing stops which are being handled by the MT4 client terminal.
 
Janfi-trading:

Hello Miguel,


I don't think so.


Here is my code for trailing stop controled by ATR, maybe it can help you and others.


thank you for your code... when i copy it i get some errors like iTrailingStop and Trail and pips_for_prices


Also is there a way to set trailing stop on price close?

 
Josip Marić:

thank you for your code... when i copy it i get some errors like iTrailingStop and Trail and pips_for_prices


Also is there a way to set trailing stop on price close?

There is a "how to" program MT4 expert, with some fonction on a MT4 site, but I lose the adress.

This is the original MT4 function for trailing stop :

#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property strict

 string Text ; 
extern int Tral_Stop      = 180;                       


//+------------------------------------------------------------------+
//   https://book.mql4.com/trading/ordermodify
//------------------------------------------------------------------------------- 1 --
void trailing_stop_MT4()                                  // Special function 'start'
  {
   string Symb=Symbol();                        // Symbol
//------------------------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)          // Cycle searching in orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
        {                                       // Analysis of orders:
         int Tip=OrderType();                   // Order type
         if(OrderSymbol()!=Symb||Tip>1)continue;// The order is not "ours"
         double SL=OrderStopLoss();             // SL of the selected order
         //---------------------------------------------------------------------- 3 --
         while(true)                            // Modification cycle
           {
            double TS=Tral_Stop;                // Initial value
            int Min_Dist= (int) MarketInfo(Symb,MODE_STOPLEVEL);//Min. distance
            if (TS < Min_Dist)    TS=Min_Dist;                    
            //------------------------------------------------------------------- 4 --
            bool Modify=false;                  // Not to be modified
            switch(Tip)                         // By order type
              {
               case 0 :                         // Order Buy
                  if (NormalizeDouble(SL,Digits)< // If it is lower than we want
                     NormalizeDouble(Bid-TS*Point,Digits))
                    {
                     SL=Bid-TS*Point;           // then modify it
                      Text="Buy ";        // Text for Buy 
                     Modify=true;               // To be modified
                    }
                  break;                        // Exit 'switch'
               case 1 :                         // Order Sell
                  if (NormalizeDouble(SL,Digits)> // If it is higher than we want
                     NormalizeDouble(Ask+TS*Point,Digits)
                     || NormalizeDouble(SL,Digits)==0)//or equal to zero
                    {
                     SL=Ask+TS*Point;           // then modify it
                     Text="Sell ";              // Text for Sell 
                     Modify=true;               // To be modified
                    }
              }                                 // End of 'switch'
            if (Modify==false)                  // If it is not modified
               break;                           // Exit 'while'
            //------------------------------------------------------------------- 5 --
            double TP    =OrderTakeProfit();    // TP of the selected order
            double Price =OrderOpenPrice();     // Price of the selected order
            int    Ticket=OrderTicket();        // Ticket of the selected order
 
            Alert ("Modification ",Text,Ticket,". Awaiting response..");
            bool Ans=OrderModify(Ticket,Price,SL,TP,0);//Modify it!
            //------------------------------------------------------------------- 6 --
            if (Ans==true)                      // Got it! :)
              {
               Alert ("Order ",Text,Ticket," is modified:)");
               break;                           // From modification cycle.
              }
            //------------------------------------------------------------------- 7 --
            int Error=GetLastError();           // Failed :(
            switch(Error)                       // Overcomable errors
              {
               case 130:Alert("Wrong stops. Retrying.");
                  RefreshRates();               // Update data
                  continue;                     // At the next iteration
               case 136:Alert("No prices. Waiting for a new tick..");
                  while(RefreshRates()==false)  // To the new tick
                     Sleep(1);                  // Cycle delay
                  continue;                     // At the next iteration
               case 146:Alert("Trading subsystem is busy. Retrying ");
                  Sleep(500);                   // Simple solution
                  RefreshRates();               // Update data
                  continue;                     // At the next iteration
                  // Critical errors
               case 2 : Alert("Common error.");
                  break;                        // Exit 'switch'
               case 5 : Alert("Old version of the client terminal.");
                  break;                        // Exit 'switch'
               case 64: Alert("Account is blocked.");
                  break;                        // Exit 'switch'
               case 133:Alert("Trading is prohibited");
                  break;                        // Exit 'switch'
               default: Alert("Occurred error ",Error);//Other errors
              }
            break;                              // From modification cycle
           }                                    // End of modification cycle
         //---------------------------------------------------------------------- 8 --
        }                                       // End of order analysis
     }                                          // End of order search
//------------------------------------------------------------------------------- 9 --
   return;                                      // Exit start()
  }
//----------------------------------------------------------------
Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
  • www.mql5.com
Predefined Macro Substitutions - Named Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Reason: