Viewing the resource: Crafting an Envelopes Cosmic Trader with MQL5 🌌

Crafting an Envelopes Cosmic Trader with MQL5 🌌

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

Introduction

Greetings, forex radar operators! Picture the forex market as a vast cosmos, with prices weaving through space like starships testing the edges of their orbits. The Envelopes EA is your cosmic radar system, an MQL5 bot that uses a 14-period Simple Moving Average (SMA) Envelopes indicator with 0.5% deviation bands to detect price reversals. When prices cross back inside these bands, it triggers automated buy or sell trades with a fixed 1-lot size, 300-pip stop loss, and 300-pip take profit, like locking onto a starship’s return to safe coordinates. This article is your radar log, guiding you through the code with crystal-clear detail for beginners, a flow smoother than a meteor shower, and examples—like trading EURUSD reversals—to keep you engaged. We’ll quote variables (e.g., "UpperEnv") and functions (e.g., "OnInit()") for clarity, balancing pro insights with a sprinkle of charm. Ready to scan the market boundaries? Let’s launch this cosmic trader!

Strategy Blueprint

The Envelopes EA automates mean-reversion trades:

  • Reversal Detection: A close below the upper Envelope band (after being above it) signals a sell; a close above the lower band (after being below it) signals a buy.

  • Trade Execution: Opens 1-lot trades at market price with a 300-pip stop loss and 300-pip take profit.

  • Purpose: Capitalizes on price reversals when the market returns to the SMA, like a starship correcting its orbit.

  • Features: Processes new bars only, with robust error handling and resource cleanup for reliability. It’s like a cosmic radar, tracking price boundaries to guide trades with precision in the forex galaxy.

Code Implementation

Let’s navigate the MQL5 code like radar operators scanning the cosmos, building our trading EA step by step. We’ll flow from setting up the radar to detecting reversals, executing trades, and shutting down cleanly, with transitions as seamless as a galactic drift. 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: Setting Up the Cosmic Radar—Initializing the EA

We start by assembling our radar system, configuring the Envelopes indicator and trade setup.

//+------------------------------------------------------------------+
//|                                                 ENVELOPES EA.mq5 |
//|      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 handleEnv;
double UpperEnv[],LowerEnv[];

int OnInit(){
   handleEnv = iEnvelopes(_Symbol,_Period,14,0,MODE_SMA,PRICE_CLOSE,0.5);
   if (handleEnv == INVALID_HANDLE){
      Print("UNABLE TO CREATE THE INDICATOR HANDLE. REVERTING NOW");
      return (INIT_FAILED);
   }
   ArraySetAsSeries(UpperEnv,true);
   ArraySetAsSeries(LowerEnv,true);
   return(INIT_SUCCEEDED);
}

We set up our radar with a #property header, updated to your preferred metadata for 2024 with a YouTube link, like powering up our cosmic sensors. We include "Trade/Trade.mqh" for trading via "obj_Trade", define the Envelopes handle ("handleEnv") and buffers ("UpperEnv", "LowerEnv") for band data. In "OnInit()", we initialize the Envelopes indicator with "iEnvelopes()", using a 14-period SMA, 0.5% deviation, and close price, checking for validity with INVALID_HANDLE. We configure buffers as time series with "ArraySetAsSeries()", and return INIT_SUCCEEDED, signaling, “Radar online, ready to scan!” This primes the EA for boundary detection, like aligning a radar dish for a galactic mission.

Step 2: Scanning the Boundaries—Detecting Price Reversals

We scan for price crossings of the Envelope bands, identifying reversal signals, like tracking a starship’s drift.

void OnTick(){
   if (CopyBuffer(handleEnv,0,0,3,UpperEnv) < 3){
      Print("NO ENOUGH DATA FROM THE UPPER ENV. REVERTING NOW");
      return;
   }
   if (CopyBuffer(handleEnv,1,0,3,LowerEnv) < 3){
      Print("NO ENOUGH DATA FROM THE LOWER ENV. REVERTING NOW");
      return;
   }
   
   static int prevBars = 0;
   int currBars = iBars(_Symbol,_Period);
   if (prevBars == currBars) return;
   prevBars = currBars;
   
   double close1 = iClose(_Symbol,_Period,1);
   double close2 = iClose(_Symbol,_Period,2);

   if (close1 < UpperEnv[0] && close2 > UpperEnv[1]){
      Print("SELL SIGNAL @ ",TimeCurrent());
      obj_Trade.Sell(1,_Symbol,Bid,Bid+300*_Point,Bid-300*_Point);
   }
   else if (close1 > LowerEnv[0] && close2 < LowerEnv[1]){
      Print("BUY SIGNAL @ ",TimeCurrent());
      obj_Trade.Buy(1,_Symbol,Ask,Ask-300*_Point,Ask+300*_Point);
   }
}

