Adding trailingstop to my EA

 

Hello everyone, I need help with adding a trailing stop to my EA. I'm looking for assistance in identifying the problem and fixing my code👇🏼. Your support would be greatly appreciated. Thank you!

double trailing_distance = 50.0; // Trailing stop distance in pointsif(PositionSelect(_Symbol) == false)
   {
      if(StdDevVal>StdDevAVGVal&& Ask > MaValine && MaValine > MAValue && MAValue > MAAvalue)
      {
         double price = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
         double buy_tp = price + 150*_Point;
         posTicket = trade.Buy(0.1, _Symbol, price, price - 150*_Point, buy_tp);
      }

      if(StdDevVal > StdDevAVGVal && Bid < MaValine && MaValine < MAValue && MAValue < MAAvalue)
      {
         double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
         double sell_tp = price - 150*_Point;
         posTicket = trade.Sell(0.1, _Symbol, price, price + 150*_Point, sell_tp);
      }
   }
   else // If position is already open
   {
      double new_stoploss = 0.0;
      
      if (trade.PositionType(_Symbol) == POSITION_TYPE_BUY)
      {
         // Calculate the new stop loss level based on trailing_distance
         new_stoploss = Ask - trailing_distance * _Point;
      }
      else if (trade.PositionType(_Symbol) == POSITION_TYPE_SELL)
      {
         // Calculate the new stop loss level based on trailing_distance
         new_stoploss = Bid + trailing_distance * _Point;
      }

      // Modify the order with the new stop loss level
      trade.OrderModify(posTicket, trade.OrderOpenPrice(), new_stoploss, 0, 0, CLR_NONE);
   }

I would really appreciate the help🙏🏼.

 
Your topic has been moved to the section: Expert Advisors and Automated Trading — In the future, please consider which section is most appropriate for your query.
MQL5 forum: Expert Advisors and Automated Trading
MQL5 forum: Expert Advisors and Automated Trading
  • www.mql5.com
How to create an Expert Advisor (a trading robot) for Forex trading
 
      if (trade.PositionType(_Symbol) == POSITION_TYPE_BUY){
         new_stoploss = Ask - trailing_distance * _Point;

You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

  1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

  2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
              MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

  3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

    Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
    My GBPJPY shows average spread = 26 points, average maximum spread = 134.
    My EURCHF shows average spread = 18 points, average maximum spread = 106.
    (your broker will be similar).
              Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

 
David Udoh:

Hello everyone, I need help with adding a trailing stop to my EA. I'm looking for assistance in identifying the problem and fixing my code👇🏼. Your support would be greatly appreciated. Thank you!

I would really appreciate the help🙏🏼.

I have an EA using the trailing stop function, would you like to see how its written?

Your question just got me to advice myself on a breakeven function i was working on. I would just replace it with a trailing stop for now.

 
double trailing_distance = 50.0; // Trailing stop distance in pointsif(PositionSelect(_Symbol) == false)
   {
      if(StdDevVal>StdDevAVGVal&& Ask > MaValine && MaValine > MAValue && MAValue > MAAvalue)
      ⋮
   }
   else // If position is already open
   {
There is no else because there is no if. Do not post code that will not compile.
 
William Roeder #:
There is no else because there is no if. Do not post code that will not compile.

what did you mean?

Did you mean to say there is nothing like "else if"

 
Henry Asaba Achankeng #:

I have an EA using the trailing stop function, would you like to see how its written?

Your question just got me to advice myself on a breakeven function i was working on. I would just replace it with a trailing stop for now.

Yes I would love to, thank you.

 
David Udoh #:

Yes I would love to, thank you.

I have it in two pieces of code, the simple one and the complicated one. The first one is simple, just create and input then use the simple logic. The second one is complex and needs so much modification within the entire code, I recommend the first one.


 {
      ulong ticket=PositionGetTicket(posIndex);
      if(PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_MAGIC)==MagicNumber) 
      {
     if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         if(TrailingStop>0)  
              {                 
               if(SymbolInfoDouble(_Symbol,SYMBOL_BID)-PositionGetDouble(POSITION_PRICE_OPEN)>MyPoint*TrailingStop)
                 {
                  if(PositionGetDouble(POSITION_SL)<SymbolInfoDouble(_Symbol,SYMBOL_BID)-MyPoint*TrailingStop)
                    {
                    trade.PositionModify(ticket,SymbolInfoDouble(_Symbol,SYMBOL_BID)-MyPoint*TrailingStop,PositionGetDouble(POSITION_TP));
                     return;
                    }
                 }
              }
        }
      
       if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
          if(TrailingStop>0)  
              {                 
               if(PositionGetDouble(POSITION_PRICE_OPEN)-SymbolInfoDouble(_Symbol,SYMBOL_ASK)>MyPoint*TrailingStop)
                 {
                  if(PositionGetDouble(POSITION_SL)>SymbolInfoDouble(_Symbol,SYMBOL_ASK)+MyPoint*TrailingStop)
                    {
                    trade.PositionModify(ticket,SymbolInfoDouble(_Symbol,SYMBOL_ASK)+MyPoint*TrailingStop,PositionGetDouble(POSITION_TP));
                     return;
                    }
                 }
              }
        }
      }
     }  
    return;
}


