Viewing the resource: BB + Stochastic EA: Master Mean-Reversion Trades

BB + Stochastic EA: Master Mean-Reversion Trades

Allan Munene Mutiiria 2025-06-20 22:58:50 80 Views
Join our fun, newbie-friendly guide to the BB + Stochastic EA MQL5 code! We’ll explain every funct...

Introduction

Hey there, future forex swing master! Picture the forex market as a playground swing, swaying too far before snapping back to center. The BB + Stochastic EA is your coach, combining Bollinger Bands’ volatility zones with the Stochastic oscillator’s momentum signals to catch those perfect mean-reversion moments. This article is your playbook, guiding you through the MQL5 code on MetaTrader 5 with vivid detail. We’ll explain every major function like you’re new to coding (no judgment!), blending humor and flow like a storyteller at a campfire. By the end, you’ll be ready to let this Expert Advisor (EA) trade market swings for you. Let’s hit the playground!

Strategy Blueprint

The BB + Stochastic EA leverages two powerful indicators:

  • Bollinger Bands: A 20-period simple moving average (SMA) with Upper and Lower Bands (two standard deviations away), marking overbought (above Upper) and oversold (below Lower) zones.

  • Stochastic Oscillator: An 8-period, 3,3 SMA-based indicator (using low/high prices) to measure momentum. Below 20 signals oversold; above 80 signals overbought.

The EA buys when the price dips below the Lower Band and the Stochastic crosses above 20, confirming oversold conditions. It sells when the price rises above the Upper Band and the Stochastic crosses below 80, signaling overbought conditions. Trades use a 0.01-lot size with 300-pip stop loss and take profit, executed only when no positions are open and on new candles. It’s like catching the swing at its extremes with a safety net. See below.

Code Implementation

Let’s dive into the MQL5 code like kids chasing a swing, crafting a narrative that flows seamlessly from setup to trading. We’ll present each major function in full, explaining every key function in detail for clarity, and quoting variables (e.g., "bb_upperDATA") and functions (e.g., "OnInit()") to keep it beginner-friendly. Our goal is to make the code as inviting as a sunny playground, guiding you through every move with ease.

Setting the Playground: Header, Includes, and Global Variables

We start by setting up the equipment, like assembling a swing set before playtime.

//+------------------------------------------------------------------+
//|                                                   BB + STOCH.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 handleBB, handleSTOCH;

double bb_upperDATA[], bb_lowerDATA[], stochDATA[];

This opening sets the stage. The header declares the EA as “BB + STOCH,” crafted by Allan in 2025, with a link to your Telegram channel and version 1.00. The #include <Trade/Trade.mqh> directive imports the MQL5 trade library, enabling trade execution. The "CTrade" class creates an object named "obj_Trade", your trading assistant for opening buy and sell orders.

Globally, we define:

  • "handleBB", "handleSTOCH": Integers to store the Bollinger Bands and Stochastic indicator handles, like keys to access their data.

  • "bb_upperDATA[]", "bb_lowerDATA[]": Arrays for the Upper and Lower Bollinger Band values.

  • "stochDATA[]": An array for the Stochastic oscillator’s main line values.

These globals are like your playground gear, ready for the EA to swing into action.

Prepping the Swing: OnInit Function

Next, we set up the indicators, like tuning the swing for a perfect ride.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){
   
   handleBB = iBands(_Symbol,_Period,20,0,2,PRICE_CLOSE);
   handleSTOCH = iStochastic(_Symbol,_Period,8,3,3,MODE_SMA,STO_LOWHIGH);
   
   if (handleBB == INVALID_HANDLE || handleSTOCH == INVALID_HANDLE){
      Print("UNABLE TO INITIALIZE THE IND HANDLES. REVERTING NOW");
      return (INIT_FAILED);
   }
   
   ArraySetAsSeries(bb_lowerDATA,true);
   ArraySetAsSeries(bb_upperDATA,true);
   ArraySetAsSeries(stochDATA,true);

   return(INIT_SUCCEEDED);
}

The "OnInit()" function is the EA’s pre-game warm-up, running when you attach it to a chart. Let’s break down its key functions:

  • "iBands()": Creates the Bollinger Bands indicator for the current symbol ("_Symbol", e.g., EURUSD) and timeframe ("_Period", e.g., H1). It uses a 20-period SMA, 0 shift, 2 standard deviations, and close price ("PRICE_CLOSE"). The handle is stored in "handleBB".

  • "iStochastic()": Creates the Stochastic oscillator with parameters: 8-period %K, 3-period %D, 3-period slowing, SMA method ("MODE_SMA"), and low/high price ("STO_LOWHIGH"). The handle is stored in "handleSTOCH".

  • "Print()": Logs a message to the MetaTrader 5 journal, reporting if either indicator fails to initialize.

  • "ArraySetAsSeries()": Configures the "bb_upperDATA[]", "bb_lowerDATA[]", and "stochDATA[]" arrays as time series, so index 0 holds the latest value, like sorting your swing scores newest first.

  • "INVALID_HANDLE": A constant (-1) indicating a failed indicator load. If either handle is invalid, the EA logs an error and exits with INIT_FAILED.

  • INIT_FAILED, INIT_SUCCEEDED: Constants for initialization failure or success, controlling whether the EA stops or proceeds.

If all goes well, it returns INIT_SUCCEEDED, signaling, “Swing’s ready!” This function ensures both indicators are loaded and arrays are prepped.

