Viewing the resource: Crafting an EMA Stoch RSI Galactic Trader with MQL5 🚀

Crafting an EMA Stoch RSI Galactic Trader with MQL5 🚀

Allan Munene Mutiiria 2025-06-21 17:22:29 98 Views
Join us for a detailed, professional, and engaging journey through our MQL5 code that automates fore...

Introduction

Greetings, forex navigators! Picture the forex market as a vast galaxy, with prices zipping like starships through turbulent starfields. The EMA Stoch RSI EA is your advanced navigation system, an MQL5 bot that combines a 5-period fast EMA, 10-period slow EMA, Stochastic (5,3,3), and RSI (14) to automate buy and sell trades with precision. It detects EMA crossovers, filters entries with Stochastic and RSI, and executes trades with a fixed 0.01 lot, 400-pip stop loss, and 200-pip take profit, like plotting a course through the cosmos. This article is your navigator’s log, guiding you through the code with crystal-clear detail for beginners, a flow smoother than a warp drive, and examples—like trading EURUSD trends—to keep you engaged. We’ll quote variables (e.g., "bufferFast") and functions (e.g., "OnInit()") for clarity, balancing pro insights with a sprinkle of charm. Ready to chart the stars? Let’s launch this galactic trader!

Strategy Blueprint

The EMA Stoch RSI EA automates trend-following trades:

  • Trend Detection: A 5-period fast EMA crossing above a 10-period slow EMA signals a buy; crossing below signals a sell.

  • Entry Filters: Stochastic (5,3,3) must be below 80 for buys, above 20 for sells; RSI (14) must be above 50 for buys, below 50 for sells.

  • Trade Execution: Opens 0.01-lot trades with a 400-pip stop loss and 200-pip take profit, using a unique magic number (123) for tracking.

  • Features: Processes new bars only, ensuring robust indicator data with error handling and cleanup. It’s like a starship navigation system, guiding trades through trending markets with triple-checked precision.

Code Implementation

Let’s navigate the MQL5 code like starship pilots plotting a course through the galaxy, building our trading EA step by step. We’ll flow from rigging the navigation system to detecting trends, executing trades, and docking cleanly, with transitions as seamless as a hyperspace jump. Each section includes code blocks, detailed explanations of what we’re doing, and examples to keep you engaged, all while staying beginner-friendly and professional.

Step 1: Rigging the Navigation System—Initializing the EA

We start by assembling our starship’s navigation system, setting up indicators and trade parameters.

//+------------------------------------------------------------------+
//|      Copyright 2024, ALLAN MUNENE MUTIIRIA. #@Forex Algo-Trader. |
//|                           https://youtube.com/@ForexAlgo-Trader? |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, ALLAN MUNENE MUTIIRIA. #@Forex Algo-Trader"
#property link      "https://youtube.com/@ForexAlgo-Trader?"
#property description "======= IMPORTANT =======\n"
#property description "1. This is a FREE EA."
#property description "2. To get the source code of the EA, follow the Copyright link."
#property description "3. Incase of anything, contact developer via the link provided."
#property description "Hope you will enjoy the EA Logic.\n"
#property description "*** HAPPY TRADING! ***"
#property version   "1.00"

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

int handleFast;      double bufferFast[];
int handleSlow;      double bufferSlow[];
int handleStoch;     double bufferStoch[];
int handleRSI;       double bufferRSI[];

int magic_no = 123;
int totalBARS = 0;

int OnInit(){
   handleFast = iMA(_Symbol,_Period,5,0,MODE_EMA,PRICE_CLOSE);
   if (handleFast==INVALID_HANDLE) return(INIT_FAILED);
   handleSlow = iMA(_Symbol,_Period,10,0,MODE_EMA,PRICE_CLOSE);
   if (handleSlow==INVALID_HANDLE) return(INIT_FAILED);
   handleStoch = iStochastic(_Symbol,_Period,5,3,3,MODE_SMA,STO_LOWHIGH);
   if (handleStoch==INVALID_HANDLE) return(INIT_FAILED);
   handleRSI = iRSI(_Symbol,_Period,14,PRICE_CLOSE);
   if (handleRSI==INVALID_HANDLE) return(INIT_FAILED);
   
   ArraySetAsSeries(bufferFast,true);
   ArraySetAsSeries(bufferSlow,true);
   ArraySetAsSeries(bufferStoch,true);
   ArraySetAsSeries(bufferRSI,true);
   
   obj_Trade.SetExpertMagicNumber(magic_no);
   return(INIT_SUCCEEDED);
}

