Viewing the resource: Two MA Crossover Trading with Trailing Stop in MQL5

Two MA Crossover Trading with Trailing Stop in MQL5

Allan Munene Mutiiria 2025-06-22 01:57:42 206 Views
This article details the MQL5 code for the Advanced 2MA Crossover EA, automating trades on fast/slow...

Introduction

Imagine navigating the forex markets with the precision of an experienced explorer, using clear trend signals to guide your trading decisions. The Advanced 2MA Crossover EA is your precision-engineered trading tool, designed to automate trend-following trades by leveraging crossovers between a fast 20-period EMA ("handleFast") and a slower 50-period SMA ("handleSlow"). When the fast MA crosses above the slow MA, it triggers a 0.01-lot buy trade with a 200-pip take profit ("ask+200*_Point"), closing any sell positions. Conversely, a crossover below opens a sell trade, closing buys. A trailing stop ("applyTrailingStop()", 100 pips) dynamically adjusts to lock in profits, ensuring disciplined trend capture without fixed stop losses. Each trade uses a unique magic number ("magic_No"=1234567) for tracking, making this EA ideal for traders seeking automated trend strategies in volatile markets.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated trading system, 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 navigator through a trend-tracking project. With vivid examples—like trading a crossover on EURUSD—and a polished tone, we’ll explore how the EA initializes, detects signals, executes trades, manages positions, and ensures cleanup. Using a precision trend navigation metaphor, this guide will illuminate the code’s technical rigor, empowering you to harness trend opportunities with confidence. Let’s activate the system and begin this trading expedition!

Strategy Blueprint

Let’s outline the EA’s trading framework, like drafting specifications for a trend-following system:

  • Signal Detection: Triggers 0.01-lot buys when the fast MA ("bufferFast") crosses above the slow MA ("bufferSlow"), or sells when it crosses below, using "CopyBuffer()", "iClose()".

  • Trade Execution: Opens buys/sells with "obj_Trade.Buy()", "obj_Trade.Sell()", setting 200-pip take profits ("ask+200*_Point", "bid-200*_Point") and no stop losses.

  • Position Management: Closes opposite positions ("obj_Trade.PositionClose()") and applies a 100-pip trailing stop ("applyTrailingStop()") for profit protection.

  • Execution: Processes signals on new bars ("iBars()") with unique trade tracking ("magic_No"=1234567).

  • Enhancements: Adding stop losses or timeframe inputs could improve risk control and flexibility. This framework automates trend trading with precision, balancing momentum capture with disciplined exits.

Code Implementation

Let’s step into the trading navigation hub and dissect the MQL5 code that powers this Advanced 2MA Crossover EA. We’ll guide you through each phase like expert navigators, ensuring the narrative flows seamlessly with professional clarity and engaging precision that captivates readers. We’ll cover initialization, signal detection, trade execution, position management, and cleanup, with detailed explanations and examples—like trading 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 trading project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the trading system, initializing moving averages and settings to prepare for trend detection.

//+------------------------------------------------------------------+
//|             Our Advanced 2MA CrossOver EA WITH 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 handleFast; double bufferFast[];
int handleSlow; double bufferSlow[];
int totalBars = 0;
int magic_No = 1234567;

int OnInit(){
   handleFast = iMA(_Symbol,_Period,20,0,MODE_EMA,PRICE_CLOSE);
   if (handleFast==INVALID_HANDLE) return(INIT_FAILED);
   handleSlow = iMA(_Symbol,_Period,50,0,MODE_SMA,PRICE_CLOSE);
   if (handleSlow==INVALID_HANDLE) return(INIT_FAILED);
   ArraySetAsSeries(bufferFast,true);
   ArraySetAsSeries(bufferSlow,true);
   obj_Trade.SetExpertMagicNumber(magic_No);
   return(INIT_SUCCEEDED);
}

