Viewing the resource: Smoothed Heiken Ashi Trend Trading System in MQL5

Smoothed Heiken Ashi Trend Trading System in MQL5

Allan Munene Mutiiria 2025-06-26 02:10:12 104 Views
This MQL5 EA uses Smoothed Heiken Ashi candles to trade trend reversals, opening 0.01-lot buy/sell t...

Introduction

Picture steering through market trends with the precision of a master navigator, using smoothed candlestick signals to pinpoint reversals with clarity. The Smoothed Heiken Ashi MT5 Indicator EA is your advanced trend navigation tool, designed to automate trading by leveraging a custom Smoothed Heiken Ashi indicator ("handleS_H_A_MT5", "iCustom()") with a 10-period LWMA setting. A buy signal triggers when a bearish Heiken Ashi candle (open above close, "Open[2] > Close[2]") is followed by a bullish candle (open below close, "Open[1] < Close[1]"), opening a 0.01-lot buy trade ("obj_Trade.Buy()") with a 300-pip stop loss and 100-pip take profit ("Ask-300*_Point", "Ask+100*_Point"), closing any sell positions ("closePositions()"). A sell signal reverses this, triggered by a bullish-to-bearish transition ("Close[2] > Close[1]", "Open[1] > Close[1]"). Trades are limited to one per new bar ("totalBars", "iBars()") to avoid overtrading, with no magic number for tracking. This strategy suits traders targeting trend reversals in volatile markets, requiring careful risk management due to fixed risk parameters and reliance on a custom indicator.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated trend navigation system, designed to inform and captivate readers. Tailored for both novice and experienced traders, we’ll dissect each code component with clear, precise explanations, as if guiding an apprentice navigator through a trend-trading project. With vivid examples—like trading EURUSD—and a polished tone, we’ll explore how the EA initializes, detects signals, executes trades, manages positions, and ensures cleanup. Using a precision trend navigation metaphor, this guide will illuminate the code’s technical rigor, empowering you to capture trends with confidence. Let’s activate the system and begin this trading expedition!

Strategy Blueprint

Let’s outline the EA’s trend navigation framework, like drafting specifications for a navigation system:

  • Indicator Setup: Initializes a custom Smoothed Heiken Ashi indicator ("iCustom()", "handleS_H_A_MT5", 10-period LWMA) to detect trend reversals.

  • Signal Detection: Triggers a buy when a bearish Heiken Ashi candle transitions to bullish ("Close[2] < Close[1]", "Open[2] > Close[2]", "Open[1] < Close[1]") or a sell when a bullish candle turns bearish ("Close[2] > Close[1]", "Open[2] < Close[2]", "Open[1] > Close[1]") using "CopyBuffer()".

  • Trade Execution: Opens 0.01-lot buy/sell trades ("obj_Trade.Buy()", "obj_Trade.Sell()") with 300-pip stop losses and 100-pip take profits ("Ask-300*_Point", "Bid-100*_Point").

  • Position Management: Closes opposite positions ("closePositions()", "PositionGetTicket()") to align with trend direction.

  • Trade Limitation: Restricts trades to one per new bar ("totalBars", "iBars()") to prevent overtrading.

  • Enhancements: Adding a magic number, configurable SL/TP, or signal filters could improve control and reliability. This framework automates trend reversal trading with precision, leveraging smoothed candles for robust signals.

Code Implementation

Let’s step into the trend navigation control room and dissect the MQL5 code that powers this Smoothed Heiken Ashi EA. We’ll guide you through each phase like expert navigators, ensuring the narrative flows seamlessly with professional clarity and engaging precision that captivates readers. We’ll cover initialization, signal detection, trade execution, position management, and cleanup, with detailed explanations and examples—like trading EURUSD—to make it accessible for beginners. Each phase will build on the last, crafting a cohesive technical narrative that transforms code into a compelling trend-trading project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the trading system, initializing the custom Smoothed Heiken Ashi indicator.

//+------------------------------------------------------------------+
//|                               SMOOTHED HEIKENASHI MT5 IND 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 handleS_H_A_MT5;
int totalBars = 0;

