preview
Building a HalfTrend Channel Indicator in MQL5

Building a HalfTrend Channel Indicator in MQL5

MetaTrader 5 — Indicators |
242 0
ALGOYIN LTD
Israel Pelumi Abioye

Introduction

Identifying trend direction and potential reversals can be challenging when price movements fluctuate around changing market levels. The HalfTrend algorithm addresses this by tracking price structure and updating its baseline when specific conditions are met. However, combining this approach with volatility-based channel boundaries provides additional context for observing price movement around the trend line. In this article, we will build a HalfTrend Channel indicator in MQL5 using the HalfTrend algorithm and an ATR-based channel calculation.

The goal is to create a trend indicator that displays the HalfTrend baseline. It also calculates dynamic channel boundaries using Wilder-smoothed ATR(100) and tracks price crossings beyond them. We will evaluate rolling highs and lows, calculate average highs and lows, update the trend state, and apply ATR-based offsets around the baseline. The indicator will also include a channel line colored according to the channel-direction state, a shaded fill, an optional opposite band, and dots marking changes in the HalfTrend baseline mode.

 

Project Overview and Implementation Plan

Developing the HalfTrend Channel indicator in MQL5 involves several connected stages, from calculating price references to displaying the final chart elements. We will implement rolling highs and lows, update the HalfTrend state and baseline, calculate Wilder-smoothed ATR(100), establish the dynamic channel boundaries, detect price crossings, and configure the channel, opposite band, shaded fill, and baseline mode-switch markers.

Comparing the HalfTrend Channel with an SMA-Based Channel

Although ATR-based channels use volatility to adjust their boundaries, their behavior also depends on how the central reference line is calculated. In a conventional SMA(high/low) channel, the upper and lower boundaries are derived from the average highs and lows, with an ATR adjustment added to the upper boundary and subtracted from the lower boundary. This approach follows averaged price data.

The HalfTrend Channel constructs its baseline differently. It combines rolling price extremes with a trend-state mechanism that evaluates average highs/lows and breakouts beyond the previous candle's high/low. During an established uptrend, the baseline can rise or remain flat, while in a downtrend, it can fall or remain flat. This creates a stepped reference line governed by the HalfTrend state rather than a moving average.

The upper and lower boundaries are calculated around the HalfTrend baseline using Wilder-smoothed ATR(100). Their distance from the baseline expands or contracts as the ATR value changes, allowing the channel width to reflect measured volatility. A separate channel-direction state tracks closing-price crossings above the upper boundary and below the lower boundary. The HalfTrend state determines the baseline mode. The channel-direction state determines which boundary is displayed and remains unchanged until a qualifying opposite crossing occurs.

What We Are Building

In this project, we will build a HalfTrend Channel indicator for MetaTrader 5 that tracks trend direction, constructs a HalfTrend baseline, and displays dynamic channel boundaries based on the Average True Range (ATR). The indicator will use a configurable amplitude to evaluate rolling highs and lows and determine when the trend state should change.

The HalfTrend algorithm maintains two trend states, represented by 0 and 1. When the algorithm is in state 0, it updates the upper baseline using the highest of the tracked low values and the previous baseline. When the algorithm is in state 1, it updates the lower baseline using the lowest of the tracked high values and the previous baseline. Specific conditions involving the average highs, average lows, rolling extremes, and previous bar prices determine when the algorithm changes its trend state. When a transition occurs, the baseline carries forward the previous active line to establish the new level.

After the baseline is calculated, the indicator measures price volatility using True Range and applies Wilder smoothing to calculate ATR(100). It then multiplies the ATR value by the configurable deviation multiplier and divides the result by two to determine the distance from the baseline to each channel boundary. The upper boundary is calculated by adding this distance to the baseline, while the lower boundary is calculated by subtracting it. This creates a channel whose total width is determined by the selected ATR multiplier and the calculated volatility.

The indicator also tracks a direction flag. It changes when the close crosses above the upper boundary or below the lower boundary. This flag determines which channel boundary is displayed as the main channel line, while the other boundary can be displayed as an opposite band. The completed indicator includes a shaded area between the midpoint of each bar and the selected channel boundary, a colored baseline that reflects the current HalfTrend mode, and dots marking changes in the baseline mode. Together, these elements display the HalfTrend structure, ATR-based channel boundaries, and confirmed changes in channel direction.

Figure 1. What We Are Building

Figure 1. What We Are Building

Implementation Plan

In this section, we will outline the development plan for implementing the HalfTrend Channel indicator in MQL5 before moving into the actual coding process.

1. Setting up the Indicator Properties, Plots, Buffers, and Inputs

First, we configure the basic structure of the HalfTrend channel indicator.

This includes:

  • indicator properties that define the number of buffers, plots, and the chart window where the indicator will be displayed;
  • plot configurations that specify the drawing styles, colors, and widths for the HalfTrend channel line, baseline, opposite band, filled area, and mode-switch markers;
  • input parameters that allow users to customize the amplitude, channel deviation multiplier, display range, plot colors, and visibility settings;
  • indicator buffers used to store the channel values, baseline values, opposite band, filled areas, and mode-switch markers, along with their corresponding color indices;
  • internal working arrays that store intermediate calculations such as true range, ATR values, rolling highs and lows, trend states, and channel boundaries;
  • buffer mappings that connect each indicator buffer with its corresponding plot or color-index role during initialization.

2. Calculating the Baseline and Updating the Trend State

The baseline is calculated by tracking rolling price extremes, maintaining reference levels, and monitoring changes in the internal trend state to determine the value plotted for each bar. The examples below use an amplitude of three bars to simplify the calculations, while the indicator's default setting is 10 bar.