The system begins with the #property header, setting the stage with copyright and contact details, like calibrating a trend-tracking system’s core. The "OnInit()" function initializes the setup, including "Trade/Trade.mqh" for trading via "obj_Trade", setting the magic number ("magic_No"=1234567) with "SetExpertMagicNumber()". It creates handles for a 20-period EMA ("handleFast", "iMA()") and 50-period SMA ("handleSlow"), with arrays "bufferFast[]" and "bufferSlow[]" set as time series ("ArraySetAsSeries()") for data storage. The variable "totalBars" tracks new bars. If handles fail ("INVALID_HANDLE"), it returns "INIT_FAILED". Returning INIT_SUCCEEDED signals, “System is ready, let’s navigate trends!” This setup primes the EA for crossover trading, like a navigation tool poised for action.

Phase 2: Mapping Trend Signals—Loading MA Data

With the system active, we load MA data to detect crossover signals, like scanning for trend changes on a market map.

void OnTick(){
   applyTrailingStop(_Symbol,100*_Point);
   int bars = iBars(_Symbol,_Period);
   if (totalBars == bars) return;
   totalBars = bars;
   if (!CopyBuffer(handleFast,0,0,3,bufferFast)){
      Print("Problem loading Fast MA data!");
      return;
   }
   if (!CopyBuffer(handleSlow,0,0,3,bufferSlow)){
      Print("Problem loading Slow MA data!");
      return;
   }

In the signal mapping hub, "OnTick()" runs every tick, applying trailing stops with "applyTrailingStop()" (100 pips, "100*_Point") for open positions. It checks for new bars with "iBars()", "totalBars", exiting if none. It loads 3 bars of data for the fast and slow MAs into "bufferFast[]" and "bufferSlow[]" using "CopyBuffer()", logging errors with "Print()" if loading fails, like a system flagging a data issue. This ensures reliable trend signals, like a clear radar scan, before processing crossovers.

Phase 3: Navigating Trades—Detecting and Executing Crossovers

With MA data loaded, we detect crossovers and execute trades, like launching trades on confirmed trend signals.

void OnTick(){
   // ... (data loading)
   double fastMA1 = bufferFast[1]; double slowMA1 = bufferSlow[1];
   double fastMA2 = bufferFast[2]; double slowMA2 = bufferSlow[2];
   if (fastMA1 > slowMA1 && !(fastMA2 > slowMA2)){
      for (int i = PositionsTotal()-1; i >= 0; i--){
         ulong ticket = PositionGetTicket(i);
         if (ticket > 0){
            if (PositionGetString(POSITION_SYMBOL)==_Symbol &&
               PositionGetInteger(POSITION_MAGIC)==magic_No){
               if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL){
                  obj_Trade.PositionClose(ticket);
               }
            }
         }
      }
      double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      obj_Trade.Buy(0.01,_Symbol,ask,0,ask+200*_Point);
   }
   else if (fastMA1 < slowMA1 && !(fastMA2 < slowMA2)){
      for (int i = PositionsTotal()-1; i >= 0; i--){
         ulong ticket = PositionGetTicket(i);
         if (ticket > 0){
            if (PositionGetString(POSITION_SYMBOL)==_Symbol &&
               PositionGetInteger(POSITION_MAGIC)==magic_No){
               if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY){
                  obj_Trade.PositionClose(ticket);
               }
            }
         }
      }
      double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
      obj_Trade.Sell(0.01,NULL,bid,0,bid-200*_Point);
   }
}

In the trade navigation hub, "OnTick()" compares MA values ("fastMA1", "slowMA1", "fastMA2", "slowMA2") from "bufferFast[1]", "bufferSlow[1]", etc. A bullish crossover ("fastMA1 > slowMA1 && !(fastMA2 > slowMA2)") closes sell positions ("PositionsTotal()", "PositionGetTicket()", "obj_Trade.PositionClose()") and opens a 0.01-lot buy with "obj_Trade.Buy()", setting take profit at "ask+200*_Point" (no stop loss). A bearish crossover ("fastMA1 < slowMA1 && !(fastMA2 < slowMA2)") closes buys and opens a sell with "obj_Trade.Sell()". For example, on EURUSD H1, a fast MA (1.2000) crossing above the slow MA (1.1995) triggers a buy at 1.2007, take profit at 1.2207, closing any sells, like locking onto a bullish trend signal.

