Installation & Setup

Introduction to Automated Trade Management in MQL4

In MetaTrader 4, you don’t have to sit in front of the chart all day, watching every candle and moving your stop loss by hand. With a simple Expert Advisor (EA), you can make the platform move your stop loss to break even, trail your stop behind price, and protect your profit automatically.

If you’ve ever wondered how to code break even and trailing stop in mql4, you’re basically asking, “How do I teach my EA to manage trades like a disciplined trader?” That’s exactly what we’ll cover here.

In this guide, you’ll learn:

  • What break-even and trailing stops actually do
  • How to write MQL4 code that moves your stop loss to break even
  • How to create a fixed-distance trailing stop
  • How to combine both features in one clean Expert Advisor
  • How to test, debug, and avoid common mistakes

You don’t need to be a pro programmer. If you understand basic MT4 usage and can follow simple logic, you’ll be able to adapt the code to your own trading strategy.


Core Concepts: Stop Loss, Take Profit, Break Even, and Trailing Stop

Before we write any code, you need to understand the basic trade management concepts your EA will use.

Stop Loss (SL)

  • A stop loss is the price where your trade will be closed automatically if it goes against you.
  • For a buy, SL is below the entry price.
  • For a sell, SL is above the entry price.

In MQL4, you set or change it with OrderSend() and OrderModify().

Take Profit (TP)

  • A take profit is the price where you lock in profit automatically.
  • For a buy, TP is above entry.
  • For a sell, TP is below entry.

Your break-even and trailing stop usually work together with SL and TP for complete risk management.

Break Even

Moving stop loss to break even means:

  • You move your SL to (or slightly beyond) the entry price after price has moved in your favor by a certain distance.
  • This reduces risk to zero (or near zero), so you “can’t lose” from that trade anymore, except for small slippage or commissions.

Example idea for a buy:

  • Entry at 1.1000
  • Break-even trigger after +20 pips
  • When price hits 1.1020, move SL from 1.0950 to 1.1000 (or 1.1002 to lock a small profit).

Trailing Stop

A trailing stop moves your SL automatically as price moves in your favor.

Simple fixed trailing stop idea:

  • Trailing distance: 30 pips
  • For a buy: SL = current Bid − 30 pips
  • As the Bid goes up, SL goes up too, always staying 30 pips behind.

Trailing stops help you let profits run while still protecting part of your unrealized profit.


Setting Up Your MQL4 Environment in MetaTrader 4

To implement all this, you’ll work in MetaEditor, which is part of MetaTrader 4.