complex one below

// Trailing Stop
void sqManageTrailingStop(ulong ticket)
  {
   if(!PositionSelectByTicket(ticket))
     {
      Verbose("Cannot select position with ticket ", IntegerToString(ticket));
      return;
     }

   valueIdentificationSymbol = PositionGetString(POSITION_SYMBOL);
   int symbolDigits = (int) SymbolInfoInteger(valueIdentificationSymbol, SYMBOL_DIGITS);

   double tsValue = NormalizeDouble(sqGetValueByIdentification(sqGetTrailingStop(ticket)), symbolDigits);

   if(tsValue > 0)
     {
      double plValue;
      int error;

      int valueType = sqGetTrailingStopType(ticket);
      ENUM_POSITION_TYPE orderType = (ENUM_POSITION_TYPE) PositionGetInteger(POSITION_TYPE);

      if(orderType == POSITION_TYPE_BUY)
        {
         if(valueType == SLPTTYPE_RANGE)
           {
            tsValue = NormalizeDouble(sqGetBid(NULL) - tsValue, symbolDigits);
           }
        }
      else
        {
         if(valueType == SLPTTYPE_RANGE)
           {
            tsValue = NormalizeDouble(sqGetAsk(NULL) + tsValue, symbolDigits);
           }
        }

      double tsActivation = NormalizeDouble(sqGetValueByIdentification(sqGetTSActivation(ticket)), symbolDigits);
      double currentSL = NormalizeDouble(PositionGetDouble(POSITION_SL), symbolDigits);
      double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double takeProfit = PositionGetDouble(POSITION_TP);

      if(orderType == POSITION_TYPE_BUY)
        {
         plValue = NormalizeDouble(sqGetBid(NULL) - openPrice, symbolDigits);

         if(plValue >= tsActivation && (currentSL == 0 || currentSL < tsValue))
           {
            Verbose("Moving trailing stop for order with ticket: ", IntegerToString(ticket), " to :", DoubleToString(tsValue));
            if(!OrderModify(ticket, tsValue, takeProfit))
              {
               error = GetLastError();
               Verbose("Failed, error: ", IntegerToString(error), " - ", ErrorDescription(error),", Ask: ", DoubleToString(sqGetAsk(NULL)), ", Bid: ", DoubleToString(sqGetBid(NULL)), " Current SL: ",  DoubleToString(currentSL));
              }
           }
        }
      else     // orderType == OP_SELL
        {
         plValue = NormalizeDouble(openPrice - sqGetAsk(NULL), symbolDigits);

         if(plValue >= tsActivation && (currentSL == 0 || currentSL > tsValue))
           {
            Verbose("Moving trailing stop for order with ticket: ", IntegerToString(ticket), " to :", DoubleToString(tsValue));
            if(!OrderModify(ticket, tsValue, takeProfit))
              {
               error = GetLastError();
               Verbose("Failed, error: ", IntegerToString(error), " - ", ErrorDescription(error),", Ask: ", DoubleToString(sqGetAsk(NULL)), ", Bid: ", DoubleToString(sqGetBid(NULL)), " Current SL: ",  DoubleToString(currentSL));
              }
           }
        }
     }
  }


I also just noticed the mql5 program itself has an ea generator where you can choose the trailing stop feature you need and the output looks very simple.

 
Henry Asaba Achankeng #:

what did you mean?

Did you mean to say there is nothing like "else if"

Without an if statement, you can't have an else or an else if. Look at OPs original posted code.

Reason: