Viewing the resource: Alligator EA: Chomp Trends with Williams’ Alligator

Alligator EA: Chomp Trends with Williams’ Alligator

Allan Munene Mutiiria 2025-06-20 21:58:24 101 Views
Dive into our fun, newbie-friendly guide to the Alligator EA MQL5 code! We’ll explain every functi...

Introduction

Hey there, future forex trailblazer! Picture yourself navigating the wild forex jungle, where trends lurk like hidden treasures. The Alligator EA, powered by Bill Williams’ Alligator indicator, is your expert tracker, using three moving averages—jaws, teeth, and lips—to pounce on trending markets. This article is your map to automating that hunt with MQL5 code on MetaTrader 5. We’ll walk through the code with vivid detail, explaining every major function like you’re new to coding (no judgment!), and weave it all together with humor and flow, like a storyteller around a campfire. By the end, you’ll be ready to let this Expert Advisor (EA) chomp profits for you. Let’s hit the trail!

Strategy Blueprint

The Alligator EA is a trend-following powerhouse, built around the Alligator indicator’s three smoothed moving averages (SMMAs):

  • Jaws: A 13-period SMMA, shifted 8 bars forward, tracking the long-term trend.

  • Teeth: An 8-period SMMA, shifted 5 bars, catching mid-term moves.

  • Lips: A 5-period SMMA, shifted 3 bars, spotting short-term action.

When the lips cross above the teeth and both are above the jaws, it’s a buy signal—an uptrend’s brewing. When the lips dip below the teeth and both are below the jaws, it’s a sell signal—a downtrend’s coming. The EA waits for a recent crossover to confirm the trend, then opens trades with a 150-pip stop loss and take profit. It’s like a jungle predator waiting for the perfect moment to strike. See below.

Code Implementation

Let’s dive into the MQL5 code like explorers uncovering a hidden temple, explaining each major function in detail to make it crystal clear. We’ll present the code in complete, logical sections, ensuring a seamless flow from one part to the next, and quote variables (e.g., "jawsBuffer") and functions (e.g., "OnInit()") for clarity. Every key function used will be explained at least once, so you understand exactly what’s happening under the hood. Let’s start the adventure!

Setting the Foundation: Header, Includes, and Global Variables

First, we lay the groundwork for the EA, like pitching a tent before the expedition begins.

//+------------------------------------------------------------------+
//|                                                 ALLIGATOR 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 handleAlligator;
double jawsBuffer[];
double teethBuffer[];
double lipsBuffer[];

This opening act sets the stage. The header declares the EA as “Alligator EA,” authored by Allan in 2025, with a link to your Telegram channel and version 1.00. The #include <Trade/Trade.mqh> directive pulls in the MQL5 trade library, which provides tools for executing trades. The "CTrade" class creates an object named "obj_Trade", our trading assistant that handles buy and sell orders.

Globally, we define:

  • "handleAlligator": An integer to store the Alligator indicator’s handle, like a ticket to access its data.

  • "jawsBuffer[]", "teethBuffer[]", "lipsBuffer[]": Arrays to hold the Alligator’s jaws, teeth, and lips values, ready to store market signals.

These globals are like the EA’s backpack, packed with essentials for the journey.

Initializing the Expedition: OnInit Function

Next, we set up the Alligator indicator, like preparing our tracking gear.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   handleAlligator = iAlligator(_Symbol,_Period,13,8,8,5,5,3,MODE_SMMA,PRICE_MEDIAN);
   if (handleAlligator == INVALID_HANDLE) return (INIT_FAILED);
   Print("Handle = ",handleAlligator);
   
   ArraySetAsSeries(jawsBuffer,true);
   ArraySetAsSeries(teethBuffer,true);
   ArraySetAsSeries(lipsBuffer,true);
   
   return(INIT_SUCCEEDED);
}

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

  • "iAlligator()": Creates the Alligator indicator for the current symbol ("_Symbol", e.g., EURUSD) and timeframe ("_Period", e.g., H1). It takes parameters: 13-period jaws with 8-bar shift, 8-period teeth with 5-bar shift, 5-period lips with 3-bar shift, using smoothed moving averages ("MODE_SMMA") based on median price ("PRICE_MEDIAN"). It returns a handle, stored in "handleAlligator".

  • "Print()": Logs a message to the MetaTrader 5 journal, here showing the "handleAlligator" value for debugging, like a trail marker.

  • "ArraySetAsSeries()": Configures the "jawsBuffer[]", "teethBuffer[]", and "lipsBuffer[]" arrays as time series, so index 0 holds the latest value (like sorting your notes newest to oldest).

If "iAlligator()" fails (returns "INVALID_HANDLE"), the EA bails with INIT_FAILED, like canceling the trip if the gear’s broken. Otherwise, it returns INIT_SUCCEEDED, signaling, “We’re ready to hunt!” This function sets up the Alligator’s tracking system, ensuring we’re locked and loaded.

Wrapping Up the Trip: OnDeinit Function

When the expedition ends, this function tidies up.

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

The "OnDeinit()" function is the EA’s pack-up routine, called when you remove it from the chart. It’s empty here, like a minimalist camper who leaves no trace. No cleanup is needed since the Alligator indicator and trades are managed automatically by MetaTrader 5. This keeps things lightweight, ready for future tweaks if needed.