Phase 4: Securing Profits—Applying Trailing Stops

With trades open, we manage positions with trailing stops, like adjusting navigation to secure trend gains.

void applyTrailingStop(string symbol,double stoplossPOINTS){
   double buy_stopLoss = NormalizeDouble(SymbolInfoDouble(symbol,SYMBOL_BID)-stoplossPOINTS,_Digits);
   double sell_stopLoss = NormalizeDouble(SymbolInfoDouble(symbol,SYMBOL_ASK)+stoplossPOINTS,Digits());
   for (int i = PositionsTotal()-1; i >= 0; i--){
      ulong posTicket = PositionGetTicket(i);
      if (posTicket > 0){
         if (PositionGetString(POSITION_SYMBOL)==_Symbol &&
            PositionGetInteger(POSITION_MAGIC)==magic_No){
            if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY &&
               buy_stopLoss > PositionGetDouble(POSITION_PRICE_OPEN) &&
               (buy_stopLoss > PositionGetDouble(POSITION_SL) ||
               PositionGetDouble(POSITION_SL)==0)){
               obj_Trade.PositionModify(posTicket,buy_stopLoss,
                  PositionGetDouble(POSITION_TP));
            }
            else if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL &&
               sell_stopLoss < PositionGetDouble(POSITION_PRICE_OPEN) &&
               (sell_stopLoss < PositionGetDouble(POSITION_SL) ||
               PositionGetDouble(POSITION_SL)==0)){
               obj_Trade.PositionModify(posTicket,sell_stopLoss,
                  PositionGetDouble(POSITION_TP));
            }
         }
      }
   }
}

In the profit securing hub, "applyTrailingStop()" adjusts stops for open positions ("PositionsTotal()", "PositionGetTicket()") using "magic_No". For buys, it sets the stop loss at "buy_stopLoss" (bid minus "stoplossPOINTS"=100), updating with "obj_Trade.PositionModify()" if above the open price and current stop loss ("PositionGetDouble()"). Sells use "sell_stopLoss" (ask plus 100 pips). For example, a EURUSD buy at 1.2007 with bid rising to 1.2107 updates the stop loss to 1.2007, securing 100 pips, like trailing a trend signal to lock in gains.

Phase 5: Shutting Down the System—Cleaning Up Resources

As our expedition concludes, we shut down the system, ensuring resources are cleared for the next journey.

void OnDeinit(const int reason){
   IndicatorRelease(handleFast);
   IndicatorRelease(handleSlow);
   ArrayFree(bufferFast);
   ArrayFree(bufferSlow);
}

In the shutdown hub, "OnDeinit()" releases MA handles ("handleFast", "handleSlow") with "IndicatorRelease()" and frees arrays ("bufferFast", "bufferSlow") with "ArrayFree()", like dismantling a navigation system’s components. This ensures a clean workspace, ready for the next task.

Why This EA is a Navigation Triumph

The Advanced 2MA Crossover EA is a trend-following triumph, automating MA crossover trades with precision, like a master navigator. Its robust signals ("bufferFast", "bufferSlow"), trailing stops ("applyTrailingStop()"), and trade management ("obj_Trade") offer clarity, with potential for stop losses or inputs to enhance safety. Picture a buy on EURUSD at 1.2007, trailing to 1.2007 for 100 pips—strategic brilliance! Beginners will value the clear logic, while experts can refine its framework, making it essential for trend traders.

Putting It All Together

To deploy this EA:

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

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

  3. Attach the EA to your chart, enable AutoTrading, and watch it execute crossover trades.

  4. Monitor logs (e.g., “Problem loading Fast MA data!”) for trade tracking, like navigation diagnostics.

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

Conclusion

We’ve engineered a 2MA Crossover Navigator that automates trend trading with precision, like a master-crafted navigation system. 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 ambition. Whether you’re a novice navigator or a seasoned market strategist, this EA empowers you to conquer trends with confidence. Ready to trade? Watch our video guide on the website for a step-by-step creation process. Now, navigate your trading legacy 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!