Viewing the resource: ATR-Based Trailing Stop System in MQL5

ATR-Based Trailing Stop System in MQL5

Allan Munene Mutiiria 2025-06-26 14:45:41 103 Views
This MQL5 EA opens 0.01-lot buy/sell trades on startup and adjusts their stop losses using a 14-peri...

Introduction

Imagine managing your trades with a precision risk management engine, dynamically adjusting stop losses to lock in profits as markets move. The Trailing Stop by ATR EA is your advanced trading tool, designed to automate risk control on MetaTrader 5 by applying trailing stop losses based on the 14-period Average True Range (ATR) indicator. Upon initialization ("OnInit()"), it opens 0.01-lot buy and sell positions ("obj_Trade.Buy()", "obj_Trade.Sell()") with a magic number (123) and initializes the ATR indicator ("iATR()", "handleATR"). On each price tick ("OnTick()"), it adjusts stop losses for matching trades ("PositionGetInteger(POSITION_MAGIC)") using ATR values ("dataATR", "CopyBuffer()") to trail the market price (e.g., bid minus ATR for buys). This strategy suits traders seeking automated risk management for small positions, requiring minimal setup but careful account monitoring to manage simultaneous trades.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated risk management engine, designed to inform and captivate readers. Tailored for both novice and experienced traders, we’ll dissect each code component with clear, precise explanations, as if guiding an apprentice engineer through a risk control project. With vivid examples—like trailing stops on EURUSD—and a polished tone, we’ll explore how the EA initializes, opens trades, adjusts stops, and ensures cleanup. Using a precision risk management engine metaphor, this guide will illuminate the code’s technical rigor, empowering you to protect trades with confidence. Let’s activate the system and begin this risk management expedition!

Strategy Blueprint

Let’s outline the EA’s risk management framework, like drafting specifications for a risk management engine:

  • Initialization: Opens 0.01-lot buy/sell trades ("obj_Trade.Buy()", "obj_Trade.Sell()") with a magic number (123) and sets up a 14-period ATR ("iATR()", "handleATR").

  • Trailing Stop: Adjusts stop losses on each tick ("OnTick()") using ATR values ("dataATR", "CopyBuffer()") to trail prices (e.g., bid minus ATR for buys).

  • Trade Filtering: Targets only trades with the specified magic number ("PositionGetInteger(POSITION_MAGIC)") for selective management.

  • Execution: Updates stops via "obj_Trade.PositionModify()", ensuring stops move only in the trade’s favor (e.g., higher for buys).

  • Enhancements: Adding configurable lot sizes, ATR periods, or position filters could improve flexibility. This framework automates risk control with precision, protecting profits in volatile markets.

Code Implementation

Let’s step into the risk management engine hub and dissect the MQL5 code that powers this Trailing Stop by ATR EA. We’ll guide you through each phase like expert engineers, ensuring the narrative flows seamlessly with professional clarity and engaging precision that captivates readers. We’ll cover initialization, trade opening, stop loss adjustment, and cleanup, with detailed explanations and examples—like trailing stops on EURUSD—to make it accessible for beginners. Each phase will build on the last, crafting a cohesive technical narrative that transforms code into a compelling risk control project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the risk management system, initializing trades and the ATR indicator.

//+------------------------------------------------------------------+
//|                                         TRAILING STOP BY ATR.mq5 |
//|                           Copyright 2025, Allan Munene Mutiiria. |
//|                                   https://t.me/Forex_Algo_Trader |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria."
#property link      "https://t.me/Forex_Algo_Trader"
#property version   "1.00"

#include <Trade/Trade.mqh>
CTrade obj_Trade;

int handleATR = INVALID_HANDLE;
double dataATR[];

int OnInit(){
   handleATR = iATR(_Symbol,_Period,14);
   if (handleATR == INVALID_HANDLE){
      Print("INVALID IND ATR HANDLE. REVERTING NOW");
      return (INIT_FAILED);
   }
   ArraySetAsSeries(dataATR,true);
   obj_Trade.SetExpertMagicNumber(123);
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   obj_Trade.Buy(0.01);
   obj_Trade.Sell(0.01);
   return(INIT_SUCCEEDED);
}

The system begins with the #property header, establishing copyright and contact details, like calibrating a risk management engine’s core. The "OnInit()" function initializes the setup, including "Trade/Trade.mqh" for trading ("CTrade", "obj_Trade") and setting a magic number (123, "SetExpertMagicNumber()"). It creates a 14-period ATR indicator ("iATR()", "handleATR") and checks for validity, returning INIT_FAILED if invalid. The ATR array is set as a time series ("ArraySetAsSeries(dataATR,true)"). It opens 0.01-lot buy and sell positions ("obj_Trade.Buy()", "obj_Trade.Sell()") at market prices ("SymbolInfoDouble()", "NormalizeDouble()"). Returning INIT_SUCCEEDED signals, “Engine is ready, let’s manage risks!” This primes the EA for automated trailing stops, like an engine poised for action. Note: The code uses MetaQuotes’ copyright, but your metadata is presented for consistency.

Phase 2: Managing Risks—Adjusting Trailing Stops

We adjust stop losses based on ATR, like fine-tuning the engine’s controls.

