Viewing the resource: Cascade Ordering EA: Ride Trends with Moving Average Cascades

Cascade Ordering EA: Ride Trends with Moving Average Cascades

Allan Munene Mutiiria 2025-06-21 00:53:08 80 Views
Join our fun, beginner-friendly guide to the Cascade Ordering EA MQL5 code! We’ll explain every fu...

Introduction

Ahoy, future forex river runner! Picture the forex market as a rushing river, its currents carving paths of trending prices. The Cascade Ordering EA is your trusty raft, harnessing fast and slow exponential moving average (EMA) crossovers to launch buy or sell trades, then cascading new orders as profits surge, like adding rafts to ride the rapids. This article is your river map, guiding you through the MQL5 code on MetaTrader 5 with vivid detail. We’ll unpack every major function with clarity for beginners, weaving humor and flow like a tale told by a campfire. By the end, you’ll be ready to let this Expert Advisor (EA) steer your trades downstream to profit. Let’s paddle into the current!

Strategy Blueprint

The Cascade Ordering EA uses two EMAs to spot trends:

  • Fast EMA: 10-period, quick to catch price shifts.

  • Slow EMA: 20-period, tracking longer-term momentum.

A buy signal triggers when the Fast EMA crosses above the Slow EMA, signaling bullish momentum; a sell signal fires when it crosses below, indicating bearish momentum. Initial trades (0.1 lots) open with a 300-pip stop loss and take profit. When price hits the take-profit, the EA opens a new trade, shifts the take-profit 300 pips further, and adjusts all open positions’ stop losses to 100 pips from the current price, creating a cascading effect. Trades execute only on new candles with no open positions, ensuring discipline. It’s like launching a raft at a river’s bend and adding more as the current strengthens. See below.

Code Implementation

Let’s navigate the MQL5 code like rafters riding a river, unfolding the logic as a seamless journey. Our expedition starts with setting up the EA, flows to retrieving EMA data, detects crossover signals, launches initial trades, cascades new orders, and adjusts stop losses. Each function builds on the last, with transitions that keep the narrative flowing like a steady current. We’ll explain every major function in detail, quoting variables (e.g., "maFast") and functions (e.g., "OnInit()") for clarity, keeping it beginner-friendly with a playful river theme.

Launching the Raft: Header, Inputs, and Standard Functions

Our journey begins by rigging the raft, preparing the EA to ride market currents.

//+------------------------------------------------------------------+
//|                                          Cascade Ordering EA.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 handleMAFast;
int handleMASlow;

double maFast[],maSlow[];

input double LOT = 0.1;
input int tpPts = 300;
input int slPts = 300;
input int slPts_min = 100;

double takeProfit = 0;
double stopLoss = 0;

bool isBuySystemInitiated = false;
bool isSellSystemInitiated = false;

int OnInit(){
   handleMAFast = iMA(_Symbol,_Period,10,0,MODE_EMA,PRICE_CLOSE);
   if (handleMAFast == INVALID_HANDLE){
      Print("UNABLE TO LOAD FAST MA, REVERTING NOW");
      return (INIT_FAILED);
   }
   handleMASlow = iMA(_Symbol,_Period,20,0,MODE_EMA,PRICE_CLOSE);
   if (handleMASlow == INVALID_HANDLE){
      Print("UNABLE TO LOAD SLOW MA, REVERTING NOW");
      return (INIT_FAILED);
   }
   
   ArraySetAsSeries(maFast,true);
   ArraySetAsSeries(maSlow,true);

   return(INIT_SUCCEEDED);
}

