Viewing the resource: Harmonic Pattern EA: Trade Patterns with Precision

Harmonic Pattern EA: Trade Patterns with Precision

Allan Munene Mutiiria 2025-06-20 22:41:57 87 Views
Join our fun, newbie-friendly guide to the Harmonic Pattern EA MQL5 code! We’ll explain every func...

Introduction

Hey there, future forex artist! Picture the forex market as a canvas where prices sketch intricate patterns, like a masterpiece waiting to be traded. The Harmonic Pattern EA is your paintbrush, using a custom indicator to spot geometric formations like Gartley, Butterfly, or Crab, and trading them with precision. This article is your studio tour, 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 worries!), blending humor and flow like a storyteller at an easel. By the end, you’ll be ready to let this Expert Advisor (EA) paint profits on your charts. Let’s start creating!

Strategy Blueprint

The Harmonic Pattern EA leverages a custom indicator to detect harmonic patterns—geometric price formations based on Fibonacci ratios that signal potential reversals. Key patterns include Gartley, Butterfly, Crab, and Bat, each with specific Fibonacci levels (e.g., 61.8%, 78.6%) forming “M” (bearish) or “W” (bullish) shapes. The EA:

  • Triggers a buy when a bullish pattern completes, entering at the pattern’s final price.

  • Triggers a sell when a bearish pattern completes, entering at the reversal point.

  • Sets a stop loss (SL) at the pattern’s key boundary and three take-profit levels (TP1, TP2, TP3), with TP3 as the primary target.

  • Uses a 0.01-lot size for controlled risk.

Trades execute only on new candles to avoid duplicates, ensuring discipline. It’s like drawing a perfect pattern and trading its beauty with confidence. See below.

Code Implementation

Let’s dive into the MQL5 code like artists mixing colors, 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., "signalBuy") and functions (e.g., "OnInit()") to keep it beginner-friendly. Our goal is to make the code as inviting as a blank canvas, guiding you through every brushstroke with ease.

Setting the Canvas: Header, Includes, and Global Variables

We begin by preparing the workspace, like stretching a canvas before painting.

//+------------------------------------------------------------------+
//|                                    Basic Harmonic Pattern EA.mq5 |
//|                        Copyright 2025, Allan Munene Mutiiria      |
//|                        mutiiriallan.forex@gmail.com               |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria"
#property link      "mutiiriallan.forex@gmail.com"
#property description "Incase of anything with this Version of EA, Contact:\n"
                      "\nEMAIL: mutiiriallan.forex@gmail.com"
                      "\nWhatsApp: +254 782 526088"
                      "\nTelegram: https://t.me/Forex_Algo_Trader"
#property version   "1.00"

#include <Trade/Trade.mqh>
CTrade obj_Trade;

int handle_BHP = INVALID_HANDLE; // -1

double signalBuy[], signalSell[];
double tp1[], tp2[], tp3[], sl0[];

double currBuy, currSell;
double currSl, currTP1, currTP2, currTP3;

This opening sets the stage. The header declares the EA as “Basic Harmonic Pattern EA,” authored by Allan in 2025, with your contact details (email, WhatsApp, Telegram) 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:

  • "handle_BHP": An integer initialized to "INVALID_HANDLE" (-1), storing the custom harmonic pattern indicator’s handle.

  • "signalBuy[]", "signalSell[]": Arrays for buy and sell signal prices from the indicator.

  • "tp1[]", "tp2[]", "tp3[]", "sl0[]": Arrays for take-profit levels (TP1, TP2, TP3) and stop loss (SL).

  • "currBuy", "currSell": Variables to track the latest buy/sell signal prices, preventing duplicate trades.

  • "currSl", "currTP1", "currTP2", "currTP3": Variables to store current stop loss and take-profit levels.

These globals are like your paint palette, ready for the EA to create its masterpiece.

Priming the Brush: OnInit Function

Next, we load the custom indicator, like dipping your brush in paint.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){
   
   handle_BHP = iCustom(_Symbol,_Period,"Market//Basic Harmonic Pattern MT5");
   
   if (handle_BHP == INVALID_HANDLE){
      Print("UNABLE TO INITIALIZE THE IND CORRECTLY. REVERTING NOW.");
      return (INIT_FAILED);
   }
   
   ArraySetAsSeries(signalBuy,true);
   ArraySetAsSeries(signalSell,true);
   
   return(INIT_SUCCEEDED);
}

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

  • "iCustom()": Loads a custom indicator named “Basic Harmonic Pattern MT5” from the “Market” folder for the current symbol ("_Symbol", e.g., EURUSD) and timeframe ("_Period", e.g., H1). It returns a handle, stored in "handle_BHP", for accessing pattern data.

  • "Print()": Logs a message to the MetaTrader 5 journal, here reporting if "iCustom()" fails, like a warning if your paint’s dried up.

  • "ArraySetAsSeries()": Configures the "signalBuy[]" and "signalSell[]" arrays as time series, so index 0 holds the latest value, like arranging your sketches newest first.

  • "INVALID_HANDLE": A constant (-1) indicating a failed indicator load. If "handle_BHP" equals this, 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, “Canvas is ready!” This function ensures the harmonic pattern indicator is loaded and arrays are prepped for signals.

Clearing the Easel: OnDeinit Function

When the painting session ends, this function tidies up.

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

