Viewing the resource: SAR and EMA Trend Trading System in MQL5

SAR and EMA Trend Trading System in MQL5

Allan Munene Mutiiria 2025-06-26 00:44:27 86 Views
This MQL5 EA combines 10/20-period EMAs and SAR (0.02, 0.2) to trade trend reversals, opening 0.01-l...

Introduction

Picture aligning your trades with market trends with the precision of a master navigator, using a synergy of indicators to confirm direction and capitalize on reversals. The SAR + EMA EA is your advanced trend alignment tool, designed to automate trading by integrating a 10-period and 20-period Exponential Moving Average (EMA, "handleEMA10", "handleEMA20", "iMA()") with the Parabolic Stop and Reverse (SAR, "handleSAR", "iSAR()", step 0.02, maximum 0.2). A buy signal triggers when the 10-period EMA crosses above the 20-period EMA ("ema10_data[0] > ema20_data[0]", "ema10_data[1] < ema20_data[1]") and the SAR is below the current low ("sar_data[0] < low0"), opening a 0.01-lot buy ("obj_Trade.Buy()") with a 300-pip stop loss and take profit ("Ask-300*_Point", "Ask+300*_Point"). A sell signal occurs with the reverse conditions ("ema10_data[0] < ema20_data[0]", "sar_data[1] > high0"). Trades are limited to one per bar ("signalTime", "iTime()") and only when no positions are open ("PositionsTotal()==0"). This strategy suits traders targeting trending markets, requiring careful risk management due to fixed risk parameters.

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

Strategy Blueprint

Let’s outline the EA’s trend alignment framework, like drafting specifications for a navigation system:

  • Indicator Setup: Initializes a 10-period EMA, 20-period EMA ("iMA()", "handleEMA10", "handleEMA20"), and SAR (0.02, 0.2, "iSAR()", "handleSAR") for trend detection.

  • Signal Detection: Triggers a buy when the 10-EMA crosses above the 20-EMA ("ema10_data[0] > ema20_data[0]", "ema10_data[1] < ema20_data[1]") and SAR is below the low ("sar_data[0] < low0"); sells when the 10-EMA crosses below the 20-EMA and SAR is above the high ("sar_data[0] > high0"), using "CopyBuffer()", "iLow()", "iHigh()".

  • Trade Execution: Opens 0.01-lot buy/sell trades ("obj_Trade.Buy()", "obj_Trade.Sell()") with 300-pip stop losses and take profits ("Ask-300*_Point", "Bid+300*_Point").

  • Trade Limitation: Restricts trades to one per bar ("signalTime", "iTime()") and no open positions ("PositionsTotal()==0").

  • Execution: Processes signals on each tick ("OnTick()") with data from "SymbolInfoDouble()".

  • Enhancements: Adding a magic number, configurable SL/TP, or trend filters could improve control and adaptability. This framework automates trend trading with precision, leveraging EMA crossovers and SAR for robust signals.

Code Implementation

Let’s step into the trend alignment control room and dissect the MQL5 code that powers this SAR + EMA 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, and cleanup, with detailed explanations and examples—like trading 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 trend-trading project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the trading system, initializing EMA and SAR indicators for trend detection.

//+------------------------------------------------------------------+
//|                                                    SAR + EMA.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 handleEMA10, handleEMA20, handleSAR;
double ema10_data[],ema20_data[],sar_data[];

int OnInit(){
   handleEMA10 = iMA(_Symbol,_Period,10,0,MODE_EMA,PRICE_CLOSE);
   handleEMA20 = iMA(_Symbol,_Period,20,0,MODE_EMA,PRICE_CLOSE);
   handleSAR = iSAR(_Symbol,_Period,0.02,0.2);
   if (handleEMA10 == INVALID_HANDLE || handleEMA20 == INVALID_HANDLE || handleSAR == INVALID_HANDLE){
      Print("ERROR CREATING THE IND HANDLES. REVERTING NOW");
      return (INIT_FAILED);
   }
   ArraySetAsSeries(ema10_data,true);
   ArraySetAsSeries(ema20_data,true);
   ArraySetAsSeries(sar_data,true);
   return(INIT_SUCCEEDED);
}

The system begins with the #property header, establishing copyright and contact details, like calibrating a trend alignment system’s core. The "OnInit()" function initializes the setup, including "Trade/Trade.mqh" for trading via "obj_Trade". It creates handles for a 10-period EMA ("handleEMA10", "iMA()", close price), a 20-period EMA ("handleEMA20"), and SAR ("handleSAR", "iSAR()", step 0.02, maximum 0.2). Data arrays ("ema10_data", "ema20_data", "sar_data") are set as time series ("ArraySetAsSeries()") for storage. If any handle fails ("INVALID_HANDLE"), it logs with "Print()" and returns "INIT_FAILED". Returning INIT_SUCCEEDED signals, “System is ready, let’s align with trends!” This primes the EA for trend-based trading, like a navigation tool poised for action.

Phase 2: Mapping Trend Signals—Loading Indicator Data

With the system active, we load EMA and SAR data to detect trend signals, like scanning for aligned market cues.