int OnInit(){
   handleS_H_A_MT5 = iCustom(_Symbol,_Period,"Market//Smoothed HeikenAshi MT5.ex5"
                     ,"===Heiken Settings===",10,MODE_LWMA,clrLime,clrRed,false
                     ,"===Other Settings",true,false);
   return(INIT_SUCCEEDED);
}

The system begins with the #property header, establishing copyright and contact details, like calibrating a trend navigation system’s core. The "OnInit()" function initializes the setup, including "Trade/Trade.mqh" for trading via "obj_Trade". It creates a handle for the custom Smoothed Heiken Ashi indicator ("handleS_H_A_MT5", "iCustom()", path "Market//Smoothed HeikenAshi MT5.ex5") with a 10-period LWMA, lime bullish candles, red bearish candles, and specific settings (display=true, alerts=false). The bar counter ("totalBars") is initialized. No error handling is implemented for the handle, assuming success. Returning INIT_SUCCEEDED signals, “System is ready, let’s navigate trends!” This primes the EA for Heiken Ashi-based trading, like a navigation tool poised for action.

Phase 2: Mapping Trend Signals—Loading Heiken Ashi Data

With the system active, we load Smoothed Heiken Ashi data to detect trend reversal signals, like scanning for directional shifts.

void OnTick(){
   double
         Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits),
         Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   double Open[],High[],Low[],Close[];
   ArraySetAsSeries(Open,true);    ArraySetAsSeries(High,true);
   ArraySetAsSeries(Low,true);     ArraySetAsSeries(Close,true);
   CopyBuffer(handleS_H_A_MT5,0,0,3,Open);
   CopyBuffer(handleS_H_A_MT5,1,0,3,High);
   CopyBuffer(handleS_H_A_MT5,2,0,3,Low);
   CopyBuffer(handleS_H_A_MT5,3,0,3,Close);
   int bars = iBars(_Symbol,_Period);
   if (totalBars == bars) return;
   totalBars = bars;

In the signal mapping hub, "OnTick()" runs every tick, fetching ask and bid prices ("Ask", "Bid", "SymbolInfoDouble()", "NormalizeDouble()"). It loads 3 bars of Heiken Ashi data ("Open", "High", "Low", "Close") from buffers 0–3 using "CopyBuffer()", setting arrays as time series ("ArraySetAsSeries()"). It checks for new bars ("iBars()", "totalBars") to limit processing, exiting if no new bar exists. No error handling is implemented for "CopyBuffer()". For example, on EURUSD H1, it loads Heiken Ashi data (e.g., "Close[2]"=1.2000, "Close[1]"=1.2005), preparing for signal detection, like charting a trend shift.

Phase 3: Navigating Trades—Executing Trend Signals

With data loaded, we execute trades based on Heiken Ashi candle transitions, like capitalizing on trend reversals.

void OnTick(){
   // ... (data loading)
   if (Close[2] < Close[1] && Open[2] > Close[2] && Open[1] < Close[1]){
      Print("BUY SIGNAL");
      closePositions(POSITION_TYPE_SELL);
      obj_Trade.Buy(0.01,_Symbol,Ask,Ask-300*_Point,Ask+100*_Point);
   }
   else if (Close[2] > Close[1] && Open[2] < Close[2] && Open[1] > Close[1]){
      Print("SELL SIGNAL");
      closePositions(POSITION_TYPE_BUY);
      obj_Trade.Sell(0.01,_Symbol,Bid,Bid+300*_Point,Bid-100*_Point);
   }
}

In the trade navigation hub, "OnTick()" checks for candle transitions. A buy signal triggers when a bearish candle ("Close[2] < Close[1]", "Open[2] > Close[2]") is followed by a bullish candle ("Open[1] < Close[1]"), logging with "Print()" (“BUY SIGNAL”), closing sell positions ("closePositions(POSITION_TYPE_SELL)"), and opening a 0.01-lot buy ("obj_Trade.Buy()") at ask ("Ask") with a 300-pip stop loss ("Ask-300*_Point") and 100-pip take profit ("Ask+100*_Point"). A sell signal reverses this ("Close[2] > Close[1]", "Open[2] < Close[2]", "Open[1] > Close[1]"), closing buys and opening a sell. For example, on EURUSD H1, a bearish-to-bullish transition (Close[2]=1.2000, Open[2]=1.2005; Close[1]=1.2007, Open[1]=1.2002) triggers a buy at 1.2007, stop loss at 1.1707, take profit at 1.2107, like locking onto a bullish reversal.