For each bar, the indicator identifies the highest high and lowest low within the selected window and calculates the average high and average low. These values are used to update the reference levels and evaluate potential trend reversals.

For example, consider these three bars:

Bar
High
Low
11.1050
1.1000
21.1060
1.1010
31.10401.1020

Figure 2. Baseline Calculation

Figure 2. Baseline Calculation

At bar 3, the rolling lowest low is 1.1000, the rolling highest high is 1.1060, the average high is 1.1050, and the average low is 1.1010.

During an uptrend, the indicator tracks the highest value reached by the rolling lowest low. Whenever a new rolling lowest low exceeds the tracked reference, the reference increases. The baseline then takes whichever is higher: the updated reference or the previous baseline.

For example, assume the previous baseline and initial reference are 1.1000.

Bar
Rolling lowest low
Tracked reference
Previous baseline
New baseline
31.10001.1000 1.1000 1.1000
41.10101.10101.1000 1.1010
51.1005
1.1010
1.1010 
1.1010
61.1020
1.1020
1.1010
1.1020
71.1015
1.1020
1.1020 
1.1020

The baseline updates to 1.1010 when the rolling lowest low rises to 1.1010. If it then falls to 1.1005, the baseline remains unaltered and the reference remains at 1.1010. As a result, during an uptrend, the baseline may climb or stay unchanged. Every time a new rolling highest high drops below the previous reference, the indicator lowers the reference. The baseline can decline or stay flat by using the lower of the new reference and its prior value.
For example, assume the previous baseline and initial reference are 1.1100.

Bar
Rolling highest high
Tracked reference
Previous baseline
New baseline
31.11001.1100 1.1100 1.1100
41.10901.10901.1100 1.1090
51.1095
1.1090
1.1090 
1.1090
61.1080
1.1080
1.1090
1.1080
71.1085
1.1080
1.1080 
1.1080

Bar 4 causes the rolling highest high to drop to 1.1090, and the baseline follows suit. At bar 5, the rolling highest high rises to 1.1095, while the reference stays at 1.1090, maintaining the baseline. As long as the downtrend state is in effect, this keeps the baseline from rising. First, the baseline maintains the prior bearish baseline value when the internal state shifts to an uptrend, following which the standard bullish computation permits it to either rise or stay flat.

For example, suppose the previous bearish baseline is 1.1000.

BarInternal trend state
Previous bearish baseline
New bullish baseline
10Downtrend
1.1000
1.1000
11Uptrend begins
1.1000
1.1000
12Uptrend continues
1.1000
1.1010
13Uptrend continues
1.1010
1.1015

The baseline begins at 1.1000 on bar11. Since the updated reference is greater than the prior baseline, the standard bullish computation resumes at bar 12, boosting the baseline to 1.1010. On the other hand, when the internal trend state changes from an uptrend to a downtrend, the new bearish baseline starts with the value of the prior bullish baseline and then applies the standard bearish calculation to successive bars.

For example, suppose the previous bullish baseline is 1.1100.

Bar
Internal trend state
Previous bullish baseline
New bearish baseline
20Uptrend
1.1100
1.1100
21Downtrend begins
1.1100
1.1100
22Downtrend continues
1.1100
1.1090
23Downtrend continues
1.1090
1.1085

Suppose the baseline starts at 1.1100 on bar 21. On bar 22, the bearish calculation moves it down to 1.1090 as the updated reference falls below the previous baseline. The internal trend state changes only when both confirmation conditions occur together. For a transition from uptrend to downtrend, the average highs must be below the tracked lowest-low reference, while the current closing price must also be lower than the previous bar's low.

Average highs
Tracked reference
Previous bar Low
Current Close
Result
1.1020
1.1030
1.1010
1.1005
Downtrend confirmed
1.1040
1.1030
1.1020
1.1015
No transition

In the first example, both conditions are met. In the second, the average highs are above the reference, so the transition is not confirmed.

Downtrend to uptrend: The average lows must rise above the tracked highest-high reference, and the current bar must close above the previous bar's high.

Average lows
Tracked reference
Previous bar High
Current Close
Result
1.1050
1.1040
1.1060
1.1065
Uptrend confirmed
1.1020
1.1040
1.1030
1.1035
No transition

In the first example, both conditions are met. In the second, the average lows are below the reference, so the transition is not confirmed.

After calculating the bullish and bearish baseline candidates, the indicator selects the one corresponding to the current internal trend state. The selected value becomes the central baseline used to calculate the ATR boundaries.

For example:

Internal trend state
Bullish baseline
Bearish baseline
Selected baseline
Uptrend
1.1020
1.1080
1.1020
Downtrend
1.1020
1.1080
1.1080

The bullish baseline is selected during an uptrend, while the bearish baseline is selected during a downtrend.

3. Calculating the True Range and Smoothing the ATR

Next, we calculate the True Range for each bar and use it to derive the 100-period Average True Range (ATR), which determines the distance between the HalfTrend baseline and the channel boundaries.

This includes:

  • calculating the True Range using the current bar's high and low, along with the previous bar's closing price where available;
  • identifying the largest of the current bar's high-low range and the two gaps between the current high or low and the previous closing price;
  • initializing the ATR using the simple average of the first 100 True Range values;
  • applying Wilder's smoothing method to update the ATR for each subsequent bar, giving greater weight to the previous ATR value than to the latest True Range;
  • marking the ATR as valid only after the initial 100-bar calculation is complete;
  • calculating the channel deviation by multiplying the ATR by the user-defined deviation multiplier and dividing the result by two.

These calculations provide the volatility-based distance used to construct the upper and lower channel boundaries around the HalfTrend baseline.

4. Constructing the ATR Channel Boundaries and Determining Breakout Direction