void OnTick(){
   if (CopyBuffer(handleATR,0,0,3,dataATR) < 3){
      Print("NOT ENOUGH DATA FOR FURTHER CALC'S. REVERTING");
      return;
   }
   if (dataATR[0] > 0){
      double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
      double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
      double buy_trail = Bid - NormalizeDouble(dataATR[0],_Digits);
      double sell_trail = Ask + NormalizeDouble(dataATR[0],_Digits);
      for (int i=PositionsTotal()-1; i>=0; i--){
         ulong ticket = PositionGetTicket(i);
         if (ticket > 0){
            if (PositionSelectByTicket(ticket)){
               string symb = PositionGetString(POSITION_SYMBOL);
               long type = PositionGetInteger(POSITION_TYPE);
               ulong magic = PositionGetInteger(POSITION_MAGIC);
               double open_p = PositionGetDouble(POSITION_PRICE_OPEN);
               double sl = PositionGetDouble(POSITION_SL);
               double tp = PositionGetDouble(POSITION_TP);
               if (symb == _Symbol && magic == 123){
                  if (type == POSITION_TYPE_BUY){
                     if (buy_trail > open_p && (sl == 0 || buy_trail > sl)){
                        obj_Trade.PositionModify(ticket,buy_trail,tp);
                     }
                  }
                  else if (type == POSITION_TYPE_SELL){
                     if (sell_trail < open_p && (sl == 0 || sell_trail < sl)){
                        obj_Trade.PositionModify(ticket,sell_trail,tp);
                     }
                  }
               }
            }
         }
      }
   }
}

In the risk management hub, "OnTick()" retrieves three ATR values ("CopyBuffer()", "dataATR") and checks for sufficient data (< 3 returns). If valid ("dataATR[0] > 0"), it calculates trailing stops: for buys, "buy_trail"=Bid - ATR (normalized via "NormalizeDouble()") and for sells, "sell_trail"=Ask + ATR. It loops through open positions ("PositionsTotal()", "PositionGetTicket()") and selects trades ("PositionSelectByTicket()") matching the symbol ("_Symbol") and magic number (123, "PositionGetInteger(POSITION_MAGIC)"). For buy positions ("POSITION_TYPE_BUY"), it updates the stop loss ("obj_Trade.PositionModify()") if "buy_trail" is above the open price and higher than the current stop ("sl == 0 || buy_trail > sl"). For sells, it updates if "sell_trail" is below the open price and lower than the current stop. For example, on EURUSD H1 with ATR=0.0010, a buy at 1.2000 with bid=1.2050 sets SL=1.2040, trailing upward as bid rises, like adjusting engine controls.

Phase 3: Shutting Down the System—Cleaning Up Resources

As our expedition concludes, we shut down the system, ensuring minimal resource use.

void OnDeinit(const int reason){
}

In the shutdown control room, "OnDeinit()" is empty, as only the ATR handle ("handleATR") and array ("dataATR") are used, requiring no explicit cleanup (MetaTrader 5 handles indicator release). For completeness, a cleanup could be added:

void OnDeinit(const int reason){
   if (handleATR != INVALID_HANDLE){
      IndicatorRelease(handleATR);
   }
}

This would release the ATR handle ("IndicatorRelease()") explicitly, like shutting down the engine cleanly.

Why This EA is a Risk Management Triumph

The Trailing Stop by ATR EA is a risk control triumph, automating dynamic stop losses with precision, like a master-crafted engine. Its ATR-based trailing logic ("dataATR", "PositionModify()") and trade filtering ("POSITION_MAGIC"=123) ensure robust profit protection, with potential for configurable parameters or additional indicators. Picture trailing a buy on EURUSD at 1.2040 with ATR=0.0010—strategic brilliance! Beginners will value the automated simplicity, while experts can enhance its flexibility, making it essential for traders seeking effective risk management.

Putting It All Together

To deploy this EA:

  1. Open MetaEditor in MetaTrader 5, like entering your risk management hub.

  2. Copy the code, compile with F5, and verify no errors—no engineer wants a faulty engine!

  3. Attach the EA to your chart (e.g., EURUSD H1) to open 0.01-lot buy/sell trades and apply trailing stops.

  4. Monitor logs (e.g., “Buy Stop placed: Entry=1.2000, SL=1.1990, TP=0”) for stop updates.

  5. Test on a demo account first—real capital deserves a trial run!

Conclusion

We’ve engineered a Trailing Stop by ATR system that protects trades with precision, like a master-crafted risk management engine. This MQL5 code is your strategic tool, brought to life with a seamless, professional narrative packed with clear explanations and vivid examples to fuel your trading confidence. Whether you’re a novice trader or a seasoned market strategist, this EA empowers you to manage risks with ease. Ready to protect? Watch our video guide on the website for a step-by-step creation process. Now, safeguard your trading with precision! 🔍

Disclaimer: Trading is like navigating complex markets—challenging and risky. Losses can exceed deposits. Test strategies on a demo account before going live.

Disclaimer: The ideas and strategies presented in this resource are solely those of the author and are intended for informational and educational purposes only. They do not constitute financial advice, and past performance is not indicative of future results. All materials, including but not limited to text, images, files, and any downloadable content, are protected by copyright and intellectual property laws and are the exclusive property of Forex Algo-Trader or its licensors. Reproduction, distribution, modification, or commercial use of these materials without prior written consent from Forex Algo-Trader is strictly prohibited and may result in legal action. Users are advised to exercise extreme caution, perform thorough independent research, and consult with qualified financial professionals before implementing any trading strategies or decisions based on this resource, as trading in financial markets involves significant risk of loss.

Recent Comments

Go to discussion to Comment or View other Comments

No comments yet. Be the first to comment!