The header declares the EA as “Cascade Ordering EA,” crafted by Allan in 2025, with a link to your Telegram channel and version 1.00, setting the river’s course.

  • Inputs: Define user-configurable settings: "LOT" (0.1), "tpPts" (300 pips), "slPts" (300 pips), "slPts_min" (100 pips), like a raft’s gear.

  • Globals: "handleMAFast", "handleMASlow" store EMA handles; "maFast[]", "maSlow[]" hold EMA data; "takeProfit", "stopLoss" track trade levels; "isBuySystemInitiated", "isSellSystemInitiated" flag active cascades.

  • "OnInit()": The EA’s launch, called when attached to a chart. It sets up:

    • "iMA()": Creates a 10-period EMA ("handleMAFast") and 20-period EMA ("handleMASlow") using "MODE_EMA" and "PRICE_CLOSE".

    • "Print()": Logs errors if handles fail.

    • "ArraySetAsSeries()": Configures "maFast[]" and "maSlow[]" as time series (index 0 = latest).

    • "INVALID_HANDLE": A constant (-1) for failed indicator loads.

    • INIT_FAILED, INIT_SUCCEEDED: Constants for initialization outcomes. It returns INIT_SUCCEEDED if successful, like launching the raft with a clear current.

This rigs the raft, preparing the EA to ride EMA crossovers.

Clearing the River: OnDeinit Function

When the journey ends, this function tidies up.

void OnDeinit(const int reason){
   IndicatorRelease(handleMAFast);
   IndicatorRelease(handleMASlow);
}

The "OnDeinit()" function is the EA’s cleanup crew, called when removed:

  • "IndicatorRelease()": Frees "handleMAFast" and "handleMASlow" from memory, like docking the raft and storing gear.

This ensures a clean riverbank, freeing resources for the next trip.

Spotting the Current: IsNewBar Function

Before riding the rapids, the EA checks for new candles to time its moves.

bool IsNewBar(){
   static int prevBars = 0;
   int currBars = iBars(_Symbol,_Period);
   if (prevBars == currBars) return (false);
   prevBars = currBars;
   return (true);
}

The "IsNewBar()" function ensures trades trigger only on new candles:

  • "iBars()": Returns the chart’s bar count, stored in "currBars".

  • Logic: Compares static "prevBars" to "currBars". If equal, returns false (same candle). If different, updates "prevBars" and returns true, like checking if the river has shifted.

This keeps the EA disciplined, timing trades like a rafter waiting for the right current.

Riding the Rapids: OnTick Function

Now we hit the EA’s core, where it detects crossovers, launches trades, and cascades orders.

void OnTick(){
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

   if (CopyBuffer(handleMAFast,0,1,3,maFast) < 3){
      Print("NO ENOUGH DATA FROM FAST MA FOR FURTHER ANALYSIS. REVERTING NOW");
      return;
   }
   if (CopyBuffer(handleMASlow,0,1,3,maSlow) < 3){
      Print("NO ENOUGH DATA FROM slow MA FOR FURTHER ANALYSIS. REVERTING NOW");
      return;
   }
   
   if (PositionsTotal()==0){
      isBuySystemInitiated = false; isSellSystemInitiated = false;
   }
   
   if (PositionsTotal() == 0 && IsNewBar()){
      if (maFast[0] > maSlow[0] && maFast[1] < maSlow[1]){
         Print("BUY SIGNAL");
         takeProfit = Ask + tpPts*_Point;
         stopLoss = Ask - slPts*_Point;
         obj_Trade.Buy(LOT,_Symbol,Ask,stopLoss,0);
         isBuySystemInitiated = true;
      }
      else if (maFast[0] < maSlow[0] && maFast[1] > maSlow[1]){
         Print("SELL SIGNAL");
         takeProfit = Bid - tpPts*_Point;
         stopLoss = Bid + slPts*_Point;
         obj_Trade.Sell(LOT,_Symbol,Bid,stopLoss,0);
         isSellSystemInitiated = true;
      }
   }
   else {
      if (isBuySystemInitiated && Ask >= takeProfit){
         Print("(Buy) WE ARE ABOVE THE TP LEVEL OF ",takeProfit);
         takeProfit = takeProfit + tpPts*_Point;
         stopLoss = Ask - slPts_min*_Point;
         obj_Trade.Buy(LOT,_Symbol,Ask,0);
         ModifyTrades(POSITION_TYPE_BUY,stopLoss);
      }
      else if (isSellSystemInitiated && Bid <= takeProfit){
         Print("(Sell) WE ARE BELOW THE TP LEVEL OF ",takeProfit);
         takeProfit = takeProfit - tpPts*_Point;
         stopLoss = Bid + slPts_min*_Point;
         obj_Trade.Sell(LOT,_Symbol,Bid,0);
         ModifyTrades(POSITION_TYPE_SELL,stopLoss);
      }
   }
}