After calculating the baseline and ATR deviation, we construct the upper and lower channel boundaries and detect closing-price crossings above the upper boundary or below the lower boundary to update the channel-direction state.

This includes:

  • selecting the active baseline according to the current trend state, using the upper baseline during an uptrend state and the lower baseline during a downtrend state;
  • calculating the upper channel boundary by adding the ATR deviation to the active baseline;
  • calculating the lower channel boundary by subtracting the ATR deviation from the active baseline;
  • storing the trend state, baseline values, channel boundaries, and reference levels in internal arrays for use in subsequent calculations;
  • tracking the previous direction state so that the indicator can determine whether the closing price has crossed a channel boundary;
  • identifying an upward breakout when the current close moves above the upper boundary after the previous close was at or below its corresponding upper boundary;
  • identifying a downward breakout when the current close moves below the lower boundary after the previous close was at or above its corresponding lower boundary;
  • retaining the existing direction state when neither crossing condition is satisfied, and evaluating crossings only when the ATR values for both the current and previous bars are valid.

5. Displaying the Channel, Baseline, Fill, and Mode-Switch Markers

Next, we prepare the calculated values for chart rendering by assigning the appropriate channel boundaries, baseline values, fill areas, and mode-switch markers to their indicator buffers.

This includes:

  • selecting the lower channel boundary when the direction state is upward and the upper boundary when the direction state is downward;
  • temporarily hiding the channel line and opposite band on bars where the direction state changes, preventing the plotted lines from connecting across the transition;
  • storing the selected channel boundary and its color index in the channel buffers;
  • displaying the opposite channel boundary when the corresponding visibility option is enabled;
  • calculating the midpoint of each bar and using it as the reference for the filled area, collapsing the fill to zero thickness whenever the fill is disabled or the channel should not be displayed;
  • displaying the baseline when enabled and assigning its color according to the current internal trend state;
  • marking bars where the internal trend state changes, using the baseline value and the color associated with the newly entered state;
  • clearing the graphical elements that have moved outside the selected display window when a new bar forms, and refreshing the fill colors.

Figure 3. HalfTrend Channel

Figure 3. HalfTrend Channel


Implementation in MQL5

Having outlined the indicator's objectives and development strategy, we can now move on to implementation. Each stage will focus on building a specific component of the HalfTrend Channel indicator, from its initial setup to its calculations and chart display.

Setting Up the Indicator Properties, Plots, Buffers, and Inputs

First, define the indicator properties, plots, buffers, and inputs required for the HalfTrend Channel indicator.

Example:

#property indicator_chart_window
#property indicator_buffers 9
#property indicator_plots   5

//--- plot 1: fill between price midpoint and channel line
#property indicator_label1  "HalfTrend Fill"
#property indicator_type1   DRAW_FILLING
#property indicator_color1  clrDarkGreen,clrMaroon

//--- plot 2: channel line
#property indicator_label2  "HalfTrend Channel"
#property indicator_type2   DRAW_COLOR_LINE
#property indicator_color2  C'4,180,145',C'255,0,85'
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2

//--- plot 3: baseline, coloured by its mode (up mode / down mode)
#property indicator_label3  "Baseline"
#property indicator_type3   DRAW_COLOR_LINE
#property indicator_color3  C'66,135,245',clrOrange
#property indicator_style3  STYLE_DASH
#property indicator_width3  1

//--- plot 4: the channel boundary opposite to the currently selected boundary
#property indicator_label4  "Opposite Band"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrGray
#property indicator_style4  STYLE_DOT
#property indicator_width4  1

//--- plot 5: dot on every bar where the baseline mode switches
#property indicator_label5  "Mode Switch"
#property indicator_type5   DRAW_COLOR_ARROW
#property indicator_color5  C'66,135,245',clrOrange
#property indicator_width5  3

//--- Inputs
input int    InpAmplitude    = 10;            // Amplitude
input color  InpColBull      = C'4,180,145';  // Bullish Trend Color
input color  InpColBear      = C'255,0,85';   // Bearish Trend Color
input color  InpColModeUp    = C'66,135,245'; // Baseline Up Mode Color
input color  InpColModeDn    = clrOrange;     // Baseline Down Mode Color
input int    InpDisplayBars  = 500;           // Display Bars (0 = all bars)
input double InpDevMul       = 2.0;           // Channel Deviation (ATR multiplier)
input bool   InpShowFill     = true;          // Show channel fill
input bool   InpShowBaseline = true;          // Show baseline (coloured by mode)
input bool   InpShowOpposite = true;          // Show opposite band (the hidden one)
input bool   InpShowModeSw   = true;          // Mark baseline mode switches

//--- buffers
double BufFill1[];
double BufFill2[];
double BufBand[];
double BufBandClr[];
double BufBase[];
double BufBaseClr[];
double BufOpp[];
double BufMode[];
double BufModeClr[];

//+------------------------------------------------------------------+
//| Blend two colors based on the specified interpolation factor     |
//+------------------------------------------------------------------+
color Blend(const color a,const color b,const double t)
  {
   double k = MathMax(0.0,MathMin(1.0,t));
   int ra = (int)(a & 0xFF), ga = (int)((a >> 8) & 0xFF), ba = (int)((a >> 16) & 0xFF);
   int rb = (int)(b & 0xFF), gb = (int)((b >> 8) & 0xFF), bb = (int)((b >> 16) & 0xFF);
   int r = (int)MathRound(ra + (rb - ra) * k);
   int g = (int)MathRound(ga + (gb - ga) * k);
   int bl = (int)MathRound(ba + (bb - ba) * k);
   return (color)(r | (g << 8) | (bl << 16));
  }

