Viewing the resource: Three MA System: Ride the Trend with Moving Averages

Three MA System: Ride the Trend with Moving Averages

Allan Munene Mutiiria 2025-06-20 21:21:41 81 Views
Dive into our fun, newbie-friendly guide to the Three MA System MQL5 code! We’ll break it into big...

Introduction

Hey, future forex rockstar! Picture the market as a dance floor, with prices grooving up and down. The Three MA System is your DJ, spinning three moving averages to drop the beat when a trend’s about to pop. This article is your VIP pass to automating that groove with MQL5 code on MetaTrader 5. We’ll serve the code in big, juicy function chunks, explain it like you’re new to the game (no shade!), and sprinkle in humor to keep it fresh. By the end, you’ll be ready to let this Expert Advisor (EA) spin trend signals for you. Let’s dance!

Strategy Blueprint

The Three MA System is a trend-following banger that uses three simple moving averages (SMAs):

  • Fast MA (8-period): The hyper kid, quick to catch price swings.

  • Medium MA (21-period): The cool teen, balancing speed and chill.

  • Slow MA (50-period): The wise elder, tracking the big picture.

When these MAs align, it’s like the stars lining up. A buy signal hits when the fast MA is above the medium, both above the slow, and the medium just crossed above the slow. A sell signal fires when the fast is below the medium, both below the slow, and the medium crossed below the slow. Our MQL5 code watches this dance, labeling “BUY” or “SELL” on the chart like a market hype man. See below.

Code Implementation

Time to crack open this MQL5 code like a glow stick and let it shine. We’re serving it in big, complete function chunks—none of that halfsies nonsense unless it’s critical. Variables like "handleMA1" and functions like "OnTick()" will be quoted for clarity. Let’s build this EA like we’re mixing a killer playlist—one track at a time.

1. Setting the Scene: Header, Properties, and Global Variables

Every EA needs a dope intro and some setup gear. This chunk lays the foundation.

//+------------------------------------------------------------------+
//|                                            3-THREE MA SYSTEM.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"
int handleMA1; // fast-8
int handleMA2; // intermediate-21
int handleMA3; // slow-50

This block is the EA’s mixtape cover, shouting, “I’m the Three MA System, made by Allan in 2025, version 1.00.” The "link" points to your Telegram channel for more trading heat. The global variables "handleMA1", "handleMA2", and "handleMA3" are like backstage passes, holding the handles for our 8-period, 21-period, and 50-period SMAs. They’re declared up top so the whole EA can use them to track the MAs.

2. Starting the Party: OnInit Function

Next, we get the EA pumped and ready to rock.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   ChartIndicatorAdd(0,0,handleMA1);
   ChartIndicatorAdd(0,0,handleMA2);
   ChartIndicatorAdd(0,0,handleMA3);
   return(INIT_SUCCEEDED);
}

The "OnInit()" function is the EA’s pre-party hype session, running when you attach it to a chart. It uses "ChartIndicatorAdd()" to slap the three MAs ("handleMA1", "handleMA2", "handleMA3") onto the chart’s main window (subwindow 0). It’s like setting up the stage lights before the show. Then, it returns INIT_SUCCEEDED to say, “We’re good to go!” Note: The handles aren’t initialized here, which we’ll see happens in "OnTick()". A bit unconventional, but it works!

3. Cleaning Up: OnDeinit Function

Every party needs a cleanup crew, even if it’s a small one.

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

The "OnDeinit()" function is the EA’s janitor, called when you remove it from the chart. Right now, it’s empty, like a cleaner who forgot their broom. It’s here for future tweaks, but we don’t need it yet since the EA doesn’t create persistent objects that need cleanup.

4. Dropping the Beat: OnTick Function

Here’s the heart of the EA, where the magic happens.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int totalBars = 0;