The "OnDeinit()" function is the EA’s cleanup routine, called when you remove it from the chart. It’s empty here, like an artist leaving a clean studio. No cleanup is needed since the custom indicator and trades are managed by MetaTrader 5, keeping things light and ready for future tweaks.

Painting the Trade: OnTick Function

Now we hit the EA’s core, where it trades harmonic patterns on every price tick.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){
   
   if (CopyBuffer(handle_BHP,0,1,1,signalBuy) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR BUY SIG'. REVERTING.");
      return;
   }
   if (CopyBuffer(handle_BHP,1,1,1,signalSell) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR SELL SIG'. REVERTING.");
      return;
   }
   
   if (CopyBuffer(handle_BHP,2,1,1,sl0) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR SL. REVERTING.");
      return;
   }
   
   if (CopyBuffer(handle_BHP,3,1,1,tp1) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR TP1. REVERTING.");
      return;
   }
   if (CopyBuffer(handle_BHP,4,1,1,tp2) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR TP2. REVERTING.");
      return;
   }
   if (CopyBuffer(handle_BHP,5,1,1,tp3) < 1){
      Print("UNABLE TO GET ENOUGH REQUESTED DATA FOR TP3. REVERTING.");
      return;
   }
   
   int currBars = iBars(_Symbol,_Period);
   static int prevBars = currBars;
   if (prevBars == currBars) return;
   prevBars = currBars;
   
   if (signalBuy[0] != EMPTY_VALUE && signalBuy[0] != currBuy){
      Print("BUY = ",signalBuy[0]);
      Print("SL = ",sl0[0],", TP1 = ",tp1[0],", TP2 = ",tp2[0],", TP3 = ",tp3[0]);
      
      currBuy = signalBuy[0];
      currSl = sl0[0]; currTP1 = tp1[0]; currTP2 = tp2[0]; currTP3 = tp3[0];
      
      obj_Trade.Buy(0.01,_Symbol,currBuy,currSl,currTP3);
   }
   
   else if (signalSell[0] != EMPTY_VALUE && signalSell[0] != currSell){
      Print("SELL = ",signalSell[0]);
      Print("SL = ",sl0[0],", TP1 = ",tp1[0],", TP2 = ",tp2[0],", TP3 = ",tp3[0]);
      
      currSell = signalSell[0];
      currSl = sl0[0]; currTP1 = tp1[0]; currTP2 = tp2[0]; currTP3 = tp3[0];
      
      obj_Trade.Sell(0.01,_Symbol,currSell,currSl,currTP3);
   }
}

The "OnTick()" function is the EA’s painting session, running on every price tick to trade harmonic patterns. It’s the heart of the strategy, so let’s unpack it with detail, explaining each major function:

  • "CopyBuffer()": Copies data from the custom indicator (via "handle_BHP") into arrays. It pulls one value from shift 1 (previous candle) for buy signals (buffer 0, "signalBuy[]"), sell signals (buffer 1, "signalSell[]"), stop loss (buffer 2, "sl0[]"), and take profits (buffers 3–5, "tp1[]", "tp2[]", "tp3[]"). If any fails to return at least one value, it logs an error with "Print()" and exits, ensuring reliable data.

  • "iBars()": Returns the number of bars on the chart, stored in "currBars", to check for new candles.

  • Bar Check Logic: A static "prevBars" variable, initialized to "currBars", tracks the previous bar count. If "prevBars" equals "currBars", the EA skips to avoid reprocessing the same candle. When a new bar forms, "prevBars" updates.

  • "EMPTY_VALUE": A constant indicating no signal (typically a very large number like DBL_MAX). The EA checks if "signalBuy[0]" or "signalSell[0]" isn’t "EMPTY_VALUE" to confirm a valid signal.

  • Buy Signal Logic: If a buy signal exists ("signalBuy[0] != EMPTY_VALUE") and is new ("signalBuy[0] != currBuy"), the EA logs the signal and levels with "Print()", updates "currBuy", "currSl", "currTP1", "currTP2", and "currTP3", and opens a buy trade with "obj_Trade.Buy()". It uses 0.01 lots, the signal price ("currBuy"), stop loss ("currSl"), and TP3 ("currTP3") as the take profit.

  • Sell Signal Logic: If a sell signal exists ("signalSell[0] != EMPTY_VALUE") and is new ("signalSell[0] != currSell"), the EA logs the signal and levels, updates "currSell" and related variables, and opens a sell trade with "obj_Trade.Sell()", using 0.01 lots, "currSell", "currSl", and "currTP3".

  • "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. They execute trades like a gallery curator hanging a painting.

This function flows from fetching indicator data to checking for new candles, validating signals, and executing trades, like an artist sketching a pattern and bringing it to life.

Putting It All Together

To unleash this EA:

  1. Ensure the “Basic Harmonic Pattern MT5” indicator is in the MetaTrader 5 “Market” folder.

  2. Open MetaEditor in MetaTrader 5.

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

  4. Compile (F5). If errors appear, double-check your copy-paste or indicator setup.

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

  6. Trade smart—don’t bet your art supplies on one pattern!

Conclusion

The Harmonic Pattern EA is your artistic ally, painting trades with the precision of geometric patterns. We’ve explored its MQL5 code with clear, detailed explanations, so you understand every stroke like a master painter. Now you’re set to automate your trades and capture the market’s rhythm. Want to see it in action? Check our video tutorial on the website!

Disclaimer: Trading’s like painting in a storm—beautiful 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!