//+------------------------------------------------------------------+
//| Apply background-blended colors to the bullish and bearish fill  |
//+------------------------------------------------------------------+
void ApplyFillColors()
  {
   color bg = (color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,Blend(bg,InpColBull,0.15));
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,Blend(bg,InpColBear,0.15));
  }

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpAmplitude < 1)
      return INIT_PARAMETERS_INCORRECT;

   if(InpDevMul < 0.0)
     {
      Print("InpDevMul must be greater than or equal to zero.");
      return INIT_PARAMETERS_INCORRECT;
     }

   SetIndexBuffer(0,BufFill1,INDICATOR_DATA);
   SetIndexBuffer(1,BufFill2,INDICATOR_DATA);
   SetIndexBuffer(2,BufBand,INDICATOR_DATA);
   SetIndexBuffer(3,BufBandClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4,BufBase,INDICATOR_DATA);
   SetIndexBuffer(5,BufBaseClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(6,BufOpp,INDICATOR_DATA);
   SetIndexBuffer(7,BufMode,INDICATOR_DATA);
   SetIndexBuffer(8,BufModeClr,INDICATOR_COLOR_INDEX);

   for(int p = 0; p < 5 ; p++)
      PlotIndexSetDouble(p,PLOT_EMPTY_VALUE,EMPTY_VALUE);

//--- fill colours: faint tint of the trend colours
   ApplyFillColors();

//--- channel line colours
   PlotIndexSetInteger(1,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(1,PLOT_LINE_COLOR,0,InpColBull);
   PlotIndexSetInteger(1,PLOT_LINE_COLOR,1,InpColBear);

//--- baseline colours: index 0 = up mode, index 1 = down mode
   PlotIndexSetInteger(2,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,0,InpColModeUp);
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,1,InpColModeDn);

//--- mode switch dots, same two colours
   PlotIndexSetInteger(4,PLOT_ARROW,159);
   PlotIndexSetInteger(4,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,0,InpColModeUp);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,1,InpColModeDn);

//---
   return(INIT_SUCCEEDED);
  }

Explanation:

The indicator properties define where the indicator appears and how many buffers and plots it uses. indicator_chart_window places the indicator directly on the main price chart. indicator_buffers 9 reserves nine buffers to store the values and color indexes required for drawing, while indicator_plots 5 specifies five visual plots. The first plot, named "HalfTrend Fill," uses DRAW_FILLING to fill the space between the price midpoint and the channel line with blended bullish and bearish colors. The second plot, "HalfTrend Channel," uses DRAW_COLOR_LINE to draw a solid channel line with a width of 2. Its color changes according to the channel-direction state, independently of the HalfTrend baseline mode.

The third plot, "Baseline," uses DRAW_COLOR_LINE to display the HalfTrend baseline as a dashed line. Blue and orange represent the two baseline modes. The fourth plot, "Opposite Band," uses DRAW_LINE to display the channel boundary that is not currently selected, using a gray dotted line. The fifth plot, "Mode Switch," uses DRAW_COLOR_ARROW to mark changes in the HalfTrend baseline mode with dots. The marker colors correspond to the two baseline modes, and the marker width is set to 3. The input parameters allow users to configure the amplitude, channel and baseline colors, display range, ATR deviation multiplier, channel fill, baseline visibility, opposite-band visibility, and mode-switch markers.

The nine buffers store the data required by these plots. The first two hold the fill boundaries, while the third and fourth store the channel line values and their color indexes. The fifth and sixth store the baseline values and their color indexes. The seventh stores the opposite band, and the final two store the mode-switch marker values and their color indexes. To improve the chart's appearance, Blend() mixes the selected colors with the chart background, while ApplyFillColors() applies the resulting colors to the fill plot. The OnInit() function validates the amplitude, connects the indicator buffers, configures empty values, and sets the plot colors, drawing styles, and arrow symbol. The #property indicator_color* declarations define the initial plot colors, while PlotIndexSetInteger() assigns the colors specified by the corresponding input parameters during initialization. If the amplitude is invalid, initialization fails. Otherwise, the indicator proceeds to calculation and display.

Calculating the Baseline and Updating the Trend State

At this stage, we establish the HalfTrend baseline from rolling highs and lows while evaluating the conditions that trigger a change in the internal trend state.

Example:

//--- per-bar state (full history, kept between calls for incremental calc)
double g_tr[];
double g_atr[];
double g_maxLo[];
double g_minHi[];
double g_upLn[];
double g_dnLn[];
double g_upB[];
double g_loB[];
int    g_trnd[];
int    g_nxt[];
char   g_T[];