Phase 4: Managing Positions—Closing Opposite Trades

With trades open, we manage positions by closing opposites, like adjusting sails to the new trend.

void closePositions(ENUM_POSITION_TYPE type){
   for (int i=PositionsTotal()-1; i>=0; i--){
      ulong ticket = PositionGetTicket(i);
      if (PositionSelectByTicket(ticket)){
         if (PositionGetString(POSITION_SYMBOL)==_Symbol){
            if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY &&
               type == POSITION_TYPE_BUY){
               obj_Trade.PositionClose(ticket);
            }
            else if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL &&
               type == POSITION_TYPE_SELL){
               obj_Trade.PositionClose(ticket);
            }
         }
      }
   }
}

In the position management hub, "closePositions()" loops through open positions ("PositionsTotal()", "PositionGetTicket()") and closes those matching the specified type ("POSITION_TYPE_BUY" or "POSITION_TYPE_SELL", "PositionGetInteger()") and symbol ("PositionGetString()", "_Symbol") using "obj_Trade.PositionClose()". For example, on EURUSD, a buy signal closes all sell positions, ensuring trend alignment, like adjusting to a new market direction.

Phase 5: Shutting Down the System—Cleaning Up Resources

As our expedition concludes, we shut down the system, ensuring resources are cleared.

void OnDeinit(const int reason){
}

In the shutdown control room, "OnDeinit()" is empty, leaving the indicator handle active, like a running navigation system. Adding cleanup would ensure a clean slate:

IndicatorRelease(handleS_H_A_MT5);
ArrayFree(Open);
ArrayFree(High);
ArrayFree(Low);
ArrayFree(Close);

This would release the indicator handle ("IndicatorRelease()", "handleS_H_A_MT5") and free arrays ("ArrayFree()", "Open", "High", "Low", "Close"), like dismantling a trend navigation system, ready for the next task.

Why This EA is a Trend Navigation Triumph

The Smoothed Heiken Ashi EA is a trend-trading triumph, automating reversals with precision, like a master-crafted navigation engine. Its Smoothed Heiken Ashi signals ("Open", "Close") and position management ("closePositions()") offer robust trend alignment, with potential for magic numbers or configurable SL/TP. Picture a buy on EURUSD at 1.2007 after a bullish candle transition—strategic brilliance! Beginners will value the clear signals, while experts can refine its framework, making it essential for trend traders.

Putting It All Together

To deploy this EA:

  1. Ensure the “Smoothed HeikenAshi MT5.ex5” indicator is installed in the MetaTrader 5 “Market” folder.

  2. Open MetaEditor in MetaTrader 5, like entering your trend navigation control room.

  3. Copy the code, compile with F5, and verify no errors—no navigator wants a faulty system!

  4. Attach the EA to your chart, enable AutoTrading, and watch it execute Heiken Ashi-based trades.

  5. Monitor logs (e.g., “BUY SIGNAL”) for trade tracking, like navigation diagnostics.

  6. Test on a demo account first—real capital deserves a trial run!

Conclusion

We’ve engineered a Smoothed Heiken Ashi Trader that automates trend reversals with precision, like a master-crafted navigation system. This MQL5 code is your strategic tool, brought to life with a seamless, professional narrative packed with clear explanations and vivid examples to fuel your trading ambition. Whether you’re a novice navigator or a seasoned market strategist, this EA empowers you to capture trends with confidence. Ready to trade? Watch our video guide on the website for a step-by-step creation process. Now, steer your trading course with precision! 🔍

Disclaimer: Trading is like navigating complex markets—challenging and risky. Losses can exceed deposits. Test strategies 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!