I can't insert dynamic stop loss on trades already executed in my EA

 
Hi, nice to meet you Vincenzo, I'm new here and I hope I'm not making a mistake. I'm trying to write my own EA and I can't add a dynamic stop loss to the trades already executed. Example: I would like my EA to set a stop loss to the buys/sells already executed only when they have already matured a profit. I would also like, if possible, that this stop loss be dynamic and be increased in favor of the trade every time the price moves in favor of a specific value to protect the profit. Unfortunately, it happens that my EA closes the trades at a loss because of the stop loss. Could someone help me? I would be very grateful. Thanks in advance, see you soon.
 
Vincenzo Scrofani:
Hi, nice to meet you Vincenzo, I'm new here and I hope I'm not making a mistake. I'm trying to write my own EA and I can't add a dynamic stop loss to the trades already executed. Example: I would like my EA to set a stop loss to the buys/sells already executed only when they have already matured a profit. I would also like, if possible, that this stop loss be dynamic and be increased in favor of the trade every time the price moves in favor of a specific value to protect the profit. Unfortunately, it happens that my EA closes the trades at a loss because of the stop loss. Could someone help me? I would be very grateful. Thanks in advance, see you soon.

For your initial stoploss, the simplest solution is to set a distant fail-safe stop. Then it sounds like you're describing a trailing stop to move the initial stop:

Trailing stop - Trading automation - MQL5 Programming for Traders - MetaTrader 5 algorithmic/automatic trading language manual

MQL5 Book: Trading automation / Creating Expert Advisors / Trailing stop
MQL5 Book: Trading automation / Creating Expert Advisors / Trailing stop
  • www.mql5.com
One of the most common tasks where the ability to change protective price levels is used is to sequentially shift Stop Loss at a better price as...
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
I tried to read it, but I can't find what I need. Could you show me where the part I'm interested in is?
 
Vincenzo Scrofani #: I tried to read it, but I can't find what I need. Could you show me where the part I'm interested in is?

If you want help with coding, then please show your code (or at least your attempt at coding it).

EDIT: Please use the CODE button (Alt-S) when inserting code — https://www.mql5.com/en/articles/24#insert-code

 
//+------------------------------------------------------------------+
//|                                                      GridTrading |
//|                        Developed by User                        |
//+------------------------------------------------------------------+
#property copyright "Dynamo_SCR"
#property version   "1.00"

//--- Input parameters
input double GridStep = 4.5;           // Step between grid levels
input double TrailingStep = 30.0;     // Step for trailing stop adjustment in pips
input double TrailingStop = 10.0;     // Trailing stop in pips
input double LotSize = 0.01;           // Lot size for each trade
input double MaxSpread = 2.0;         // Maximum allowed spread in pips

//--- Global variables
double GridLevels[];                  // Array to store grid levels
long LastOrderTicket = 0;             // Last order ticket to manage trailing stop

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   ArrayResize(GridLevels, 0);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Clean up resources if needed
}

//+------------------------------------------------------------------+
//| Expert tick function                                            |
//+------------------------------------------------------------------+
void OnTick()
{
double currentPrice = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
   double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;

   if (spread > MaxSpread)
      return; // Exit if spread is too high

   UpdateGrid(currentPrice);
   CheckForTrade(currentPrice);
   ManageTrailingStop();
}

//+------------------------------------------------------------------+
//| Update grid levels                                              |
//+------------------------------------------------------------------+
void UpdateGrid(double price)
{
   ArrayResize(GridLevels, 0);
   double startLevel = MathFloor(price / GridStep) * GridStep;
   for (int i = -50; i <= 50; i++)
   {
      double level = NormalizeDouble(startLevel + (i * GridStep), _Digits);
      ArrayResize(GridLevels, ArraySize(GridLevels) + 1);
      GridLevels[ArraySize(GridLevels) - 1] = level;
   }
}

//+------------------------------------------------------------------+
//| Check for trade opportunities                                   |
//+------------------------------------------------------------------+
void CheckForTrade(double price)
{
   for (int i = 0; i < ArraySize(GridLevels); i++)
   {
      if (price >= GridLevels[i] && LastOrderDirection() != POSITION_TYPE_BUY)
      {
         OpenOrder(POSITION_TYPE_BUY);
         break;
      }
      else if (price <= GridLevels[i] && LastOrderDirection() != POSITION_TYPE_SELL)
      {
OpenOrder(POSITION_TYPE_SELL);
         break;
      }
   }
}