const int    ATR_LEN    = 100;
int     g_lastTotal = 0;
int     g_dispStart = 0;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpAmplitude < 1)
      return INIT_PARAMETERS_INCORRECT;

   if(InpDevMul < 0.0)
     {
      Print("InpDevMul must be greater than or equal to zero.");
      return INIT_PARAMETERS_INCORRECT;
     }

   SetIndexBuffer(0,BufFill1,INDICATOR_DATA);
   SetIndexBuffer(1,BufFill2,INDICATOR_DATA);
   SetIndexBuffer(2,BufBand,INDICATOR_DATA);
   SetIndexBuffer(3,BufBandClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4,BufBase,INDICATOR_DATA);
   SetIndexBuffer(5,BufBaseClr,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(6,BufOpp,INDICATOR_DATA);
   SetIndexBuffer(7,BufMode,INDICATOR_DATA);
   SetIndexBuffer(8,BufModeClr,INDICATOR_COLOR_INDEX);

   for(int p = 0; p < 5; p++)
      PlotIndexSetDouble(p,PLOT_EMPTY_VALUE,EMPTY_VALUE);

//--- fill colours: faint tint of the trend colours
   ApplyFillColors();

//--- channel line colours
   PlotIndexSetInteger(1,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(1,PLOT_LINE_COLOR,0,InpColBull);
   PlotIndexSetInteger(1,PLOT_LINE_COLOR,1,InpColBear);

//--- baseline colours: index 0 = up mode, index 1 = down mode
   PlotIndexSetInteger(2,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,0,InpColModeUp);
   PlotIndexSetInteger(2,PLOT_LINE_COLOR,1,InpColModeDn);

//--- mode switch dots, same two colours
   PlotIndexSetInteger(4,PLOT_ARROW,159);
   PlotIndexSetInteger(4,PLOT_COLOR_INDEXES,2);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,0,InpColModeUp);
   PlotIndexSetInteger(4,PLOT_LINE_COLOR,1,InpColModeDn);

   g_lastTotal = 0;

//---
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int32_t rates_total,
                const int32_t prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int32_t &spread[])
  {
   if(rates_total < ATR_LEN + InpAmplitude + 5)
      return 0;

   bool full = (prev_calculated <= 0 || prev_calculated > rates_total);
   int calcStart = full ? 0 : MathMax(0,prev_calculated - 1);
   bool newBar = (full || rates_total != g_lastTotal);

//--- calculation always runs on all bars; only drawing is limited to the display window
   g_dispStart = (InpDisplayBars <= 0) ? 0 : MathMax(0,rates_total - InpDisplayBars);

   if(full)
     {
      ArrayInitialize(BufFill1,0.0);
      ArrayInitialize(BufFill2,0.0);
      ArrayInitialize(BufBand,EMPTY_VALUE);
      ArrayInitialize(BufBandClr,0);
      ArrayInitialize(BufBase,EMPTY_VALUE);
      ArrayInitialize(BufBaseClr,0);
      ArrayInitialize(BufOpp,EMPTY_VALUE);
      ArrayInitialize(BufMode,EMPTY_VALUE);
      ArrayInitialize(BufModeClr,0);
     }

   if(ArrayResize(g_tr, rates_total) != rates_total ||
      ArrayResize(g_atr, rates_total) != rates_total ||
      ArrayResize(g_maxLo, rates_total) != rates_total ||
      ArrayResize(g_minHi, rates_total) != rates_total ||
      ArrayResize(g_upLn, rates_total) != rates_total ||
      ArrayResize(g_dnLn, rates_total) != rates_total ||
      ArrayResize(g_upB, rates_total) != rates_total ||
      ArrayResize(g_loB, rates_total) != rates_total ||
      ArrayResize(g_trnd, rates_total) != rates_total ||
      ArrayResize(g_nxt, rates_total) != rates_total ||
      ArrayResize(g_T, rates_total) != rates_total)
     {
      Print("Failed to resize one or more internal arrays. Error: ", GetLastError());
      return 0;
     }

//--- HalfTrend + ATR bands on every bar
   for(int i = calcStart; i < rates_total; i++)
     {
      //--- swing high/low and SMA of highs/lows over the amplitude window
      int s0 = MathMax(0,i - InpAmplitude + 1);
      double hiPrc = high[s0], loPrc = low[s0], sh = 0.0, sl = 0.0;
      for(int k = s0; k <= i; k++)
        {
         hiPrc = MathMax(hiPrc,high[k]);
         loPrc = MathMin(loPrc,low[k]);
         sh += high[k];
         sl += low[k];
        }
      bool smaOk = (i >= InpAmplitude - 1);
      double hiSma = sh / InpAmplitude;
      double loSma = sl / InpAmplitude;

      //--- previous state
      int    pTrnd = -1;
      int    trnd = 0, nxt = 0;
      double maxLo = low[i], minHi = high[i];
      double pUp = 0.0, pDn = 0.0;
      bool   pT = false;
      bool   hasPrev = (i > 0);
      if(hasPrev)
        {
         pTrnd = g_trnd[i - 1];
         trnd  = g_trnd[i - 1];
         nxt   = g_nxt[i - 1];
         maxLo = g_maxLo[i - 1];
         minHi = g_minHi[i - 1];
         pUp   = g_upLn[i - 1];
         pDn   = g_dnLn[i - 1];
         pT    = (g_T[i - 1] == 1);
        }

      //--- HalfTrend state machine
      double lowPrev  = hasPrev ? low[i - 1] : low[i];
      double highPrev = hasPrev ? high[i - 1] : high[i];
      if(nxt == 1)
        {
         maxLo = MathMax(loPrc,maxLo);
         if(smaOk && hiSma < maxLo && close[i] < lowPrev)
           {
            trnd = 1;
            nxt = 0;
            minHi = hiPrc;
           }
        }
      else
        {
         minHi = MathMin(hiPrc,minHi);
         if(smaOk && loSma > minHi && close[i] > highPrev)
           {
            trnd = 0;
            nxt = 1;
            maxLo = loPrc;
           }
        }

      //--- baseline construction
      double upLn = pUp, dnLn = pDn;
      if(trnd == 0)
        {
         if(hasPrev && pTrnd != 0)
            upLn = pDn;
         else
            upLn = hasPrev ? MathMax(maxLo,pUp) : maxLo;
        }
      else
        {
         if(hasPrev && pTrnd != 1)
            dnLn = pUp;
         else
            dnLn = hasPrev ? MathMin(minHi,pDn) : minHi;
        }
     }

   g_lastTotal = rates_total;

//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

Explanation:

The first condition checks whether enough price bars are available to calculate the indicator reliably, returning 0 if the minimum requirement is not met. The full variable determines whether the indicator needs to recalculate all bars, while calcStart identifies where calculation should begin when updating previously calculated data. The newBar variable checks whether this is a full calculation or the total number of bars has changed. Next, g_dispStart determines the earliest bar to display based on InpDisplayBars, although the calculations still cover all bars. If a full recalculation is required, ArrayInitialize() resets the indicator buffers to their appropriate starting values to prevent old results from remaining on the chart. Finally, ArrayResize() adjusts the internal arrays to match rates_total, ensuring enough storage is available for the trend state, ATR values, price extremes, baseline levels, channel bands, and other calculations for every bar.

For each bar, the loop identifies the highest and lowest prices within the selected InpAmplitude window, storing them in hiPrc and loPrc. It also derives the average high and low values, hiSma and loSma, using sh and sl. The s0 variable defines the window's starting bar, while smaOk checks whether enough bars are available to use these averages in the trend reversal conditions. During the initial bars, fewer than InpAmplitude bars may be available, but the accumulated highs and lows are still divided by InpAmplitude. Consequently, these early values are not true averages of the available bars. However, smaOk prevents them from being used in reversal checks until a complete calculation window is available. Next, the program restores the previous trend state, reversal references, baseline levels, and channel direction when an earlier bar exists. The hasPrev condition prevents invalid access to previous-bar data and maintains continuity between calculations.

The variable nxt controls which reversal conditions the HalfTrend state machine evaluates, determining whether the algorithm checks for a bullish or bearish transition. A bearish reversal occurs when the applicable conditions involving the average high, maxLo, and the current close are satisfied. A bullish reversal occurs when the applicable conditions involving the average low, minHi, and the current close are satisfied. After a reversal, upLn or dnLn updates the baseline using the relevant price reference. During an ongoing trend, the baseline can only rise or remain flat in a bullish state, while in a bearish state, it can only fall or remain flat. When the trend reverses, the baseline takes the value of the previous baseline from the opposite trend to maintain continuity.

Calculating the True Range and Smoothing the ATR

This stage computes the True Range for each bar and applies Wilder's smoothing to calculate the ATR. The resulting volatility measure determines the distance between the baseline and the upper and lower channel boundaries.

Example:

//--- baseline construction
   double upLn = pUp, dnLn = pDn;
   if(trnd == 0)
     {
      if(hasPrev && pTrnd != 0)
         upLn = pDn;
      else
         upLn = hasPrev ? MathMax(maxLo,pUp) : maxLo;
     }
   else
     {
      if(hasPrev && pTrnd != 1)
         dnLn = pUp;
      else
         dnLn = hasPrev ? MathMin(minHi,pDn) : minHi;
     }

//--- true range and ATR(100) using Wilder smoothing (SMA seed)
   double tr = (i == 0) ? high[i] - low[i]
               : MathMax(high[i] - low[i],MathMax(MathAbs(high[i] - close[i - 1]),MathAbs(low[i] - close[i - 1])));
   g_tr[i] = tr;
   if(i < ATR_LEN - 1)
      g_atr[i] = 0.0;
   else
      if(i == ATR_LEN - 1)
        {
         double s = 0.0;
         for(int k = 0; k < ATR_LEN; k++)
            s += g_tr[k];
         g_atr[i] = s / ATR_LEN;
        }
      else
         g_atr[i] = (g_atr[i - 1] * (ATR_LEN - 1) + tr) / ATR_LEN;

   bool valid = (i >= ATR_LEN - 1);
   double dev = valid ? InpDevMul * g_atr[i] / 2.0 : 0.0;  

Explanation:

To calculate the True Range (tr), the code evaluates the current bar's high-low range and the absolute differences between the current high and previous close, and between the current low and previous close. The largest of these values becomes the bar's True Range. It stores each result in g_tr[i] and initializes the ATR to zero until ATR_LEN bars are available. At the first valid bar, it calculates the ATR using the simple average of the initial True Range values, then applies Wilder's smoothing formula to update the ATR for subsequent bars.

The valid condition confirms when the ATR is ready for use, while dev calculates half the specified ATR-based channel width using InpDevMul * g_atr[i] / 2.0. Therefore, InpDevMul specifies the total channel width in ATR multiples, with half the calculated distance extending above and below the baseline. For example, a multiplier of 2.0 produces a total width of two ATRs, placing each boundary one ATR away from the baseline. These calculations measure market volatility and determine how far the upper and lower ATR boundaries extend from the baseline.

Constructing the ATR Channel Boundaries and Determining Breakout Direction

This stage calculates the upper and lower ATR channel boundaries around the baseline and determines the breakout direction based on price movement relative to these boundaries.

Example:

//--- true range and ATR(100) using Wilder smoothing (SMA seed)
   double tr = (i == 0) ? high[i] - low[i]
               : MathMax(high[i] - low[i],MathMax(MathAbs(high[i] - close[i - 1]),MathAbs(low[i] - close[i - 1])));
   g_tr[i] = tr;
   if(i < ATR_LEN - 1)
      g_atr[i] = 0.0;
   else
      if(i == ATR_LEN - 1)
        {
         double s = 0.0;
         for(int k = 0; k < ATR_LEN; k++)
            s += g_tr[k];
         g_atr[i] = s / ATR_LEN;
        }
      else
         g_atr[i] = (g_atr[i - 1] * (ATR_LEN - 1) + tr) / ATR_LEN;

   bool valid = (i >= ATR_LEN - 1);
   double dev = valid ? InpDevMul * g_atr[i] / 2.0 : 0.0;

   double htLn = (trnd == 0) ? upLn : dnLn;
   double upB = valid ? htLn + dev : EMPTY_VALUE;
   double loB = valid ? htLn - dev : EMPTY_VALUE;

   g_trnd[i] = trnd;
   g_nxt[i] = nxt;
   g_maxLo[i] = maxLo;
   g_minHi[i] = minHi;
   g_upLn[i] = upLn;
   g_dnLn[i] = dnLn;
   g_upB[i] = upB;
   g_loB[i] = loB;

//--- direction flag: crossover of the upper band / crossunder of the lower band
   bool T = pT;
   if(valid && i > 0 && i - 1 >= ATR_LEN - 1)
     {
      if(close[i] > upB && close[i - 1] <= g_upB[i - 1])
         T = true;
      if(close[i] < loB && close[i - 1] >= g_loB[i - 1])
         T = false;
     }
   g_T[i] = T ? 1 : 0;

Explanation:

The program determines the channel direction by initially carrying forward the previous direction stored in pT. Once the ATR values are valid and a previous bar is available, the indicator sets the channel direction to true when the current close crosses above the current upper band, provided the previous close was at or below the previous upper band. The direction changes to false when the current close crosses below the current lower band, provided the previous close was at or above the previous lower band. The resulting state is recorded in g_T[i] as 1 or 0, preserving the last confirmed channel direction for subsequent bars. This state remains unchanged until a qualifying closing-price crossing occurs in the opposite direction.

Displaying the Channel, Baseline, Fill, and Mode-Switch Markers

Display the ATR channel, trend baseline, colored fill, opposite band, and mode-switch markers according to the calculated trend state and display settings.

Example:

//--- HalfTrend + ATR bands on every bar
for(int i = calcStart; i < rates_total; i++)
  {
//--- swing high/low and SMA of highs/lows over the amplitude window
   int s0 = MathMax(0,i - InpAmplitude + 1);
   double hiPrc = high[s0], loPrc = low[s0], sh = 0.0, sl = 0.0;
   for(int k = s0; k <= i; k++)
     {
      hiPrc = MathMax(hiPrc,high[k]);
      loPrc = MathMin(loPrc,low[k]);
      sh += high[k];
      sl += low[k];
     }
   bool smaOk = (i >= InpAmplitude - 1);
   double hiSma = sh / InpAmplitude;
   double loSma = sl / InpAmplitude;

//--- previous state
   int    pTrnd = -1;
   int    trnd = 0, nxt = 0;
   double maxLo = low[i], minHi = high[i];
   double pUp = 0.0, pDn = 0.0;
   bool   pT = false;
   bool   hasPrev = (i > 0);
   if(hasPrev)
     {
      pTrnd = g_trnd[i - 1];
      trnd  = g_trnd[i - 1];
      nxt   = g_nxt[i - 1];
      maxLo = g_maxLo[i - 1];
      minHi = g_minHi[i - 1];
      pUp   = g_upLn[i - 1];
      pDn   = g_dnLn[i - 1];
      pT    = (g_T[i - 1] == 1);
     }

//--- HalfTrend state machine
   double lowPrev  = hasPrev ? low[i - 1] : low[i];
   double highPrev = hasPrev ? high[i - 1] : high[i];
   if(nxt == 1)
     {
      maxLo = MathMax(loPrc,maxLo);
      if(smaOk && hiSma < maxLo && close[i] < lowPrev)
        {
         trnd = 1;
         nxt = 0;
         minHi = hiPrc;
        }
     }
   else
     {
      minHi = MathMin(hiPrc,minHi);
      if(smaOk && loSma > minHi && close[i] > highPrev)
        {
         trnd = 0;
         nxt = 1;
         maxLo = loPrc;
        }
     }

//--- baseline construction
   double upLn = pUp, dnLn = pDn;
   if(trnd == 0)
     {
      if(hasPrev && pTrnd != 0)
         upLn = pDn;
      else
         upLn = hasPrev ? MathMax(maxLo,pUp) : maxLo;
     }
   else
     {
      if(hasPrev && pTrnd != 1)
         dnLn = pUp;
      else
         dnLn = hasPrev ? MathMin(minHi,pDn) : minHi;
     }

//--- true range and ATR(100) using Wilder smoothing (SMA seed)
   double tr = (i == 0) ? high[i] - low[i]
               : MathMax(high[i] - low[i],MathMax(MathAbs(high[i] - close[i - 1]),MathAbs(low[i] - close[i - 1])));
   g_tr[i] = tr;
   if(i < ATR_LEN - 1)
      g_atr[i] = 0.0;
   else
      if(i == ATR_LEN - 1)
        {
         double s = 0.0;
         for(int k = 0; k < ATR_LEN; k++)
            s += g_tr[k];
         g_atr[i] = s / ATR_LEN;
        }
      else
         g_atr[i] = (g_atr[i - 1] * (ATR_LEN - 1) + tr) / ATR_LEN;

   bool valid = (i >= ATR_LEN - 1);
   double dev = valid ? InpDevMul * g_atr[i] / 2.0 : 0.0;

   double htLn = (trnd == 0) ? upLn : dnLn;
   double upB = valid ? htLn + dev : EMPTY_VALUE;
   double loB = valid ? htLn - dev : EMPTY_VALUE;

   g_trnd[i] = trnd;
   g_nxt[i] = nxt;
   g_maxLo[i] = maxLo;
   g_minHi[i] = minHi;
   g_upLn[i] = upLn;
   g_dnLn[i] = dnLn;
   g_upB[i] = upB;
   g_loB[i] = loB;

//--- direction flag: crossover of the upper band / crossunder of the lower band
   bool T = pT;
   if(valid && i > 0 && i - 1 >= ATR_LEN - 1)
     {
      if(close[i] > upB && close[i - 1] <= g_upB[i - 1])
         T = true;
      if(close[i] < loB && close[i - 1] >= g_loB[i - 1])
         T = false;
     }
   g_T[i] = T ? 1 : 0;

//--- buffers (drawn only inside the display window)
   bool flip = (T != pT);
   bool plotOk = (i >= g_dispStart) && valid;
   double band = T ? loB : upB;

   BufBand[i] = (plotOk && !flip) ? band : EMPTY_VALUE;
   BufBandClr[i] = T ? 0 : 1;

//--- the band that is not drawn as the channel line
   BufOpp[i] = (InpShowOpposite && plotOk && !flip) ? (T ? upB : loB) : EMPTY_VALUE;

//--- the fill never holds empty values: where nothing should show, both edges
//--- sit on the same price (zero thickness) so the plot has nothing to stretch to
   double mid = (high[i] + low[i]) / 2.0;
   BufFill1[i] = mid;
   BufFill2[i] = (InpShowFill && plotOk && !flip) ? band : mid;

//--- baseline, coloured by its mode: 0 = up mode, 1 = down mode
   BufBase[i] = (InpShowBaseline && plotOk) ? htLn : EMPTY_VALUE;
   BufBaseClr[i] = (trnd == 0) ? 0 : 1;

//--- dot where the baseline mode switches (colour = the mode it switches into)
   bool modeSwitch = hasPrev && (trnd != pTrnd);
   BufMode[i] = (InpShowModeSw && plotOk && modeSwitch) ? htLn : EMPTY_VALUE;
   BufModeClr[i] = (trnd == 0) ? 0 : 1;
  }

//--- blank the bars that just slid out of the display window
if(!full && newBar)
  {
   for(int k = MathMax(0,g_dispStart - 3); k < g_dispStart; k++)
     {
      double mid = (high[k] + low[k]) / 2.0;
      BufFill1[k] = mid;
      BufFill2[k] = mid;
      BufOpp[k]  = EMPTY_VALUE;
      BufMode[k] = EMPTY_VALUE;
      BufBand[k] = EMPTY_VALUE;
      BufBase[k] = EMPTY_VALUE;
     }
   ApplyFillColors();
  }

g_lastTotal = rates_total;

Explanation:

The code first checks whether the channel direction has changed using flip and whether the current bar is within the display window and has valid ATR values using plotOk. The variable band selects the lower ATR boundary when the channel-direction state is true or the upper boundary when it is false. BufBand stores the selected boundary, while BufBandClr assigns its bullish or bearish color according to the channel direction. When enabled, BufOpp displays the opposite boundary, which is not currently selected. For the fill, the mid calculates the midpoint between the bar's high and low. BufFill1 stores this midpoint, while BufFill2 stores the selected boundary when the fill is enabled and the bar is valid. Otherwise, both buffers receive the midpoint, collapsing the fill to zero width.

BufBase displays the HalfTrend baseline, and BufBaseClr assigns its color according to the current baseline mode. The modeSwitch condition detects changes in this baseline mode and places a dot at the baseline when mode-switch markers are enabled. When a new bar appears, the second section clears drawing data for bars that have moved outside the display window. The loop resets the fill boundaries to the bar midpoint and sets BufOpp, BufMode, BufBand, and BufBase to EMPTY_VALUE, preventing these plots from displaying outdated values for those bars. ApplyFillColors() then reapplies the background-blended colors to the fill plot.

Output:

Figure 4. HalfTrend Channel Indicator

Figure 4. HalfTrend Channel Indicator


Conclusion

By completing this article, we have developed a HalfTrend Channel indicator in MQL5 that combines HalfTrend trend-state calculations with ATR-based channel boundaries to track price breakouts and baseline mode changes. The focus was on understanding how the baseline is constructed from rolling price extremes, how ATR is calculated and smoothed to determine the channel boundaries, and how price movement across these boundaries updates the channel direction. Throughout this implementation, we have learned how to:

  • calculate rolling price extremes and average highs and lows using the amplitude period;
  • update the HalfTrend trend state using defined bullish and bearish reversal conditions;
  • construct the baseline from tracked price references;
  • calculate True Range and smooth the ATR using Wilder's method;
  • construct upper and lower ATR channel boundaries around the baseline;
  • determine channel direction when the closing price crosses above the upper ATR boundary or below the lower ATR boundary;
  • display the channel, opposite band, baseline, fill, and mode-switch markers; and
  • manage indicator buffers and limit chart drawings to the selected display window.

This project combines HalfTrend trend analysis with ATR-based channel boundaries to provide a visual representation of trend changes and price breakouts. The resulting tool can help traders study directional changes, observe price movement beyond the channel boundaries, and gain additional context for technical analysis.

Attached files |
Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5 Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5
A compact MFE/MAE recorder in pure MQL5 samples excursion while a position is open and writes one CSV row per closed position, measured in R and frozen at entry. A companion script prints a reach-rate table per asset class: the share of trades that ever reached each level. In a 226-position sample, three of the four classes never reached the 3R target the system was using. Use it to test whether a target is reachable before trusting it.
Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects
The EA evaluates indicator signals from buffers or dated chart objects on historical closed bars, keeping execution separate from account reports. It models virtual positions with user-defined entry timing, stop loss, staged targets, partial exits, break-even, and optional reversal on opposite signals, and renders exit paths and statistics on the chart. EURUSD examples compare SMA buffer/object sources and test confirmed RSI divergence, illustrating a practical way to judge signals before building a dedicated EA.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol
This article shows how to build a native Cassandra CQL v4 client in MQL5 over a raw socket, without a REST or gRPC proxy. It details CQL frame encoding, correct handling of prepared-statement ids as short bytes, and a lot-sizing error found in the Strategy Tester, with targeted guards. You get a reusable client class, an EA that batches closed-trade inserts, and a script that reads rows back and cross-checks them with terminal history.