We rig our navigation system with a #property header, declaring the EA as a free offering by Allan in 2024 with a YouTube link, like powering up our starship’s consoles. We include "Trade/Trade.mqh" for trading via "obj_Trade", define indicator handles ("handleFast", "handleSlow", "handleStoch", "handleRSI") and buffers ("bufferFast", "bufferSlow", "bufferStoch", "bufferRSI"), and set a "magic_no" (123) for trade tracking. In "OnInit()", we initialize indicators with "iMA()", "iStochastic()", "iRSI()", checking for validity with INVALID_HANDLE, configure buffers as time series using "ArraySetAsSeries()", and set the magic number with "SetExpertMagicNumber()". Returning INIT_SUCCEEDED signals, “Navigation system online, ready to chart!” This primes the EA for trend detection, like calibrating sensors for a galactic voyage.

Step 2: Scanning the Starfield—Detecting Trends and Filters

We scan for EMA crossovers, applying Stochastic and RSI filters to confirm trade signals, like spotting a new star’s trajectory.

void OnTick(){
   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;
   }
   if (!CopyBuffer(handleStoch,MAIN_LINE,1,2,bufferStoch)){
      Print("Problem Loading Stochastic data!!!");
      return;
   }
   if (!CopyBuffer(handleRSI,0,1,2,bufferRSI)){
      Print("Problem Loading RSI data!!!");
      return;
   }
   
   double fastMA1 = bufferFast[0];     double slowMA1 = bufferSlow[0];
   double fastMA2 = bufferFast[1];     double slowMA2 = bufferSlow[1];
   
   if (fastMA1 > slowMA1 && !(fastMA2 > slowMA2)){
      if (bufferStoch[0] < 80){
         if (bufferRSI[0] > 50){
            Print("Stoch = ",NormalizeDouble(bufferStoch[0],2),
                  ", RSI = ",NormalizeDouble(bufferRSI[0],2));
            double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
            obj_Trade.Buy(0.01,_Symbol,ask,ask-400*_Point,ask+200*_Point);
         }
      }
   }
   else if (fastMA1 < slowMA1 && !(fastMA2 < slowMA2)){
      if (bufferStoch[0] > 20){
         if (bufferRSI[0] < 50){
            Print("Stoch = ",NormalizeDouble(bufferStoch[0],2),
                  ", RSI = ",NormalizeDouble(bufferRSI[0],2));
            double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
            obj_Trade.Sell(0.01,_Symbol,bid,bid+400*_Point,bid-200*_Point);
         }
      }
   }
}

In "OnTick()", we check for new bars with "iBars()", "totalBARS" to avoid duplicate processing, like scanning the starfield at regular intervals. We load indicator data with "CopyBuffer()", fetching 3 bars for EMAs ("bufferFast", "bufferSlow"), 2 bars for Stochastic ("bufferStoch", main line) and RSI ("bufferRSI") starting at bar 1, with error handling via "Print()". For buys, we check if "fastMA1 > slowMA1" and "!(fastMA2 > slowMA2)" (EMA crossover), "bufferStoch[0] < 80" (not overbought), and "bufferRSI[0] > 50" (bullish momentum), logging values with "Print()", "NormalizeDouble()", and opening a buy with "obj_Trade.Buy()", 0.01 lots, 400-pip stop loss, and 200-pip take profit via "SymbolInfoDouble()", "_Point". Sells reverse this logic: "fastMA1 < slowMA1", "!(fastMA2 < slowMA2)", "bufferStoch[0] > 20", "bufferRSI[0] < 50", using "obj_Trade.Sell()". This is like detecting a bullish EMA crossover on EURUSD at 1.2000 with Stochastic at 65 and RSI at 55, launching a buy trade.

