Viewing the resource: Fixed-Point Trailing Stop System in MQL5

Fixed-Point Trailing Stop System in MQL5

Allan Munene Mutiiria 2025-06-26 14:58:40 113 Views
This MQL5 EA opens three 0.01-lot buy/sell trades on startup and applies 300-pip trailing stops to t...

Introduction

Imagine safeguarding your trades with a precision risk management engine, automatically adjusting stop losses to secure profits as markets move. The Trailing Stop EA is your advanced trading tool, designed to automate risk control on MetaTrader 5 by opening three 0.01-lot buy and sell positions upon initialization ("OnInit()", "obj_trade.Buy()", "obj_trade.Sell()") and applying trailing stop losses based on a fixed 300-pip distance ("applyTrailingSTOP()", 300*_Point). On each price tick ("OnTick()"), it updates stop losses for trades with a specific magic number (123, "PositionGetInteger(POSITION_MAGIC)"), trailing the market price (e.g., bid minus 300 pips for buys) to protect gains. Managed via "CTrade", the system ensures selective trade management, avoiding interference with other positions. This strategy suits traders seeking automated risk management for multiple small positions, requiring careful account monitoring for 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 three 0.01-lot buy and sell trades ("obj_trade.Buy()", "obj_trade.Sell()") with a magic number (123) in "OnInit()".

  • Trailing Stop: Adjusts stop losses on each tick ("OnTick()", "applyTrailingSTOP()") using a fixed 300-pip distance (e.g., bid minus 300 pips 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 stop distances, lot sizes, or position limits 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 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.

//+------------------------------------------------------------------+
//|                                                TRAILING STOP.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 OnInit(){
   obj_trade.SetExpertMagicNumber(123);
   for (int i = 0; i < 3; i++){
      int ticketBuy = obj_trade.Buy(0.01);
      if (ticketBuy > 0){
         for (int j = 0; j < 1; j++){
            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 opens three 0.01-lot buy positions ("obj_trade.Buy()") and, for each successful buy ("ticketBuy > 0"), one 0.01-lot sell position ("obj_trade.Sell()"), totaling six positions (three buy, three sell). 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 a fixed distance, like fine-tuning the engine’s controls.

void OnTick(){
   applyTrailingSTOP(123,300*_Point);
}

void applyTrailingSTOP(int magicNo, double slPoints){
   double buySL = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID)-slPoints,_Digits);
   double sellSL = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK)+slPoints,_Digits);
   for (int i = PositionsTotal() - 1; i >= 0; i--){
      ulong ticket = PositionGetTicket(i);
      if (ticket > 0){
         if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
            PositionGetInteger(POSITION_MAGIC) == magicNo){
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY &&
               buySL > PositionGetDouble(POSITION_PRICE_OPEN) &&
               (buySL > PositionGetDouble(POSITION_SL) ||
               PositionGetDouble(POSITION_SL) == 0)){
               obj_trade.PositionModify(ticket,buySL,PositionGetDouble(POSITION_TP));
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL &&
               sellSL < PositionGetDouble(POSITION_PRICE_OPEN) &&
               (sellSL < PositionGetDouble(POSITION_SL) ||
               PositionGetDouble(POSITION_SL) == 0)){
               obj_trade.PositionModify(ticket,sellSL,PositionGetDouble(POSITION_TP));
            }
         }
      }
   }
}

In the risk management hub, "OnTick()" calls "applyTrailingSTOP()" with magic number 123 and a 300-pip stop distance ("300*_Point"). The function calculates trailing stops: for buys, "buySL"=Bid - slPoints and for sells, "sellSL"=Ask + slPoints, normalized via "NormalizeDouble()". It loops through open positions ("PositionsTotal()", "PositionGetTicket()") and selects trades matching the symbol ("_Symbol") and magic number ("PositionGetInteger(POSITION_MAGIC)"=123). For buy positions ("POSITION_TYPE_BUY"), it updates the stop loss ("obj_trade.PositionModify()") if "buySL" is above the open price ("PositionGetDouble(POSITION_PRICE_OPEN)") and higher than the current stop or unset ("POSITION_SL == 0"). For sells, it updates if "sellSL" is below the open price and lower than the current stop or unset. For example, on EURUSD H1 with bid=1.2050 and slPoints=0.0300, a buy at 1.2000 sets SL=1.1750, trailing to 1.2020 as bid rises to 1.2320, 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 no resources (e.g., indicators, arrays) are used beyond open positions, which persist in MetaTrader 5. For completeness, a placeholder could be added:

void OnDeinit(const int reason){
   // No resources to clean up
}

This ensures the system shuts down cleanly, like idling the engine for the next task.

Why This EA is a Risk Management Triumph

The Trailing Stop EA is a risk control triumph, automating fixed-point stop losses with precision, like a master-crafted engine. Its selective trade management ("POSITION_MAGIC"=123) and dynamic stop adjustments ("applyTrailingSTOP()", "PositionModify()") ensure robust profit protection, with potential for configurable parameters or position filters. Picture trailing a buy on EURUSD at 1.2020 with a 300-pip stop—strategic brilliance! Beginners will value the automated simplicity, while experts can enhance its flexibility, making it essential for traders managing multiple positions.

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 three 0.01-lot buy/sell trades with trailing stops.

  4. Monitor logs (e.g., stop loss updates) to confirm trailing stop adjustments.

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

Conclusion

We’ve engineered a Trailing Stop 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!