void OnTick()
{
   ChartIndicatorAdd(0,0,handleMA1);
   ChartIndicatorAdd(0,0,handleMA2);
   ChartIndicatorAdd(0,0,handleMA3);

   int bars = iBars(_Symbol,PERIOD_CURRENT);
   if (totalBars == bars)return;
   totalBars = bars;
   
   double maArray1[],maArray2[],maArray3[];
   
   // CREATE THE INDICATOR HANDLES
   handleMA1 = iMA(_Symbol,_Period,8,0,MODE_SMA,PRICE_CLOSE); // fast-8
   handleMA2 = iMA(_Symbol,_Period,21,0,MODE_SMA,PRICE_CLOSE); // intermediate-21
   handleMA3 = iMA(_Symbol,_Period,50,0,MODE_SMA,PRICE_CLOSE); // slow-50
   
   // sort the data as a time series
   ArraySetAsSeries(maArray1,true);
   ArraySetAsSeries(maArray2,true);
   ArraySetAsSeries(maArray3,true);
   
   // copy the data from the predefined arrays to other arrays for analysis
   if (!CopyBuffer(handleMA1,0,0,3,maArray1))return;
   if (!CopyBuffer(handleMA2,0,0,3,maArray2))return;
   if (!CopyBuffer(handleMA3,0,0,3,maArray3))return;

   // check for buy entry signal
   if ( (maArray1[0] > maArray2[0]) &&
        (maArray1[0] > maArray3[0]) &&
        (maArray2[0] > maArray3[0]) &&
        (maArray2[1] < maArray3[1])
   ){
      Comment("BUY");
   }
   // check for sell entry signal
   if ( (maArray1[0] < maArray2[0]) &&
        (maArray1[0] < maArray3[0]) &&
        (maArray2[0] < maArray3[0]) &&
        (maArray2[1] > maArray3[1])
   ){
      Comment("SELL");
   }
   else {Comment(" ");}
}

This is the EA’s main jam, and it’s a big one, so let’s break it down without splitting the function:

  • Global Tracker: Outside the function, "totalBars" tracks the number of bars to avoid reprocessing the same candle. It’s like a bouncer checking IDs to keep things fresh.

  • Adding Indicators: The "ChartIndicatorAdd()" calls (repeated from "OnInit()") ensure the MAs stay on the chart. A bit redundant, but it’s like double-checking your playlist.

  • New Bar Check: The "iBars()" function grabs the current bar count, and if "totalBars" matches "bars", the EA skips (no new candle, no work). When a new bar forms, "totalBars" updates.

  • Array Setup: Three arrays ("maArray1", "maArray2", "maArray3") are declared to hold MA values. They’re set as time series with "ArraySetAsSeries()", so index 0 is the latest value.

  • Handle Creation: The "iMA()" function creates handles for the 8-period ("handleMA1"), 21-period ("handleMA2"), and 50-period ("handleMA3") SMAs, all based on close prices ("PRICE_CLOSE") and simple MA type ("MODE_SMA").

  • Data Copy: The "CopyBuffer()" function pulls the last three MA values into the arrays. If it fails, the EA bails to avoid bad data.

  • Buy Signal: If "maArray1[0]" (fast MA) is above "maArray2[0]" (medium MA), both are above "maArray3[0]" (slow MA), and the medium MA was below the slow MA last bar ("maArray2[1]" < "maArray3[1]"), it’s a buy! The EA slaps “BUY” on the chart with "Comment()".

  • Sell Signal: If "maArray1[0]" is below "maArray2[0]", both below "maArray3[0]", and the medium MA was above the slow MA last bar ("maArray2[1]" > "maArray3[1]"), it’s a sell! “SELL” gets displayed.

  • No Signal: If neither signal hits, "Comment()" clears the chart with a blank space.

This function’s the whole show, crunching MA data and flashing signals like a market DJ.

Putting It All Together

To use this EA:

  1. Open MetaEditor in MetaTrader 5.

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

  3. Compile (F5). If errors pop up, check your copy-paste skills.

  4. Drag the EA onto your chart, enable AutoTrading, and watch for “BUY” or “SELL” labels.

  5. Trade smart—don’t bet your coffee fund on one signal!

Conclusion

The Three MA System EA is like a trend-spotting DJ, mixing three moving averages to drop buy or sell signals. We’ve unpacked its MQL5 code in big, clear chunks, so you can vibe with every line. Now you’re ready to automate your trading and ride the trends. Want to see it in action? Check our video tutorial on the website!

Disclaimer: Trading’s like dancing on a tightrope—exciting 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!