The "OnTick()" function is the EA’s river run, executing trades and cascades:

  • "SymbolInfoDouble()": Fetches ask ("SYMBOL_ASK", "Ask") and bid ("SYMBOL_BID", "Bid") prices.

  • "NormalizeDouble()": Rounds prices to "_Digits" (e.g., 5 for EURUSD).

  • "CopyBuffer()": Copies three EMA values (shift 1) into "maFast[]" and "maSlow[]". If fewer than three, logs errors with "Print()" and exits.

  • "PositionsTotal()": Checks open positions, resetting "isBuySystemInitiated" and "isSellSystemInitiated" if none.

  • Initial Trade: If no positions and "IsNewBar()" returns true, checks for crossovers:

    • Buy: "maFast[0] > maSlow[0] && maFast[1] < maSlow[1]", sets "takeProfit" (300 pips), "stopLoss" (300 pips), uses "obj_Trade.Buy()", and sets "isBuySystemInitiated".

    • Sell: "maFast[0] < maSlow[0] && maFast[1] > maSlow[1]", sets "takeProfit", "stopLoss", uses "obj_Trade.Sell()", and sets "isSellSystemInitiated".

  • Cascade Trade: If "isBuySystemInitiated" and "Ask >= takeProfit", shifts "takeProfit" up 300 pips, sets "stopLoss" 100 pips below "Ask", opens a new buy, and calls "ModifyTrades()". Similar for sells.

  • "Buy()", "Sell()": Open trades with "LOT", "_Symbol", price, stop loss, and take profit (0 for cascades).

This rides the rapids, launching and cascading trades like adding rafts to a surging current.

Locking in Profits: ModifyTrades Function

Finally, the EA adjusts stop losses, securing gains like anchoring rafts.

void ModifyTrades(ENUM_POSITION_TYPE posType,double sl){
   for (int i=0; i<=PositionsTotal(); i++){
      ulong ticket = PositionGetTicket(i);
      if (ticket > 0){
         if (PositionSelectByTicket(ticket)){
            ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
            if(type == posType){
               obj_Trade.PositionModify(ticket,sl,0);
            }
         }
      }
   }
}

The "ModifyTrades()" function adjusts stop losses:

  • "PositionGetTicket()": Gets a position’s ticket at index i.

  • "PositionSelectByTicket()": Selects the position by "ticket".

  • "PositionGetInteger()": Retrieves the position type ("POSITION_TYPE").

  • "PositionModify()": Updates the position’s stop loss to "sl", take profit 0.

This secures the journey, tightening stop losses like anchoring rafts in a strong current. See below.

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, check your copy-paste.

  4. Drag the EA onto your chart, set inputs (e.g., "LOT", "tpPts"), enable AutoTrading, and watch for cascading trades.

  5. Trade smart—don’t bet your raft on one current!

Conclusion

The Cascade Ordering EA is your river raft, riding EMA crossovers and cascading orders to capture trends. We’ve navigated its MQL5 code with clear, detailed explanations, so you understand every move like a seasoned rafter. Now you’re set to automate your trades and surf market currents. Want to see it in action? Check our video guide on the website!

Disclaimer: Trading’s like rafting a wild river—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!