🚀 AI One-Click Generation of mql4 Strategy Code

How to Program a Break-Even Stop Loss in a Mql4 Expert Advisor

mql4 | Published on: 2025/12/1
The following content is generated by EasyQuant .

Problem Description

How do I make my EA move the stop loss to the entry price after the trade is 20 pips in profit?

Solution

To implement a "Break Even" function in MQL4, you need to create a function that scans your open orders on every tick, checks if the current market price has moved 20 pips in your favor, and then modifies the order to move the Stop Loss to the opening price.

Here is the complete, robust MQL4 code snippet that you can add to your Expert Advisor.

Key Features of This Code

  1. 5-Digit Broker Support: It automatically detects if your broker uses 5 digits (points) and converts your "20 pips" setting correctly (20 pips = 200 points).
  2. Server Spam Protection: It checks if the Stop Loss is already at the entry price before trying to modify it. This prevents error 1 (No changes) and keeps the server log clean.
  3. Magic Number Filter: It only modifies trades opened by this specific EA.

The MQL4 Code

You can copy this entire block into your EA file.

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input double BreakEvenPips   = 20.0;    // Pips profit required to trigger BE
input double BreakEvenOffset = 0.0;     // Extra pips to lock in (e.g., 1.0 to cover commissions)
input int    MagicNumber     = 123456;  // ID of your EA's trades

// Global variable for pip adjustment
double PipsToPoints;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Adjust for 3 or 5 digit brokers (1 pip = 10 points)
   if(Digits == 3 || Digits == 5) PipsToPoints = Point * 10;
   else PipsToPoints = Point;
   
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Call the Break Even function on every tick
   ApplyBreakEven();
}

//+------------------------------------------------------------------+
//| Function to move Stop Loss to Entry Price                        |
//+------------------------------------------------------------------+
void ApplyBreakEven()
{
   // Loop through all open orders
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         // Filter: Only manage trades for this Symbol and Magic Number
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
         {
            //--- BUY ORDERS ---
            if(OrderType() == OP_BUY)
            {
               // 1. Check if profit exceeds the target (Current Bid - Open Price)
               if(Bid - OrderOpenPrice() >= BreakEvenPips * PipsToPoints)
               {
                  // Calculate the new Stop Loss price (Entry + Offset)
                  double newSL = OrderOpenPrice() + (BreakEvenOffset * PipsToPoints);
                  
                  // 2. Check if SL is not already at the new level (prevents server errors)
                  if(OrderStopLoss() < newSL)
                  {
                     // 3. Modify the order
                     if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrBlue))
                     {
                        Print("Error modifying Buy Order to BE: ", GetLastError());
                     }
                  }
               }
            }
            
            //--- SELL ORDERS ---
            if(OrderType() == OP_SELL)
            {
               // 1. Check if profit exceeds the target (Open Price - Current Ask)
               if(OrderOpenPrice() - Ask >= BreakEvenPips * PipsToPoints)
               {
                  // Calculate the new Stop Loss price (Entry - Offset)
                  double newSL = OrderOpenPrice() - (BreakEvenOffset * PipsToPoints);
                  
                  // 2. Check if SL is not already at the new level (or is 0)
                  if(OrderStopLoss() > newSL || OrderStopLoss() == 0)
                  {
                     // 3. Modify the order
                     if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrRed))
                     {
                        Print("Error modifying Sell Order to BE: ", GetLastError());
                     }
                  }
               }
            }
         }
      }
   }
}

How to Integrate This

  1. Inputs: Copy the input variables to the top of your file.
  2. OnInit: Copy the logic inside OnInit to your existing OnInit function. This ensures PipsToPoints is calculated correctly when the EA loads.
  3. Functions: Copy the ApplyBreakEven() function to the bottom of your file.
  4. OnTick: Add the line ApplyBreakEven(); inside your OnTick() function.

Q&A: Common Issues

Q: Why use BreakEvenOffset?
A: Setting the Stop Loss exactly at the entry price often results in a small monetary loss due to commissions or swap fees. Setting BreakEvenOffset to 1.0 or 2.0 ensures you cover those costs if the price reverses.

Q: Will this work on 5-digit brokers (e.g., EURUSD 1.12345)?
A: Yes. The OnInit logic calculates PipsToPoints. If you input 20 pips, the code automatically calculates 200 points for 5-digit brokers, ensuring the distance is correct.

Q: Why do you check OrderStopLoss() < newSL?
A: OrderModify is an expensive server call. If the price is 50 pips in profit, the condition "Profit > 20 pips" is still true. Without this check, the EA would try to move the Stop Loss to the entry price on every single tick, causing the broker to block your EA for spamming requests. This check ensures the modification happens only once.