Tracking the Prey: OnTick Function

Now we hit the heart of the EA, where it hunts for trends on every price tick.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

   int currentBars = iBars(_Symbol,_Period);
   static int prevBars = 0;
   if (prevBars == currentBars) return;
   prevBars = currentBars;
   
   if (!CopyBuffer(handleAlligator,GATORJAW_LINE,0,2,jawsBuffer)) return;
   if (!CopyBuffer(handleAlligator,1,0,2,teethBuffer)) return;
   if (!CopyBuffer(handleAlligator,GATORLIPS_LINE,0,2,lipsBuffer)) return;

   if (lipsBuffer[0] > teethBuffer[0] &&
      lipsBuffer[0] > jawsBuffer[0] &&
      teethBuffer[0] > jawsBuffer[0] &&
      teethBuffer[1] < jawsBuffer[1]){
      Print("BUY SIGNAL");
      double sl = Bid - 150*_Point;
      double tp = Bid + 150*_Point;
      obj_Trade.PositionOpen(_Symbol,ORDER_TYPE_BUY,0.01,Ask,sl,tp);
   }
   else if (lipsBuffer[0] < teethBuffer[0] &&
      lipsBuffer[0] < jawsBuffer[0] &&
      teethBuffer[0] < jawsBuffer[0] &&
      teethBuffer[1] > jawsBuffer[1]){
      Print("SELL SIGNAL");
      double sl = Ask + 150*_Point;
      double tp = Ask - 150*_Point;
      obj_Trade.PositionOpen(_Symbol,ORDER_TYPE_SELL,0.01,Bid,sl,tp);
   }
}

The "OnTick()" function is the EA’s pulse, running on every price tick like a tracker scanning the jungle. It’s the core of the strategy, so let’s unpack it with detail, explaining each major function:

  • "SymbolInfoDouble()": Retrieves market data for the current symbol. Here, it grabs the ask price ("SYMBOL_ASK") and bid price ("SYMBOL_BID")—the prices to buy or sell at. These are stored in "Ask" and "Bid".

  • "NormalizeDouble()": Rounds a number (e.g., "Ask", "Bid") to the symbol’s decimal places ("_Digits", e.g., 5 for EURUSD). This ensures prices are formatted correctly for trading, like measuring ingredients precisely.

  • "iBars()": Returns the number of bars (candles) on the current chart, stored in "currentBars". This checks if a new candle has formed.

  • Bar Check Logic: A static variable "prevBars" tracks the previous bar count. If "prevBars" equals "currentBars", the EA skips (no new candle). When a new bar forms, "prevBars" updates. This ensures trades only trigger on new candles, avoiding spam.

  • "CopyBuffer()": Copies data from the Alligator indicator (via "handleAlligator") into arrays. It pulls two values (latest and previous) for the jaws ("GATORJAW_LINE"), teeth (buffer index 1), and lips ("GATORLIPS_LINE") into "jawsBuffer[]", "teethBuffer[]", and "lipsBuffer[]". If it fails, the EA exits to avoid bad data.

  • Buy Signal Logic: Checks if "lipsBuffer[0]" (latest lips) is above "teethBuffer[0]" and "jawsBuffer[0]", and "teethBuffer[0]" is above "jawsBuffer[0]", with "teethBuffer[1]" (previous teeth) below "jawsBuffer[1]" (previous jaws). This confirms an uptrend with a recent crossover. If true, it logs “BUY SIGNAL” with "Print()", sets a stop loss ("sl") 150 pips below "Bid" and take profit ("tp") 150 pips above using "_Point" (pip size), and opens a buy trade with "obj_Trade.PositionOpen()".

  • Sell Signal Logic: Checks if "lipsBuffer[0]" is below "teethBuffer[0]" and "jawsBuffer[0]", and "teethBuffer[0]" is below "jawsBuffer[0]", with "teethBuffer[1]" above "jawsBuffer[1]". This confirms a downtrend with a crossover. If true, it logs “SELL SIGNAL”, sets a stop loss 150 pips above "Ask" and take profit 150 pips below, and opens a sell trade.

  • "PositionOpen()": A method of the "CTrade" class, used to open trades. It takes the symbol ("_Symbol"), order type ("ORDER_TYPE_BUY" or "ORDER_TYPE_SELL"), lot size (0.01), price ("Ask" for buys, "Bid" for sells), stop loss, and take profit. It executes the trade like a broker on speed dial.

This function ties everything together, scanning the Alligator’s signals and firing trades when the trend’s ripe. The flow from price retrieval to signal checking to trade execution is like a well-choreographed hunt.

Putting It All Together

To unleash this EA:

  1. Open MetaEditor in MetaTrader 5.

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

  3. Compile (F5). If errors creep in, check your copy-paste game.

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

  5. Trade smart—don’t bet your safari gear on one signal!

Conclusion

The Alligator EA is your trend-hunting companion, using Bill Williams’ Alligator to chomp on forex moves. We’ve explored its MQL5 code with vivid detail, from setup to trading, so you understand every step like a seasoned tracker. Now you’re equipped to automate your trades and ride the market’s waves. Want to see it in action? Check our video tutorial on the website!

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