void OnTick(){
   if (CopyBuffer(handleEMA10,0,0,3,ema10_data) < 3){
      Print("UNABLE TO COPY DATA FROM EMA 10 FOR FURTHER ANALYSIS. REVERTING");
      return;
   }
   if (CopyBuffer(handleEMA20,0,0,3,ema20_data) < 3){return;}
   if (CopyBuffer(handleSAR,0,0,3,sar_data) < 3){return;}
   double low0 = iLow(_Symbol,_Period,0);
   double high0 = iHigh(_Symbol,_Period,0);
   datetime currBarTime0 = iTime(_Symbol,_Period,0);
   static datetime signalTime = currBarTime0;
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

In the signal mapping hub, "OnTick()" runs every tick, loading 3 bars of data for the 10-period EMA ("ema10_data", "CopyBuffer()", "handleEMA10"), 20-period EMA ("ema20_data", "handleEMA20"), and SAR ("sar_data", "handleSAR"). It exits with "Print()" for EMA10 failures or silently for others ("< 3") if data is insufficient. It fetches the current low ("low0", "iLow()") and high ("high0", "iHigh()") and tracks bar time ("currBarTime0", "iTime()", "signalTime") for trade limits. Ask and bid prices ("Ask", "Bid", "SymbolInfoDouble()", "NormalizeDouble()") are retrieved. For example, on EURUSD H1, it loads EMA10=1.2005, EMA20=1.2000, SAR=1.1995, low=1.2000, high=1.2010, preparing for signal detection, like aligning navigational instruments.

Phase 3: Navigating Trades—Executing Trend Signals

With data loaded, we execute trades based on EMA crossovers and SAR confirmation, like locking onto a trend course.

void OnTick(){
   // ... (data loading)
   if (ema10_data[0] > ema20_data[0] && ema10_data[1] < ema20_data[1]
      && sar_data[0] < low0 && signalTime != currBarTime0){
      Print("BUY SIGNAL @ ",TimeCurrent());
      signalTime = currBarTime0;
      if (PositionsTotal()==0){
         obj_Trade.Buy(0.01,_Symbol,Ask,Ask-300*_Point,Ask+300*_Point);
      }
   }
   else if (ema10_data[0] < ema20_data[0] && ema10_data[1] > ema20_data[1]
      && sar_data[0] > high0 && signalTime != currBarTime0){
      Print("SELL SIGNAL @ ",TimeCurrent());
      signalTime = currBarTime0;
      if (PositionsTotal()==0){
         obj_Trade.Sell(0.01,_Symbol,Bid,Bid+300*_Point,Bid-300*_Point);
      }
   }
}

In the trade navigation hub, "OnTick()" checks for signals. A buy signal triggers when the 10-EMA crosses above the 20-EMA ("ema10_data[0] > ema20_data[0]", "ema10_data[1] < ema20_data[1]"), SAR is below the low ("sar_data[0] < low0"), and it’s a new bar ("signalTime != currBarTime0"). If no positions exist ("PositionsTotal()==0"), it opens a 0.01-lot buy ("obj_Trade.Buy()") at ask ("Ask") with a 300-pip stop loss ("Ask-300*_Point") and take profit ("Ask+300*_Point"), logging with "Print()". A sell signal mirrors this: 10-EMA below 20-EMA, SAR above high ("sar_data[0] > high0"), opening a sell ("obj_Trade.Sell()") at bid ("Bid"). For example, on EURUSD H1, a 10-EMA crossover from 1.1998 to 1.2005 above 20-EMA, with SAR at 1.1995 below low=1.2000, triggers a buy at 1.2007, stop loss at 1.1707, take profit at 1.2307, like aligning with a bullish trend.

Phase 4: Shutting Down the System—Cleaning Up Resources

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

void OnDeinit(const int reason){
}

In the shutdown control room, "OnDeinit()" is empty, leaving indicator handles active, like a running navigation system. Adding cleanup would ensure a clean slate:

IndicatorRelease(handleEMA10);
IndicatorRelease(handleEMA20);
IndicatorRelease(handleSAR);
ArrayFree(ema10_data);
ArrayFree(ema20_data);
ArrayFree(sar_data);

This would release handles ("IndicatorRelease()", "handleEMA10", "handleEMA20", "handleSAR") and free arrays ("ArrayFree()", "ema10_data", "ema20_data", "sar_data"), like dismantling a trend alignment system, ready for the next task.

Why This EA is a Trend Alignment Triumph

The SAR + EMA EA is a trend-following triumph, automating trades with precision, like a master-crafted navigation engine. Its EMA crossovers ("ema10_data", "ema20_data") and SAR confirmation ("sar_data") offer robust signals, with disciplined risk parameters ("300*_Point") and trade limits ("signalTime", "PositionsTotal()"). Potential enhancements like magic numbers or configurable SL/TP could further refine it. Picture a buy on EURUSD at 1.2007 with SAR below the low—strategic brilliance! Beginners will value the clear signals, while experts can enhance 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 trend alignment control room.

  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 SAR and EMA-based trades.

  4. Monitor logs (e.g., “BUY SIGNAL @ 2025.06.26 00:00:00”) for trade tracking, like navigation diagnostics.

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

Conclusion

We’ve engineered a SAR + EMA Trader 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 align with trends with confidence. Ready to trade? Watch our video guide on the website for a step-by-step creation process. Now, chart your trading course 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!