//+------------------------------------------------------------------+
//| Open an order                                                   |
//+------------------------------------------------------------------+
void OpenOrder(int direction)
{
   MqlTradeRequest request;
   MqlTradeResult result;
   ZeroMemory(request);
   ZeroMemory(result);

   request.action = TRADE_ACTION_DEAL;
   request.symbol = _Symbol;
   request.volume = LotSize;
   request.type = (direction == POSITION_TYPE_BUY) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   request.price = (direction == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
   request.sl = (direction == POSITION_TYPE_BUY) 
                ? NormalizeDouble(request.price - (TrailingStop * _Point), _Digits) 
                : NormalizeDouble(request.price + (TrailingStop * _Point), _Digits);
   request.tp = 0;
   request.deviation = 5;
   request.magic = 0;
   request.comment = "GridTrade";

   // Send order without checking filling mode
   if (OrderSend(request, result))
   {
      Print("Order sent successfully. Ticket: ", result.order);
      LastOrderTicket = result.order;
   }
   else
   {
      Print("OrderSend failed. Error: ", GetLastError());
   }
}
//+------------------------------------------------------------------+
//| Manage trailing stop                                            |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
   int totalPositions = PositionsTotal(); // Get the total number of positions

   for (int i = totalPositions - 1; i >= 0; i--)
   {
      if (PositionSelect(_Symbol)) // Select position by index
      {
         double newStop = 0.0;
         double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         double currentStop = PositionGetDouble(POSITION_SL);

         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
         {
            newStop = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID) - (TrailingStop * _Point), _Digits);
            if (newStop > currentStop)
            {
               ModifyPosition(PositionGetInteger(POSITION_IDENTIFIER), newStop);
            }
         }
         else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         {
            newStop = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (TrailingStop * _Point), _Digits);
            if (newStop < currentStop)
            {
               ModifyPosition(PositionGetInteger(POSITION_IDENTIFIER), newStop);
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Modify position                                                 |
//+------------------------------------------------------------------+
void ModifyPosition(long ticket, double stopLoss)
{
MqlTradeRequest request;
   MqlTradeResult result;
   ZeroMemory(request);
   ZeroMemory(result);

   request.action = TRADE_ACTION_SLTP;
   request.symbol = _Symbol;
   request.sl = stopLoss;
   request.tp = 0;
   request.magic = 0;
   request.position = ticket;

   if (OrderSend(request, result))
   {
      Print("Position modified. Ticket: ", result.order);
   }
   else
   {
      Print("OrderSend failed. Error: ", GetLastError());
   }
}

//+------------------------------------------------------------------+
//| Retrieve last order direction                                   |
//+------------------------------------------------------------------+
int LastOrderDirection()
{
   if (LastOrderTicket <= 0 || !PositionSelect(_Symbol))
      return(-1);

   return(PositionGetInteger(POSITION_TYPE));
}
//+------------------------------------------------------------------+
 
Fernando Carreiro #:

If you want help with coding, then please show your code (or at least your attempt at coding it).

EDIT: Please use the CODE button (Alt-S) when inserting code — https://www.mql5.com/en/articles/24#insert-code

I was shared the code

 
Vincenzo Scrofani #:I was shared the code

Have a look at a sample trailing stop EA in the CodeBase. It mostly contains custom functions which should be fairly easy to plug into your code.

Code Base

Trailing stop MT5

Mr Anucha Maneeyotin, 2021.09.24 06:54

Use protect profit after open position
 

You should make it a habit of studying example code in the CodeBase. Use the search option to narrow down what you are looking for (e.g. "trailing stop").

There are many examples there—some good, some bad. You will learn from studying and understanding both.

Here are some that I found on the first page or two of the search (there were many more):

Code Base

Dynamic Trailing Stop Loss and Profit Target Management

Ohene Kofi Akuoku Osei, 2023.04.27 18:03

This code snippet implements a dynamic risk management strategy for existing trades. It focuses on closing trades based on profit or loss thresholds and employs a trailing stop loss to lock in profits as the trade moves favorably. The strategy helps manage risk and enhance profitability in a streamlined manner.

Code Base

A WPR Based Trailing Stop Module

Egor Murikov, 2013.07.16 20:26

A trailing stop module based on the WPR indicator with short and long Stop Loss

Code Base

Trailing Stop by Fixed Parabolic SAR

Yoshihiro Nakata, 2022.07.08 17:10

Modify to allow direct specification of the starting point of the Parabolic SAR.

Code Base

Trailing stop tutorial using ATR indicator

Dao Thanh Tan, 2024.05.28 21:02

Trailing stop tutorial using ATR indicator

Code Base

Code Block for "Trailing Stop" based on current market price. (Ask / Bid)

Hapu Arachchilage Tharindu Lakmal, 2024.04.04 22:09

This code block loops through all opened position and do trailing based on Ask and Bid prices.
MQL5 Code Base
MQL5 Code Base
  • www.mql5.com
MQL5 Source Code Library for MetaTrader 5
 

There are also Articles dedicated to coding trailing stops, so research them ...

Articles

How to develop any type of Trailing Stop and connect it to an EA

Artyom Trishkin, 2024.09.25 17:12

In this article, we will look at classes for convenient creation of various trailings, as well as learn how to connect a trailing stop to any EA.

Articles

How to add Trailing Stop using Parabolic SAR

Artyom Trishkin, 2024.09.10 12:55

When creating a trading strategy, we need to test a variety of protective stop options. Here is where a dynamic pulling up of the Stop Loss level following the price comes to mind. The best candidate for this is the Parabolic SAR indicator. It is difficult to think of anything simpler and visually clearer.

Articles

Learn how to design a trading system by Parabolic SAR

Mohamed Abdelmaaboud, 2022.05.13 17:09

In this article, we will continue our series about how to design a trading system using the most popular indicators. In this article, we will learn about the Parabolic SAR indicator in detail and how we can design a trading system to be used in MetaTrader 5 using some simple strategies.

Articles

Trailing stop in trading

Aleksej Poljakov, 2024.05.27 16:47

In this article, we will look at the use of a trailing stop in trading. We will assess how useful and effective it is, and how it can be used. The efficiency of a trailing stop largely depends on price volatility and the selection of the stop loss level. A variety of approaches can be used to set a stop loss.
 

Also take some time to study the MQL5 programming for traders - Book on MQL5.com.

It too, contains a section about trailing stops ... MQL5 Book: Trading automation / Creating Expert Advisors / Trailing stop