Step 3: Plotting the Course—Executing Trades

With signals confirmed, we execute trades with precise parameters, like launching a starship on a calculated trajectory.

void OnTick(){
   // ... (indicator loading and signal logic)
   if (fastMA1 > slowMA1 && !(fastMA2 > slowMA2)){
      if (bufferStoch[0] < 80){
         if (bufferRSI[0] > 50){
            Print("Stoch = ",NormalizeDouble(bufferStoch[0],2),
                  ", RSI = ",NormalizeDouble(bufferRSI[0],2));
            double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
            obj_Trade.Buy(0.01,_Symbol,ask,ask-400*_Point,ask+200*_Point);
         }
      }
   }
   else if (fastMA1 < slowMA1 && !(fastMA2 < slowMA2)){
      if (bufferStoch[0] > 20){
         if (bufferRSI[0] < 50){
            Print("Stoch = ",NormalizeDouble(bufferStoch[0],2),
                  ", RSI = ",NormalizeDouble(bufferRSI[0],2));
            double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
            obj_Trade.Sell(0.01,_Symbol,bid,bid+400*_Point,bid-200*_Point);
         }
      }
   }
}

The trade execution logic uses "obj_Trade.Buy()" or "obj_Trade.Sell()", opening 0.01-lot trades at the ask (buy) or bid (sell) price, setting a 400-pip stop loss ("ask-400*_Point", "bid+400*_Point") and 200-pip take profit ("ask+200*_Point", "bid-200*_Point"). The "magic_no" (123) ensures trade tracking, like tagging a starship’s mission. For example, a buy on GBPUSD at 1.3500 sets a stop loss at 1.3100 and take profit at 1.3700, logging “Stoch = 70.12, RSI = 52.34” for transparency, like filing a flight plan.

Step 4: Docking the Ship—Cleaning Up Resources

When the voyage ends, we shut down the system, freeing resources cleanly.

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

In "OnDeinit()", we use "IndicatorRelease()" to free "handleFast", "handleSlow", "handleStoch", "handleRSI", and "ArrayFree()" to clear "bufferFast", "bufferSlow", "bufferStoch", "bufferRSI", like shutting down starship sensors. This ensures no memory leaks, leaving the chart clean for the next mission.

Why This EA’s a Galactic Legend (and Keeps You Engaged!)

This EA is a trend-trading legend, combining EMA crossovers, Stochastic timing, and RSI confirmation like a triple-checked navigation system. Its automated execution and robust risk management make it reliable, ready for tweaks like adjustable lot sizes. Example? Catch a bullish EMA crossover on EURUSD at 1.2000, buy with a 400-pip stop and 200-pip target, nabbing 150 pips as the trend unfolds—pure galactic gold! Beginners can follow, and pros can enhance it, making it a must-have for automated trend traders.

Putting It All Together

To launch this EA:

  1. Open MetaEditor in MetaTrader 5 like powering up a starship.

  2. Paste the code, compile (F5), and check for typos—no navigator wants a faulty system.

  3. Drop the EA on your chart, enable AutoTrading, and watch it open buy/sell trades based on EMA, Stochastic, and RSI signals.

  4. Monitor logs for Stochastic and RSI values to understand trade triggers, like reviewing flight data.

  5. Test on a demo first—real pips deserve a practice voyage!

Conclusion

We’ve crafted an EMA Stoch RSI galactic trader that automates trend-following trades with precision, guided by EMA crossovers, Stochastic, and RSI. This MQL5 code is our navigation system, explained with detail to make you a trading pilot, a touch of charm to keep you engaged, and flow to carry you like a hyperspace jump. Ready to navigate? Check our video guide on the website for a front-row seat to this cosmic trading mission. Now go conquer those market stars! 🌌

Disclaimer: Trading’s like navigating a galaxy—thrilling but risky. Losses can exceed deposits. Test 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!