In "OnTick()", we load 3 bars of data for upper ("UpperEnv") and lower ("LowerEnv") bands with "CopyBuffer()", checking for sufficiency and logging errors with "Print()". We ensure new-bar processing using "iBars()", "prevBars", and "currBars", like scanning at regular intervals. We grab closing prices for bars 1 and 2 with "iClose()". For a sell, we check if "close1 < UpperEnv[0]" (below upper band) and "close2 > UpperEnv[1]" (previously above), logging with "Print()", "TimeCurrent()", and triggering "obj_Trade.Sell()". For a buy, we check "close1 > LowerEnv[0]" (above lower band) and "close2 < LowerEnv[1]" (previously below), triggering "obj_Trade.Buy()". This is like detecting a EURUSD close below the upper band at 1.2050 after being above it, signaling a sell reversal.

Step 3: Locking Onto Signals—Executing Trades

With reversals detected, we execute trades with precise parameters, like launching a starship on a confirmed course.

void OnTick(){
   // ... (data loading and signal logic)
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   
   if (close1 < UpperEnv[0] && close2 > UpperEnv[1]){
      Print("SELL SIGNAL @ ",TimeCurrent());
      obj_Trade.Sell(1,_Symbol,Bid,Bid+300*_Point,Bid-300*_Point);
   }
   else if (close1 > LowerEnv[0] && close2 < LowerEnv[1]){
      Print("BUY SIGNAL @ ",TimeCurrent());
      obj_Trade.Buy(1,_Symbol,Ask,Ask-300*_Point,Ask+300*_Point);
   }
}

The trade execution logic uses "obj_Trade.Buy()" or "obj_Trade.Sell()", opening 1-lot trades at the ask (buy) or bid (sell) price via "SymbolInfoDouble()", "NormalizeDouble()", setting a 300-pip stop loss ("Ask-300*_Point", "Bid+300*_Point") and 300-pip take profit ("Ask+300*_Point", "Bid-300*_Point") with "_Point". For example, a sell on GBPUSD at 1.3500 sets a stop loss at 1.3800 and take profit at 1.3200, logging “SELL SIGNAL @ 2025.06.21 10:00” for transparency, like filing a mission report.

Step 4: Shutting Down the Radar—Cleaning Up Resources

When the mission ends, we power down the radar, freeing resources cleanly.

void OnDeinit(const int reason){
   IndicatorRelease(handleEnv);
   ArrayFree(UpperEnv);
   ArrayFree(LowerEnv);
}

In "OnDeinit()", we use "IndicatorRelease()" to free "handleEnv" and "ArrayFree()" to clear "UpperEnv", "LowerEnv", like shutting down radar sensors. This ensures no memory leaks, leaving the chart clean for the next mission, like docking a starship after a scan.

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

This EA is a mean-reversion legend, detecting price reversals with Envelopes like a radar tracking starship drifts. Its automated execution and balanced risk management make it reliable, ready for tweaks like adjustable lot sizes. Example? Catch a buy on EURUSD at 1.1950 after crossing above the lower band, nabbing 200 pips as prices revert—pure cosmic gold! Beginners can follow, and pros can enhance it, making it a must-have for automated reversal traders.

Putting It All Together

To launch this EA:

  1. Open MetaEditor in MetaTrader 5 like powering up a radar station.

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

  3. Drop the EA on your chart, enable AutoTrading, and watch it open buy/sell trades based on Envelope crossovers.

  4. Monitor logs for signal timestamps to track trade triggers, like reviewing radar pings.

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

Conclusion

We’ve crafted an Envelopes cosmic trader that automates price reversal trades with precision, guided by the Envelopes indicator. This MQL5 code is our radar system, explained with detail to make you a market operator, a touch of charm to keep you engaged, and flow to carry you like a galactic drift. Ready to scan? Check our video guide on the website for a front-row seat to this cosmic trading mission. Now go track those market boundaries! 🌌

Disclaimer: Trading’s like scanning the cosmos—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!