Steps to Prepare

  1. Open MetaEditor
    • In MT4, click Tools → MetaQuotes Language Editor, or press F4.
  2. Create a New Expert Advisor
    • In MetaEditor, go to File → New → Expert Advisor (template).
    • Give it a name like BreakEvenTrailingEA.
    • Click Next until the template is created.
  3. Understand the Main Function (Old EAs)
    • Classic MQL4 uses start() as the main tick function: int start() { // Your trade management code will go here return(0); }
  4. Enable Algorithmic Trading
    • Make sure AutoTrading is enabled in MT4.
    • Attach your EA to a chart and watch for any errors in the Experts and Journal tabs.
  5. Check the Official Documentation
    • For detailed function info, the official reference at
      https://docs.mql4.com
      is an excellent resource.

Once everything’s set up, you’re ready to write the actual break-even and trailing stop logic.


Understanding Price, Points, and Pips in MQL4

Many new coders get confused by pips and points. Your break-even and trailing-distance logic must be precise, or you’ll move stops to the wrong place.

Digits and Point

  • Digits is the number of decimal places of the symbol.
    • 4-digit broker example: EURUSD = 1.1234 → 1 pip = 0.0001
    • 5-digit broker example: EURUSD = 1.12345 → 1 pip = 0.00010
  • Point is the smallest price step.
    • On a 5-digit broker, 1 pip = 10 points.

Converting Pips to Price Distance

If you want to work in pips, you can define a helper like:

double PipValue()
  {
    if (Digits == 3 || Digits == 5)
       return(Point * 10);
    return(Point);
  }

Then, a 20-pip distance is:

double distance = 20 * PipValue();

Using a helper like this keeps your EA working on both 4- and 5-digit brokers.


Coding Break Even Logic in an Expert Advisor

Now we’ll implement the core break-even logic that moves stop loss to entry (plus an optional small buffer).

First, define external parameters at the top of your EA:

extern int    BreakEvenTriggerPips = 20;  // distance in pips before BE
extern int    BreakEvenOffsetPips  = 2;   // extra pips to lock profit
extern int    MagicNumber          = 12345;

Selecting Orders Safely with Symbol and Magic Number Filters

Inside start(), you’ll loop through open orders:

int start()
  {
    ManageBreakEven();
    return(0);
  }

void ManageBreakEven()
  {
    for(int i = OrdersTotal() - 1; i >= 0; i--)
      {
        if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           continue;

        if(OrderSymbol() != Symbol())
           continue;

        if(OrderMagicNumber() != MagicNumber)
           continue;

        // Only manage market orders
        if(OrderType() == OP_BUY || OrderType() == OP_SELL)
           ApplyBreakEvenToOrder();
      }
  }

This pattern ensures:

  • You don’t touch orders from other EAs.
  • You only work on the current symbol.
  • You ignore pending orders (like buy stops or sell limits).

Break Even Conditions for Buy Orders

Now let’s write ApplyBreakEvenToOrder() to handle buys:

void ApplyBreakEvenToOrder()
  {
    double pip = PipValue();
    double triggerDistance = BreakEvenTriggerPips * pip;
    double offset          = BreakEvenOffsetPips  * pip;

    // For BUY trades
    if(OrderType() == OP_BUY)
      {
        double currentPrice = Bid;
        double entryPrice   = OrderOpenPrice();
        double sl           = OrderStopLoss();

        // Price must have moved enough in profit
        if(currentPrice - entryPrice >= triggerDistance)
          {
            double newSL = entryPrice + offset;

            // Only move SL forward (never backward)
            if(sl < newSL)
              {
                newSL = NormalizeDouble(newSL, Digits);
                bool modified = OrderModify(
                                  OrderTicket(),
                                  OrderOpenPrice(),
                                  newSL,
                                  OrderTakeProfit(),
                                  0,
                                  clrNONE
                                );
                if(!modified)
                   Print("BreakEven BUY failed. Error: ", GetLastError());
              }
          }
      }
    // SELL logic will follow
  }

Key points:

  • We check if price has moved by at least BreakEvenTriggerPips.
  • We move SL to entryPrice + offset for a buy.
  • We only modify the order if the new SL is better than the old one.

Break Even Conditions for Sell Orders

Now add the sell part inside the same function:

    // For SELL trades
    if(OrderType() == OP_SELL)
      {
        double currentPrice = Ask;
        double entryPrice   = OrderOpenPrice();
        double sl           = OrderStopLoss();

        if(entryPrice - currentPrice >= triggerDistance)
          {
            double newSL = entryPrice - offset;

            // For SELL, a "better" SL is lower (closer to price in profit)
            if(sl == 0 || sl > newSL)
              {
                newSL = NormalizeDouble(newSL, Digits);
                bool modified = OrderModify(
                                  OrderTicket(),
                                  OrderOpenPrice(),
                                  newSL,
                                  OrderTakeProfit(),
                                  0,
                                  clrNONE
                                );
                if(!modified)
                   Print("BreakEven SELL failed. Error: ", GetLastError());
              }
          }
      }

Now you have a working break-even manager for both buy and sell orders.


Coding a Fixed Trailing Stop in MQL4

Next, we’ll create a fixed trailing stop. This will keep your stop loss a set distance from the current price once the trade is in profit.

Add these external inputs:

extern int TrailingStopPips = 30;   // distance from price
extern int TrailingStepPips = 5;    // minimum step to move SL

Then, add a new function:

void ManageTrailingStop()
  {
    double pip = PipValue();

    for(int i = OrdersTotal() - 1; i >= 0; i--)
      {
        if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           continue;

        if(OrderSymbol() != Symbol())
           continue;

        if(OrderMagicNumber() != MagicNumber)
           continue;

        if(OrderType() == OP_BUY || OrderType() == OP_SELL)
           ApplyTrailingToOrder();
      }
  }

And don’t forget to call it inside start() along with the break-even logic:

int start()
  {
    ManageBreakEven();
    ManageTrailingStop();
    return(0);
  }

Trailing Stop for Buy Positions

Inside ApplyTrailingToOrder(), handle buys like this:

void ApplyTrailingToOrder()
  {
    double pip = PipValue();
    double tsDistance = TrailingStopPips * pip;
    double tsStep     = TrailingStepPips * pip;

    if(OrderType() == OP_BUY)
      {
        double currentPrice = Bid;
        double newSL        = currentPrice - tsDistance;
        double oldSL        = OrderStopLoss();

        // Only trail if trade is already in profit beyond trailing distance
        if(currentPrice - OrderOpenPrice() > tsDistance)
          {
            // Only move SL if we are at least tsStep ahead of old SL
            if(oldSL < newSL - tsStep || oldSL == 0)
              {
                newSL = NormalizeDouble(newSL, Digits);
                bool modified = OrderModify(
                                  OrderTicket(),
                                  OrderOpenPrice(),
                                  newSL,
                                  OrderTakeProfit(),
                                  0,
                                  clrNONE
                                );
                if(!modified)
                   Print("Trailing BUY failed. Error: ", GetLastError());
              }
          }
      }

This code:

  • Ensures the trade is clearly in profit.
  • Moves SL only if it’s at least a few pips closer to price (to avoid too many modifications).

Trailing Stop for Sell Positions

For sell orders:

    if(OrderType() == OP_SELL)
      {
        double currentPrice = Ask;
        double newSL        = currentPrice + tsDistance;
        double oldSL        = OrderStopLoss();

        if(OrderOpenPrice() - currentPrice > tsDistance)
          {
            // For SELL, SL must move downward (closer to current price)
            if(oldSL > newSL + tsStep || oldSL == 0)
              {
                newSL = NormalizeDouble(newSL, Digits);
                bool modified = OrderModify(
                                  OrderTicket(),
                                  OrderOpenPrice(),
                                  newSL,
                                  OrderTakeProfit(),
                                  0,
                                  clrNONE
                                );
                if(!modified)
                   Print("Trailing SELL failed. Error: ", GetLastError());
              }
          }
      }
  }

Now you have a basic trailing stop engine for both directions.


Combining Break Even and Trailing Stop in One EA

Usually, you want both behaviors:

  1. First, move SL to break even when the trade is safely in profit.
  2. Then, let the trailing stop keep moving SL further into profit.

A simple way to combine them:

  • Run break-even logic first.
  • Run trailing logic second.

We already did that by calling both functions in start():

int start()
  {
    ManageBreakEven();   // Step 1: secure the trade
    ManageTrailingStop(); // Step 2: trail profits
    return(0);
  }

If you want stricter control, you can:

  • Only start trailing once SL is at or beyond break-even.
  • Add extra checks inside ManageTrailingStop() to ensure SL is not moved backwards by mistake.

This gives your EA a clear and logical trade-management flow.


Testing, Debugging, and Optimizing Your EA

Even if your code compiles, it doesn’t mean it works as you imagine. You must test and debug it.

Using Strategy Tester

  1. Open View → Strategy Tester in MT4.
  2. Choose your EA and symbol (e.g., EURUSD).
  3. Select timeframe and testing period.
  4. Use “Visual mode” to see how your stops move on the chart.

Watch the trade list and confirm:

  • SL moves to break even at the correct price.
  • Trailing stop keeps updating as price moves.

Reading the Log

In the Strategy Tester, check the Journal:

  • Look for printed messages like
    BreakEven BUY failed. Error: 1.
  • Error codes tell you what went wrong (e.g., invalid stops, busy trade server, etc.).

You can cross-check error codes in the official docs: https://docs.mql4.com/constants/errors.

Optimizing Settings

Use Strategy Tester’s Optimization:

  • Test different values for:
    • BreakEvenTriggerPips
    • BreakEvenOffsetPips
    • TrailingStopPips
    • TrailingStepPips

Try to find a balance where:

  • You protect your account early enough.
  • You still give the trade room to breathe.

Common Mistakes and How to Avoid Them

Here are some typical problems people face while figuring out how to code break even and trailing stop in mql4:

  1. Wrong Pip/Point Calculation
    • Using Point directly on 5-digit brokers and expecting pip values.
    • Fix: use a PipValue() helper.
  2. Moving SL in the Wrong Direction
    • Setting buy SL above current Bid or sell SL below current Ask.
    • This can cause ERR_INVALID_STOPS.
    • Fix: always check logical direction when calculating new SL.
  3. Too Many OrderModify Calls
    • Updating SL on every tick for tiny changes.
    • Broker may reject too frequent modifications.
    • Fix: use TrailingStepPips to move SL only when progress is big enough.
  4. Managing Other EAs’ Trades by Accident
    • Forgetting to filter by MagicNumber.
    • Fix: always check OrderMagicNumber().
  5. Ignoring Errors
    • Not checking the return value of OrderModify().
    • Fix: always check and log GetLastError().

By avoiding these mistakes, your EA will be more stable and easier to maintain.


FAQs about how to code break even and trailing stop in mql4

Q1. Do I need two separate EAs for break even and trailing stop?

No. You can put both break-even and trailing-stop logic into the same EA. Just keep the logic organized in separate functions like ManageBreakEven() and ManageTrailingStop(), and call them from start().


Q2. When should break even trigger compared to the trailing stop?

Common practice is:

  • Let break even trigger first when the trade is safely in profit (for example, +20 pips).
  • After SL is moved to entry (or slightly beyond), you let the trailing stop take over and keep moving SL as the trade goes further in your favor.

Q3. Why do I get “invalid stops” when I try to modify the order?

“Invalid stops” usually means:

  • Your new stop loss is too close to the current price.
  • Or it’s on the wrong side of price (e.g., buy SL above Bid).

Check:

  • Minimum stop levels for your broker.
  • The direction of your SL (below price for buys, above price for sells).
  • That you’re using proper pip/point calculations.

Q4. Can I use this code on any symbol and timeframe?

Yes, the logic is not tied to a specific symbol or timeframe. However:

  • Different symbols have different volatility and pip values.
  • You may need different parameter values (like BreakEvenTriggerPips and TrailingStopPips) for indices, metals, or crypto versus major forex pairs.

Always test each symbol separately in Strategy Tester.


Q5. Will this work with manual trades or only EA trades?

If you remove or adjust the MagicNumber filter, the EA can manage manual trades too. For example:

  • Use MagicNumber = 0 and handle orders where OrderMagicNumber() == 0.
  • Be careful: it might then manage all manual trades on that symbol.

Q6. Is it better to code this as an EA or use a trade manager script/indicator?

For continuous management (break even and trailing stops), an EA is usually better because:

  • It runs on every tick.
  • It doesn’t need manual re-attachment for each trade.

Scripts are good for one-time actions; indicators are for visual signals. For ongoing stop management, EA is the right tool.


Conclusion and Next Steps for Your MQL4 Journey

You’ve now seen the full process of how to code break even and trailing stop in mql4:

  • You understand the key concepts: stop loss, take profit, break even, and trailing stop.
  • You know how to loop through trades safely using symbol and magic number filters.
  • You’ve learned how to move your stop to break even after price moves in your favor.
  • You’ve implemented a fixed trailing stop for both buy and sell orders.
  • You know how to combine both features in one Expert Advisor and test everything in Strategy Tester.

From here, you can:

  • Customize the parameters to match your trading system.
  • Add more advanced features like ATR-based trailing stops, partial closes, or different rules per time of day.
  • Explore more advanced examples and references on the official MQL4 documentation at https://docs.mql4.com.

With this foundation, you’re no longer just a button-click trader—you’re a trader who can teach the platform exactly how to manage risk and protect profits.

AVA AIGPT5 EA: AI-fueled 4D Nano Algorithm Gold Scalper for MT4

(2)

238 in stock

$0.00 $678.99Price range: $0.00 through $678.99
Select options This product has multiple variants. The options may be chosen on the product page

FXCore100 EA [UPDATED]

(3)

342 in stock

Original price was: $490.00.Current price is: $7.99.

Golden Deer Holy Grail Indicator (Lifetime Premium)

(12)

324 in stock

Original price was: $1,861.99.Current price is: $187.99.

Millionaire Bitcoin Scalper Pro EA: AI-fueled 4D Nano Scalper for MT4

(8)

245 in stock

$0.00 $987.99Price range: $0.00 through $987.99
Select options This product has multiple variants. The options may be chosen on the product page

Powerful Forex VPS for MT4 & MT5 – Best Price

(11)

182 in stock

$44.99 $359.99Price range: $44.99 through $359.99
Select options This product has multiple variants. The options may be chosen on the product page

Top 2000 Trading Tools for Forex Success in 2025 (EA & Indicator)

(3)

Out of stock

Original price was: $9,999.99.Current price is: $4.99.
author-avatar

About Daniel B Crane

Hi there! I'm Daniel. I've been trading for over a decade and love sharing what I've learned. Whether it's tech or trading, I'm always eager to dive into something new. Want to learn how to trade like a pro? I've created a ton of free resources on my website, bestmt4ea.com. From understanding basic concepts like support and resistance to diving into advanced strategies using AI, I've got you covered. I believe anyone can learn to trade successfully. Join me on this journey and let's grow your finances together!

Leave a Reply