Clearing the Playground: OnDeinit Function

When playtime ends, this function tidies up.

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

The "OnDeinit()" function is the EA’s cleanup crew, called when you remove it from the chart. It’s empty here, like a playground left spotless. No cleanup is needed since the indicators and trades are managed by MetaTrader 5, keeping things light.

Swinging into Action: OnTick Function

Now we hit the EA’s core, where it trades mean-reversion on every price tick.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){
   
   if (CopyBuffer(handleBB,UPPER_BAND,0,3,bb_upperDATA) < 3){
      Print("NOT ENOUGH DATA FROM UPPER BAND FOR FURTHER ANALYSIS. REVERTING");
      return;
   }
   if (CopyBuffer(handleBB,LOWER_BAND,0,3,bb_lowerDATA) < 3){return;}
   if (CopyBuffer(handleSTOCH,0,0,3,stochDATA) < 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);

   if (stochDATA[0] > 20 && stochDATA[1] < 20 && low0 < bb_lowerDATA[0]
      && 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 (stochDATA[0] < 80 && stochDATA[1] > 80 && high0 > bb_upperDATA[0]
      && signalTime != currBarTime0){
      Print("SELL SIGNAL @ ",TimeCurrent());
      signalTime = currBarTime0;
      if (PositionsTotal()==0){
         obj_Trade.Sell(0.01,_Symbol,Bid,Bid+300*_Point,Bid-300*_Point);
      }
   }
}

The "OnTick()" function is the EA’s swing session, running on every price tick to catch mean-reversion trades. It’s the heart of the strategy, so let’s unpack it with detail, explaining each major function:

  • "CopyBuffer()": Copies data from the indicators into arrays. It pulls three values from the Bollinger Bands’ Upper Band ("UPPER_BAND", "bb_upperDATA[]"), Lower Band ("LOWER_BAND", "bb_lowerDATA[]"), and Stochastic’s main line (buffer 0, "stochDATA[]"). If fewer than three values are retrieved for the Upper Band, it logs an error with "Print()". If any fails, the EA exits to ensure reliable data.

  • "iLow()", "iHigh()": Retrieve the low and high prices of the current candle (index 0), stored in "low0" and "high0", to compare with Bollinger Bands.

  • "iTime()": Gets the timestamp of the current candle, stored in "currBarTime0", to ensure trades only trigger on new candles.

  • Signal Timing Logic: A static "signalTime" variable, initialized to "currBarTime0", tracks the last signal’s timestamp. If "signalTime" matches "currBarTime0", the EA skips to avoid duplicate trades.

  • "SymbolInfoDouble()": Retrieves real-time market data, grabbing the ask price ("SYMBOL_ASK") for buying and bid price ("SYMBOL_BID") for selling, stored in "Ask" and "Bid".

  • "NormalizeDouble()": Rounds prices (e.g., "Ask", "Bid") to the symbol’s decimal places ("_Digits", e.g., 5 for EURUSD), ensuring trade-ready formatting.

  • "PositionsTotal()": Returns the total number of open positions, used to ensure no positions are open before trading.

  • Buy Signal Logic: If the Stochastic crosses above 20 ("stochDATA[0] > 20", "stochDATA[1] < 20"), the price is below the Lower Band ("low0 < bb_lowerDATA[0]"), it’s a new candle ("signalTime != currBarTime0"), and no positions are open ("PositionsTotal()==0"), the EA logs “BUY SIGNAL” with "Print()", updates "signalTime", and opens a buy trade with "obj_Trade.Buy()". It uses 0.01 lots, "Ask" price, a 300-pip stop loss ("Ask-300*_Point"), and a 300-pip take profit ("Ask+300*_Point").

  • Sell Signal Logic: If the Stochastic crosses below 80 ("stochDATA[0] < 80", "stochDATA[1] > 80"), the price is above the Upper Band ("high0 > bb_upperDATA[0]"), it’s a new candle, and no positions are open, the EA logs “SELL SIGNAL”, updates "signalTime", and opens a sell trade with "obj_Trade.Sell()", using 0.01 lots, "Bid" price, a 300-pip stop loss ("Bid+300*_Point"), and a 300-pip take profit ("Bid-300*_Point").

  • "TimeCurrent()": Returns the current server time, used in "Print()" to log signal timestamps.

  • "Buy()", "Sell()": Methods of the "CTrade" class, opening buy or sell trades with parameters like lot size (0.01), symbol ("_Symbol"), price, stop loss, and take profit.

  • "_Point": A built-in variable for the symbol’s pip size, used to calculate stop loss and take profit distances.

This function flows from fetching data to checking signals and executing trades, like a swing catching the perfect moment to soar.

Putting It All Together

To launch this EA:

  1. Open MetaEditor in MetaTrader 5.

  2. Paste the code into a new Expert Advisor file.

  3. Compile (F5). If errors appear, double-check your copy-paste.

  4. Drag the EA onto your chart, enable AutoTrading, and watch for buy or sell trades.

  5. Trade smart—don’t bet your playground gear on one swing!

Conclusion

The BB + Stochastic EA is your mean-reversion coach, blending Bollinger Bands and Stochastic to catch market swings. We’ve explored its MQL5 code with clear, detailed explanations, so you understand every move like a seasoned pro. Now you’re set to automate your trades and ride the market’s rhythm. Want to see it in action? Check our video tutorial on the website!

Disclaimer: Trading’s like swinging on a high rope—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!