preview
Building an ATR-Based Indicator for Potential Support and Resistance in MQL5

Building an ATR-Based Indicator for Potential Support and Resistance in MQL5

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

Introduction

Support and resistance areas often become apparent only after the price has reacted to the same region several times. However, waiting for repeated reactions means potential price levels may only become clear after the market structure has already developed. How can we define potential reaction areas consistently without relying solely on those repeated tests?

In this article, we will build an ATR-based indicator in MQL5 that establishes volatility-based boundaries around a bar's midpoint. The boundaries are calculated using a smoothed ATR and remain fixed while the current price structure is active. A new structure is created only when a completed candle meets the indicator's boundary-break condition. We will implement the volatility calculations, structure initialization and resets, midpoint conditions, breakout detection, and optional failed-breakout markers. The resulting indicator provides a configurable framework for examining potential price reaction areas, rather than confirming support and resistance through repeated reactions.


Project Overview and Implementation Plan

Before implementing the indicator in MQL5, we define its structure and the required build steps. The plan links each component to the goal: measure volatility with ATR, set adaptive boundaries, detect breaks, and visualize the structure.

What We Are Building

In this project, we will build an adaptive support and resistance indicator for MetaTrader 5 that uses a smoothed volatility estimate to establish potential price reaction areas before repeated tests occur. It builds upper and lower boundaries around a central price, splits the range into zones, and detects boundary breaks, midpoint conditions, and returns after tests. The indicator displays these conditions through colored zones, horizontal levels, and chart markers.

The initial central price is the midpoint of the bar's high and low. The smoothed ATR, multiplied by the configured multiplier, determines the distance from the central price to the upper and lower boundaries. Each side is then divided by a midpoint, creating upper and lower zones that may serve as potential resistance and support areas. As new bars form, the indicator detects an upward boundary break when the previous bar's low is at or below the upper boundary and the current completed bar's low moves above it. A downward break requires the previous bar's high to be at or above the lower boundary and the current completed bar's high to move below it. A confirmed break resets the structure around the current bar's midpoint and updates its directional state.

While a structure remains unchanged, the indicator also checks how price interacts with its midpoint levels. A bullish or bearish midpoint condition can be marked when price crosses the corresponding midpoint and satisfies the required historical condition. The indicator also detects when price returns inside an outer boundary after the previous bar reached or crossed it, displaying optional X markers for these events. Finally, the structures are represented using colored zones, horizontal boundary and midpoint lines, and chart markers. Older chart objects are automatically removed when they fall outside the selected display range.

Figure 1. What We Are Building

Figure 1. What We Are Building

Implementation Plan

In this section, we will outline the development plan that will be followed in MQL5 before moving into the actual implementation.

1. Calculating and Smoothing the ATR

Before creating the adaptive price structure, the indicator estimates market volatility using ATR(200). The raw ATR values are obtained through an indicator handle and then averaged over 100 bars to smooth the volatility estimate further. The resulting value is multiplied by the configured multiplier and used to determine the distance from the central price to the upper and lower boundaries.

In this step, the indicator:

  • creates the required indicator inputs, including the ATR multiplier and display, zone, color, filtering, and failed-breakout settings;
  • creates an ATR(200) indicator handle during initialization;
  • verifies that the ATR handle was created successfully;
  • checks that enough historical bars are available for the ATR and smoothing calculations;
  • waits for the ATR handle to finish calculating before processing the data;
  • copies the ATR values into an internal array for further calculations;
  • resizes the smoothed ATR array according to the number of available bars;
  • calculates a 100-bar average of the raw ATR values;
  • multiplies the smoothed ATR by the configured multiplier;
  • stores the resulting value for use in determining the width of each price structure.

2. Creating the Price Structure and Detecting Boundary Crosses

After calculating the smoothed ATR, the indicator uses the midpoint of each bar to establish and manage the central price structure. This midpoint is calculated from the bar's high and low prices and provides the reference price around which the upper and lower boundaries are created. The current structure values are then carried forward from the previous bar, including the central price, upper and lower boundaries, midpoint levels, and directional state.

For example, if a bar has a high of 101.00 and a low of 99.00, its midpoint is:

Midpoint= (101.00 + 99.00) ÷ 2 = 100.00

Figure 2. Midpoint

Figure 2. Midpoint

This value serves as the central price of the bar, around which the smoothed ATR determines the upper and lower boundaries. As new bars form, the indicator checks for boundary breaks on completed bars and resets the structure around the new bar's midpoint when either breakout condition is met.

In this step, the indicator:

  • calculates the midpoint of each bar using its high and low prices;
  • loads the previous central price, upper and lower boundaries, and their midpoint levels;
  • carries forward the previous directional state and structure starting time;
  • identifies the initial bar where the first price structure can be established;
  • ensures that boundary-break conditions are evaluated only on completed bars;
  • detects an upper breakout when the current bar's low is above the upper boundary;
  • detects a lower breakout when the current bar's high is below the lower boundary;
  • prepares the structure for recalculation when either boundary-break condition is met.

3. Initializing and Updating the Price Structure

After calculating the bar midpoint and checking for boundary-break conditions, the indicator initializes or resets the price structure when required. The bar midpoint becomes the new central price, while the smoothed ATR, multiplied by the configured multiplier, determines the distance from the center to each boundary. A midpoint level divides each side of the structure into two sections. For example, suppose the central price is 100.00 and the final ATR-based distance is 4.00 points. The upper boundary is placed at 104.00, while the lower boundary is placed at 96.00, giving the structure a total width of 8.00 points. The midpoint levels are then calculated halfway between the central price and their respective boundaries.

Level
Calculation
Price
Purpose 
Upper boundary
100.00 + 4.00
104.00
 Upper limit of the structure
Upper midpoint
(100.00 + 104.00) ÷ 2
102.00
 Midpoint of the upper side
Central price
Bar midpoint
100.00
 Center of the structure
Lower midpoint
(100.00 + 96.00) ÷ 2
98.00
 Midpoint of the lower side
Lower boundary
100.00 − 4.00
96.00
 Lower limit of the structure

Figure 3. Support and Resistance

Figure 3. Support and Resistance

4. Evaluating Price Movement within the Structure

Once the price structure has been established, the indicator evaluates how the high and low of each confirmed bar interact with the structure's internal midpoint levels and outer boundaries. This allows it to identify bullish and bearish conditions around the Lower Midpoint and Upper Midpoint, while also detecting failed breakouts at the Upper Boundary and Lower Boundary.

For the midpoint conditions, a bullish condition occurs when the previous bar's low is at or below the Lower Midpoint, while the current bar's low moves above the Lower Midpoint.

Figure 4. Bullish Condition

Figure 4. Bullish Condition

This helps confirm that the price has moved back above the Lower Midpoint rather than simply remaining on the same side of it. The bearish condition follows the opposite movement. The previous bar's high must be at or above the Upper Midpoint, while the current bar's high moves below it. In addition, the high ten bars earlier must already be below the Upper Midpoint.

Figure 5. Bearish Condition

Figure 5. Bearish Condition

The indicator also evaluates whether the price has made a true breakout or a failed breakout at the outer boundaries. For an upward breakout, the low of the previous bar must be at or below the Upper Boundary, while the current bar's low moves above the Upper Boundary.

Figure 6. Resistance Breakout

Figure 6. Resistance Breakout

Failed breakouts can optionally be marked with an X, with failed upward breakouts placed above the relevant high and failed downward breakouts below the relevant low. This makes it easy to distinguish an attempted boundary break that returned inside the structure from a confirmed break that continued beyond the boundary.

Figure 7. Failed Breakout

Figure 7. Failed Breakout

5. Drawing the Price Structure and Managing Chart Objects

After the price conditions have been evaluated, the indicator represents the active and historical structures directly on the chart using rectangles, horizontal lines, and directional markers. Each structure is identified by its starting time so that its zones and levels can be created and extended as new bars form. When a boundary break is confirmed, a circle marker is placed at the confirming candle's low for an upward breakout or at its high for a downward breakout. Bullish and bearish midpoint conditions are represented using upward and downward triangle markers, respectively. These markers are positioned slightly away from the confirming bar's low or high using a small ATR-based offset so they remain visually separated from the candle.

In this step, the indicator:

  • creates the upper and lower zone rectangles between their respective midpoint and boundary levels;
  • extends each zone as new bars form while the same price structure remains active;
  • draws the Upper Boundary, Upper Midpoint, Central Price, Lower Midpoint, and Lower Boundary as horizontal lines;
  • uses solid lines for the outer boundaries and midpoint levels and a dotted line for the Central Price;
  • checks whether the current bar is within the configured display range before drawing the structure;
  • places a circle marker at the confirming candle's low for an upward breakout or at its high for a downward breakout;
  • places an upward triangle below the confirming candle when a bullish condition is detected;
  • places a downward triangle above the confirming candle when a bearish condition is detected;
  • optionally places an X marker above the confirming candle for a failed upward breakout;
  • optionally places an X marker below the confirming candle for a failed downward breakout;
  • applies a small ATR-based offset to separate the triangle and X markers from the candle;
  • prevents duplicate chart objects by using unique names based on the structure's starting time;
  • removes objects that have completely moved outside the selected display range;
  • refreshes the chart after the objects have been created, extended, or removed.


    Implementation in MQL5

    With the indicator structure and implementation plan clearly defined, we can now proceed to the implementation phase. The ATR-based support and resistance indicator will be developed in stages, with each part of the design translated into functional MQL5 code. The implementation will cover the volatility calculation, adaptive price structure, price movement conditions, chart objects, and display management, while the purpose and logic of each section are explained throughout the process.

    Calculating and Smoothing the ATR

    The indicator first establishes its calculation settings and creates the ATR(200) handle required to measure market volatility.

    Example:

    #property indicator_chart_window
    #property indicator_plots   0
    
    //--- INPUTS
    input double InpMulti          = 4.0;                  // Multiplier applied to the smoothed ATR to determine distance from the center to each boundary
    input int    InpDisplayBars    = 500;                  // Number of recent bars for which range objects remain visible
    input bool   InpFillZones      = true;                 // Enable or disable filling of the upper and lower zones
    input color  InpZoneColorUpper = C'34,88,209';         // Color of the upper zone
    input color  InpZoneColorLower = C'247,207,158';       // Color of the lower zone
    input color  InpColorBullish   = C'29,172,112';        // Color used for bullish breakout and buy markers
    input color  InpColorBearish   = C'223,58,121';        // Color used for bearish breakout and sell markers
    input bool   InpDebugLog       = false;                // Enable debug messages in the Experts log
    input bool   InpFilterSignals  = false;                // Show midpoint signals only when they agree with the current trend
    input bool   InpShowX          = false;                // Show X markers for failed breakouts
    
    //--- ATR calculation
    int    g_atrHandle = INVALID_HANDLE;                   // Handle for the ATR(200) indicator
    double g_atrRaw[];
    
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+
    int OnInit()
      {
    //--- Create the ATR(200) indicator handle
       g_atrHandle = iATR(NULL, 0, 200);
    
    //--- Stop initialization if the ATR handle could not be created
       if(g_atrHandle == INVALID_HANDLE)
         {
          Print("Failed to create ATR(200) handle");
          return(INIT_FAILED);
         }
    
    //--- Validate ATR multiplier
       if(InpMulti <= 0)
         {
          Print("InpMulti must be greater than 0.");
          return(INIT_PARAMETERS_INCORRECT);
         }
    
    //--- Validate display bars
       if(InpDisplayBars < 1)
         {
          Print("InpDisplayBars must be greater than 0.");
          return(INIT_PARAMETERS_INCORRECT);
         }
    //---
       return(INIT_SUCCEEDED);
      }
    
    //+------------------------------------------------------------------+
    //| Custom indicator deinitialization                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
      {
    //--- Release the ATR indicator handle when the indicator is removed
       if(g_atrHandle != INVALID_HANDLE)
          IndicatorRelease(g_atrHandle);
      }
    //+------------------------------------------------------------------+
    //| 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 < 302)
          return(0); // not enough bars yet for ATR(200)+SMA(100) to be valid
    
       if(BarsCalculated(g_atrHandle) < rates_total)
          return(prev_calculated); // ATR handle hasn't finished calculating, wait
    
       if(ArrayResize(g_atrRaw, rates_total) < 0)
          return(prev_calculated); // resize failed, retry next tick
    
       if(CopyBuffer(g_atrHandle, 0, 0, rates_total, g_atrRaw) <= 0)
          return(prev_calculated); // copy failed, retry next tick
    
       ArraySetAsSeries(g_atrRaw, false); // match non-series order used elsewhere
    
    //--- Determine the first bar that needs to be recalculated
       int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
       if(start < 301)
          start = 0;
    
    //--- Process each bar from the recalculation starting point
       for(int i = start; i < rates_total; i++)
         {
    
         }
    
    //--- return value of prev_calculated for next call
       return(rates_total);
      }

    Explanation:

    The indicator is displayed directly on the main price chart without standard indicator plots, while its inputs control how the price structure is calculated and visualized. The configured multiplier determines the distance from the center to each boundary using the smoothed ATR, while the display setting controls how many recent bars remain visible. Zone filling can be enabled or disabled, and separate colors can be assigned to the upper and lower zones as well as bullish and bearish chart markers. Debug messages can also be enabled, midpoint conditions can be filtered according to the current direction, and optional X markers can be displayed for potential failed breakouts. When directional filtering is enabled, buy conditions may be suppressed until the first confirmed upside breakout establishes a bullish state, because the initial trend state defaults to bearish.

    During initialization, the indicator creates the ATR(200) calculation and verifies that it was created successfully. If the calculation cannot be initialized, the indicator stops with an error. When the indicator is removed, the ATR resource is released to ensure proper cleanup. Before processing the price structure, the indicator checks that at least 302 historical bars are available. This threshold ensures enough data to initialize the first structure at index 301. ATR smoothing begins at index 299, where the indicator averages the current ATR value with the preceding 99 values to produce a 100-bar smoothed estimate.

    The structure itself is initialized at index 301, allowing the indicator to establish its central price and upper and lower boundaries using the smoothed ATR. The indicator then confirms that the ATR calculation is complete, prepares storage for the ATR values, and copies the calculated data into the array. Finally, the values are arranged in the required order before the indicator determines the bar from which recalculation should continue.

    With the raw ATR values prepared, the next step is to smooth them over 100 bars. This produces the volatility value used to determine the width of each price structure.

    Example:

    //--- ATR calculation
    int    g_atrHandle = INVALID_HANDLE;                   // Handle for the ATR(200) indicator
    double g_atrRaw[];
    
    //--- Range and state arrays
    double ATRSmooth[];                                    // Stores the 100-bar smoothed ATR multiplied by InpMulti

    //+------------------------------------------------------------------+
    //| 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 < 302)
          return(0); // not enough bars yet for ATR(200)+SMA(100) to be valid
    
       if(BarsCalculated(g_atrHandle) < rates_total)
          return(prev_calculated); // ATR handle hasn't finished calculating, wait
    
       if(ArrayResize(g_atrRaw, rates_total) < 0)
          return(prev_calculated); // resize failed, retry next tick
    
       if(CopyBuffer(g_atrHandle, 0, 0, rates_total, g_atrRaw) <= 0)
          return(prev_calculated); // copy failed, retry next tick
    
       ArraySetAsSeries(g_atrRaw, false); // match non-series order used elsewhere
    
    //--- Determine the first bar that needs to be recalculated
       int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
       if(start < 301)
          start = 0;
    
    //--- Resize arrays to match the number of available bars
       ArrayResize(ATRSmooth,     rates_total);
    
       ArraySetAsSeries(time, false);
       ArraySetAsSeries(high, false);
       ArraySetAsSeries(low, false);
    
    //--- Process each bar from the recalculation starting point
       for(int i = start; i < rates_total; i++)
         {
          //--- Calculate the smoothed ATR used to determine the distance from the center to each boundary
          double atrSmooth = EMPTY_VALUE;
          if(i >= 299)
            {
             double sum = 0;
             for(int k = i - 99; k <= i; k++)
                sum += g_atrRaw[k];
             atrSmooth = (sum / 100.0) * InpMulti;
            }
          ATRSmooth[i] = atrSmooth;
         }
    
    //--- return value of prev_calculated for next call
       return(rates_total);
      }
    //+------------------------------------------------------------------+

    Explanation:

    The code first resizes the smoothed ATR array to hold a value for every available bar. It then processes each bar from the recalculation starting point and, once at least 100 ATR values are available, sums the ATR values from the current bar and previous 99 bars. This sum is divided by 100 to obtain the 100-bar average ATR, which is then multiplied by the configured ATR multiplier to determine the final range width. The resulting value is stored in the smoothed ATR array for use when creating the price structure.

    The selected values are heuristic defaults rather than optimized parameters. ATR(200) and the additional 100-bar smoothing prioritize stable volatility estimates over responsiveness; shorter periods would react faster but could produce more fluctuating boundaries. The multiplier of 4.0 determines the distance from the central price to each outer boundary: smaller values create narrower structures and generally more frequent breaks, while larger values create wider structures and fewer breaks. The ten-bar lookback used for midpoint conditions is a fixed historical filter in the current implementation. These settings should be evaluated for the chosen symbol and timeframe and should not be interpreted as evidence of predictive or trading performance.

    Creating the Price Structure and Detecting Boundary Crosses

    Using the bar midpoint as the central price, the indicator applies the smoothed ATR to calculate the upper and lower boundaries and their corresponding midpoint levels.

    Example:

    //--- Range and state arrays
    double ATRSmooth[];                                    // Stores the 100-bar smoothed ATR multiplied by InpMulti
    double Value[];                                        // Stores the central price of each range
    double ValueUpper[];                                   // Stores the upper boundary of each range
    double ValueLower[];                                   // Stores the lower boundary of each range
    double ValueUpperMid[];                                // Stores the midpoint between the central price and upper boundary
    double ValueLowerMid[];                                // Stores the midpoint between the central price and lower boundary
    double Trend[];                                        // Stores the current directional state: 1 for bullish, 0 for bearish
    double SegStartTime[];                                 // Stores the starting time of each range segment

    //--- Resize arrays to match the number of available bars
    ArrayResize(ATRSmooth, rates_total);
    ArrayResize(Value, rates_total);
    ArrayResize(ValueUpper, rates_total);
    ArrayResize(ValueLower, rates_total);
    ArrayResize(ValueUpperMid, rates_total);
    ArrayResize(ValueLowerMid, rates_total);
    ArrayResize(Trend, rates_total);
    ArrayResize(SegStartTime, rates_total);
    
    ArraySetAsSeries(time, false);
    ArraySetAsSeries(high, false);
    ArraySetAsSeries(low, false);
    
    //--- Process each bar from the recalculation starting point
    for(int i = start; i < rates_total; i++)
      {
    //--- Calculate the smoothed ATR used to determine the distance from the center to each boundary
       double atrSmooth = EMPTY_VALUE;
       if(i >= 299)
         {
          double sum = 0;
          for(int k = i - 99; k <= i; k++)
             sum += g_atrRaw[k];
          atrSmooth = (sum / 100.0) * InpMulti;
         }
       ATRSmooth[i] = atrSmooth;
    
    //--- Calculate the midpoint of the current bar
       double hl2 = (high[i] + low[i]) / 2.0;
    
    //--- Load the previous range values and directional state
       double vVal, vUp, vLo, vUpMid, vLoMid, vSegStart;
       bool   vTrend;
       if(i == 0)
         {
          vVal = EMPTY_VALUE;
          vUp = EMPTY_VALUE;
          vLo = EMPTY_VALUE;
          vUpMid = EMPTY_VALUE;
          vLoMid = EMPTY_VALUE;
          vTrend = false;
          vSegStart = 0;
         }
       else
         {
          vVal = Value[i-1];
          vUp  = ValueUpper[i-1];
          vLo  = ValueLower[i-1];
          vUpMid = ValueUpperMid[i-1];
          vLoMid = ValueLowerMid[i-1];
          vTrend = (Trend[i-1] != 0.0);
          vSegStart = SegStartTime[i-1];
         }
    
    //--- Check whether price has crossed either outer boundary
       bool crossUpper = false;
       bool crossLower = false;
    
       bool   isInit = (i == 301);
       bool   confirmed = (i < rates_total - 1);
    
       if(!isInit && vVal != EMPTY_VALUE && i > 0)
         {
          crossUpper = confirmed && low[i-1]  <= vUp && low[i]  > vUp;
          crossLower = confirmed && high[i-1] >= vLo && high[i] < vLo;
         }
      }

    Explanation:

    These arrays are resized to match the total number of available bars, providing enough space to store the central price, upper and lower boundaries, midpoint levels, directional state, and starting time of each price structure. For each bar, the midpoint is calculated by adding its high and low prices and dividing the result by two. This midpoint provides the central price around which the upper and lower boundaries are created. The existing structure is carried forward by retrieving its values from the previous bar. The central price, upper and lower boundaries, midpoint levels, directional state, and starting time are preserved for continued processing. On the first bar, no previous structure exists, so the price levels are set to EMPTY_VALUE, the direction is initialized to false, and the structure starting time is set to zero.

    For each subsequent bar, the values are retrieved from index i-1 of their respective arrays. This allows the same price structure to remain active across multiple bars until an event, such as a boundary break, requires a new structure. Two Boolean variables are initialized to false to record whether an upward or downward boundary break occurs on the current bar. The isInit condition identifies bar 301 as the point where the first structure can be initialized, allowing sufficient historical data for the ATR and smoothing calculations. This initialization bar is not treated as a boundary break because no previous structure has been established for comparison.

    The confirmed condition ensures that boundary breaks are evaluated only on completed bars. For this indexing approach, the price and time arrays must be explicitly configured from oldest to newest. Under this arrangement, i < rates_total - 1 excludes the final array element, which represents the currently forming bar. This prevents temporary price movements on that bar from triggering a structure reset.

    Once the initialization bar has passed and a valid previous structure exists, the code checks for boundary breaks. An upper break occurs when the previous bar's low was at or below the upper boundary (vUp), while the current bar's low is above it. Similarly, a lower break occurs when the previous bar's high was at or above the lower boundary (vLo), while the current bar's high is below it. These conditions require the entire current candle to lie beyond the respective boundary before the structure is considered broken.

    Initializing and Updating the Price Structure

    Price interaction with the structure's midpoint levels and outer boundaries is examined to identify bullish and bearish conditions, along with failed breakout attempts.

    Example:

    //--- Check whether price has crossed either outer boundary
       bool crossUpper = false;
       bool crossLower = false;
    
       bool   isInit = (i == 301);
       bool   confirmed = (i < rates_total - 1);
    
       if(!isInit && vVal != EMPTY_VALUE && i > 0)
         {
          crossUpper = confirmed && low[i-1]  <= vUp && low[i]  > vUp;
          crossLower = confirmed && high[i-1] >= vLo && high[i] < vLo;
         }
    
    //--- Store the broken boundary before the range is reset
       double brokenUp = vUp;
       double brokenLo = vLo;
    
    //--- Initialize or reset the range when required
       bool resetNow = false;
       if(isInit)
         {
          vVal = hl2;
          vUp = hl2 + atrSmooth;
          vLo = hl2 - atrSmooth;
          vUpMid = (vVal + vUp) / 2.0;
          vLoMid = (vVal + vLo) / 2.0;
          resetNow = true;
         }
       else
          if(vVal != EMPTY_VALUE)
            {
             if(crossUpper || crossLower)
               {
                vVal = hl2;
                vUp = hl2 + atrSmooth;
                vLo = hl2 - atrSmooth;
                vUpMid = (vVal + vUp) / 2.0;
                vLoMid = (vVal + vLo) / 2.0;
                resetNow = true;
               }
            }
    
    //--- Record the starting time of the current range segment
       vSegStart = resetNow ? (double)time[i] : vSegStart;
    
    //--- Update the directional state after a boundary break
       if(crossUpper)
          vTrend = true;
       if(crossLower)
          vTrend = false;
    
    //--- Store the current range values and state
       Value[i] = vVal;
       ValueUpper[i] = vUp;
       ValueLower[i] = vLo;
       ValueUpperMid[i] = vUpMid;
       ValueLowerMid[i] = vLoMid;
       Trend[i] = vTrend ? 1.0 : 0.0;
       SegStartTime[i] = vSegStart;
    

    Explanation:

    When processing the initial bar, the current bar's midpoint becomes the central price, while the smoothed ATR determines the distance to the upper and lower boundaries. The corresponding upper and lower midpoint levels are then calculated and resetNow is set to true to indicate that a new structure has been created.

    Once an existing structure is available, the code checks whether either outer boundary has been crossed. If an upper or lower cross is detected, the structure is reset around the current bar's midpoint using the latest smoothed ATR value. New upper and lower boundaries and their midpoint levels are calculated, while resetNow records that the previous structure has ended and a new one has started. Whenever a new structure is created, its starting time is recorded using the current bar's time. The directional state is then updated based on which boundary was crossed: an upper cross sets the direction to bullish, while a lower cross sets it to bearish. Finally, the current structure values and state are stored in their respective arrays so they can be carried forward and used when processing the next bar.

    Evaluating Price Movement within the Structure

    Price interactions with the structure's midpoint levels and outer boundaries are examined to identify bullish and bearish conditions, as well as failed breakout attempts.

    Example:

    //--- Record the starting time of the current range segment
       vSegStart = resetNow ? (double)time[i] : vSegStart;
    
    //--- Update the directional state after a boundary break
       if(crossUpper)
          vTrend = true;
       if(crossLower)
          vTrend = false;
    
    //--- Store the current range values and state
       Value[i] = vVal;
       ValueUpper[i] = vUp;
       ValueLower[i] = vLo;
       ValueUpperMid[i] = vUpMid;
       ValueLowerMid[i] = vLoMid;
       Trend[i] = vTrend ? 1.0 : 0.0;
       SegStartTime[i] = vSegStart;
    
    //--- Check whether the range remained unchanged from the previous bar
       bool stable = (i > 0 && vVal != EMPTY_VALUE && Value[i-1] != EMPTY_VALUE && vVal == Value[i-1]);
    
    //--- Initialize midpoint and failed-breakout conditions
       bool buySig = false, sellSig = false, fakeUp = false, fakeDn = false;
       if(stable && confirmed && i >= 11)
         {
          buySig  = (low[i-1]  <= vLoMid && low[i]  > vLoMid) && low[i-10]  > vLoMid;
          sellSig = (high[i-1] >= vUpMid && high[i] < vUpMid) && high[i-10] < vUpMid;
          fakeUp  = (high[i-1] >= vUp   && high[i] < vUp);
          fakeDn  = (low[i-1]  <= vLo   && low[i]  > vLo);
         }
    

    Explanation:

    Before evaluating price movement within the structure, the code confirms that the structure has remained unchanged from the previous bar. It checks that both central prices are valid and equal and that a previous bar is available. This ensures that midpoint conditions and failed-breakout checks are only evaluated after the newly created structure has become established. In other words, the indicator only evaluates price behavior inside an established structure.

    Once the structure is stable, the bar is confirmed, and at least 11 bars are available, four Boolean conditions are initialized: buySig for a bullish midpoint condition, sellSig for a bearish midpoint condition, fakeUp for a failed upward breakout, and fakeDn for a failed downward breakout. Keeping them initially set to false ensures that no condition is considered valid unless all of its required price checks are satisfied. For the bullish condition, the previous bar's low must be at or below the Lower Midpoint, while the current bar's low moves above it. The code also requires the low ten bars earlier to already be above the Lower Midpoint. This additional historical check helps confirm that price has returned above the level rather than simply moving across it as part of the same uninterrupted movement.

    The bearish condition uses the opposite arrangement around the Upper Midpoint. The previous bar's high must be at or above the Upper Midpoint, while the current bar's high moves below it, and the high ten bars earlier must already be below the Upper Midpoint. Together, these checks identify a downward movement through the Upper Midpoint after price had previously been positioned below that level. 

    Finally, fakeUp and fakeDn identify failed attempts to break the outer boundaries. A failed upward breakout occurs when the previous high reaches the Upper Boundary but the current high falls below it. A failed downward breakout follows the opposite movement.

    Drawing the Price Structure and Managing Chart Objects

    Calculated price structures, key levels, breakout markers, and other conditions are displayed as chart objects, with their positions updated and older objects removed as new bars form.

    Example:

    //--- Object naming prefix
    #define OBJ_PREFIX "ATRCH_"                            // Prefix used to identify objects created by this indicator
    
    //--- Chart appearance
    color  g_MidColor;                                     // Stores the chart foreground color for the middle range lines
    
    //+------------------------------------------------------------------+
    //| Create or update a zone rectangle                                |
    //+------------------------------------------------------------------+
    void UpsertZone(string name, datetime t1, double p1v, datetime t2, double p2v, color clr)
      {
    //--- Create the zone if it does not already exist
       if(ObjectFind(0, name) < 0)
         {
          ObjectCreate(0, name, OBJ_RECTANGLE, 0, t1, p1v, t2, p2v);
    
          //--- Set the zone appearance and properties
          ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
          ObjectSetInteger(0, name, OBJPROP_FILL, InpFillZones);
          ObjectSetInteger(0, name, OBJPROP_BACK, true);
          ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
          ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
          ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         }
       else
         {
          //--- Extend the existing zone to the new ending time
          ObjectSetInteger(0, name, OBJPROP_TIME, 1, t2);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Create or update a horizontal line                               |
    //+------------------------------------------------------------------+
    void UpsertHLine(string name, datetime t1, double price, datetime t2, color clr, bool dotted)
      {
    //--- Create the horizontal line if it does not already exist
       if(ObjectFind(0, name) < 0)
         {
          ObjectCreate(0, name, OBJ_TREND, 0, t1, price, t2, price);
    
          //--- Set the line appearance and properties
          ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
          ObjectSetInteger(0, name, OBJPROP_STYLE, dotted ? STYLE_DOT : STYLE_SOLID);
          ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
          ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
          ObjectSetInteger(0, name, OBJPROP_BACK, true);
          ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
          ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         }
       else
         {
          //--- Extend the existing line to the new ending time
          ObjectSetInteger(0, name, OBJPROP_TIME, 1, t2);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Draw a circle marker at the specified time and price              |
    //+------------------------------------------------------------------+
    void DrawO(datetime t, double price, color clr, bool upper)
      {
    //--- Build a unique object name based on marker position
       string name = OBJ_PREFIX + "O_" + (upper ? "u_" : "l_") + (string)((long)t);
    
    //--- Skip creation if the marker already exists
       if(ObjectFind(0, name) >= 0)
          return;
    
    //--- Create the circle marker as a text object
       ObjectCreate(0, name, OBJ_TEXT, 0, t, price);
    
    //--- Use the Wingdings circle glyph
       ObjectSetString(0, name, OBJPROP_TEXT, CharToString(108));
    
    //--- Set the font and marker appearance
       ObjectSetString(0, name, OBJPROP_FONT, "Wingdings");
       ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 12);
       ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
       ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_CENTER);
    
    //--- Keep the marker non-interactive and hidden from the object list
       ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
       ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
    
    //--- Print marker details when debug logging is enabled
       if(InpDebugLog)
          PrintFormat("ATRCH: O created at %s price=%.5f",
                      TimeToString(t, TIME_DATE|TIME_MINUTES|TIME_SECONDS), price);
      }
    
    //+------------------------------------------------------------------+
    //| Draw a directional triangle marker at the specified price        |
    //+------------------------------------------------------------------+
    void DrawTriangle(datetime t, double price, color clr, bool up)
      {
    //--- Build a unique object name based on direction and time
       string name = OBJ_PREFIX + (up ? "Buy_" : "Sell_") + (string)((long)t);
    
    //--- Skip creation if the marker already exists
       if(ObjectFind(0, name) >= 0)
          return;
    
    //--- Create the triangle marker as an arrow object
       ObjectCreate(0, name, OBJ_ARROW, 0, t, price);
    
    //--- Set the arrow direction and appearance
       ObjectSetInteger(0, name, OBJPROP_ARROWCODE, up ? 233 : 234);
       ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
       ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);
       ObjectSetInteger(0, name, OBJPROP_ANCHOR, up ? ANCHOR_TOP : ANCHOR_BOTTOM);
    
    //--- Keep the marker non-interactive and hidden from the object list
       ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
       ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
      }
    
    //+------------------------------------------------------------------+
    //| Draw a false breakout marker at the specified time and price     |
    //+------------------------------------------------------------------+
    void DrawX(datetime t, double price, color clr, bool anchorAbove)
      {
    //--- Build a unique object name based on time and anchor position
       string name = OBJ_PREFIX + "X_" + (string)((long)t) + (anchorAbove ? "a" : "b");
    
    //--- Skip creation if the false breakout marker already exists
       if(ObjectFind(0, name) >= 0)
          return;
    
    //--- Create the false breakout marker as a text object
       ObjectCreate(0, name, OBJ_TEXT, 0, t, price);
    
    //--- Set the X character and font appearance
       ObjectSetString(0, name, OBJPROP_TEXT, "X");
       ObjectSetString(0, name, OBJPROP_FONT, "Arial Bold");
       ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 10);
       ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
    
    //--- Position the marker above or below the breakout price
       ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchorAbove ? ANCHOR_BOTTOM : ANCHOR_TOP);
    
    //--- Keep the marker non-interactive and hidden from the object list
       ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
       ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
      }
    
    //+------------------------------------------------------------------+
    //| Remove objects that have moved outside the display window        |
    //| as new bars form                                                 |
    //+------------------------------------------------------------------+
    void PruneOldObjects(const datetime &time[], int rates_total)
      {
    //--- Determine the oldest bar that remains within the display window
       int cutoffIdx = rates_total - InpDisplayBars;
    
    //--- Stop if there are not enough bars to determine the cutoff
       if(cutoffIdx < 0)
          return;
    
    //--- Get the time of the oldest bar within the display window
       datetime cutoffTime = time[cutoffIdx];
    
    //--- Get the total number of chart objects
       int total = ObjectsTotal(0, 0, -1);
    
    //--- Check all chart objects from the end of the list
       for(int o = total - 1; o >= 0; o--)
         {
          //--- Get the object name
          string nm = ObjectName(0, o, 0, -1);
    
          //--- Skip objects that do not belong to this indicator
          if(StringFind(nm, OBJ_PREFIX) != 0)
             continue;
    
          //--- Get the object type
          long typeVal = ObjectGetInteger(0, nm, OBJPROP_TYPE);
    
          //--- Get the relevant ending time of the object
          datetime tEnd;
    
          if(typeVal == OBJ_RECTANGLE || typeVal == OBJ_TREND)
             tEnd = (datetime)ObjectGetInteger(0, nm, OBJPROP_TIME, 1);
          else
             tEnd = (datetime)ObjectGetInteger(0, nm, OBJPROP_TIME, 0);
    
          //--- Delete objects that are completely outside the display window
          if(tEnd < cutoffTime)
             ObjectDelete(0, nm);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+
    int OnInit()
      {
    //--- Create the ATR(200) indicator handle
       g_atrHandle = iATR(NULL, 0, 200);
    
    //--- Stop initialization if the ATR handle could not be created
       if(g_atrHandle == INVALID_HANDLE)
         {
          Print("Failed to create ATR(200) handle");
          return(INIT_FAILED);
         }
    
    //--- Validate ATR multiplier
       if(InpMulti <= 0)
         {
          Print("InpMulti must be greater than 0.");
          return(INIT_PARAMETERS_INCORRECT);
         }
    
    //--- Validate display bars
       if(InpDisplayBars < 1)
         {
          Print("InpDisplayBars must be greater than 0.");
          return(INIT_PARAMETERS_INCORRECT);
         }
    
    //--- Store the chart foreground color for the middle range lines
       g_MidColor = (color)ChartGetInteger(0, CHART_COLOR_FOREGROUND);
    
    //--- Delete all chart objects created by this indicator
       ObjectsDeleteAll(0, OBJ_PREFIX);
    
    //---
       return(INIT_SUCCEEDED);
      }
    
    //+------------------------------------------------------------------+
    //| Custom indicator deinitialization                                |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
      {
    //--- Release the ATR indicator handle when the indicator is removed
       if(g_atrHandle != INVALID_HANDLE)
          IndicatorRelease(g_atrHandle);
    
    //--- Delete all chart objects created by this indicator
       ObjectsDeleteAll(0, OBJ_PREFIX);
      }
    //--- Store the current range values and state
    Value[i] = vVal;
    ValueUpper[i] = vUp;
    ValueLower[i] = vLo;
    ValueUpperMid[i] = vUpMid;
    ValueLowerMid[i] = vLoMid;
    Trend[i] = vTrend ? 1.0 : 0.0;
    SegStartTime[i] = vSegStart;
    
    //--- Check whether the range remained unchanged from the previous bar
    bool stable = (i > 0 && vVal != EMPTY_VALUE && Value[i-1] != EMPTY_VALUE && vVal == Value[i-1]);
    
    //--- Initialize midpoint and failed-breakout conditions
    bool buySig = false, sellSig = false, fakeUp = false, fakeDn = false;
    if(stable && confirmed && i >= 11)
      {
       buySig  = (low[i-1]  <= vLoMid && low[i]  > vLoMid) && low[i-10]  > vLoMid;
       sellSig = (high[i-1] >= vUpMid && high[i] < vUpMid) && high[i-10] < vUpMid;
       fakeUp  = (high[i-1] >= vUp   && high[i] < vUp);
       fakeDn  = (low[i-1]  <= vLo   && low[i]  > vLo);
      }
    
    //--- Check whether the current bar is inside the display range
    bool visible = (rates_total - 1 - i) < InpDisplayBars;
    if(visible && vVal != EMPTY_VALUE)
      {
    //--- Build the object key from the range starting time
       datetime segStart = (datetime)vSegStart;
       string   key       = (string)((long)segStart);
    
    //--- Draw the upper and lower zones for the current range
       UpsertZone(OBJ_PREFIX + "ZoneUp_" + key, segStart, vUpMid, time[i], vUp, InpZoneColorUpper);
       UpsertZone(OBJ_PREFIX + "ZoneLo_" + key, segStart, vLo, time[i], vLoMid, InpZoneColorLower);
    
    //--- Draw the upper boundary, midpoint levels, and lower boundary
       UpsertHLine(OBJ_PREFIX + "LineUp_"    + key, segStart, vUp,    time[i], InpColorBullish, false);
       UpsertHLine(OBJ_PREFIX + "LineUpMid_" + key, segStart, vUpMid, time[i], g_MidColor, false);
       UpsertHLine(OBJ_PREFIX + "LineMid_"   + key, segStart, vVal,   time[i], g_MidColor, true);
       UpsertHLine(OBJ_PREFIX + "LineLoMid_" + key, segStart, vLoMid, time[i], g_MidColor, false);
       UpsertHLine(OBJ_PREFIX + "LineLo_"    + key, segStart, vLo,    time[i], InpColorBearish, false);
      }
    
    //--- Draw breakout, midpoint, and failed-breakout markers
    if(i > 0 && visible)
      {
       datetime tAnchor = time[i];
       double   offset  = (atrSmooth != EMPTY_VALUE) ? atrSmooth * 0.1 : 0.0;
    
    //--- Mark confirmed breaks of the upper and lower boundaries
       if(crossUpper)
          DrawO(tAnchor, low[i], InpColorBullish, true);
       if(crossLower)
          DrawO(tAnchor, high[i], InpColorBearish, false);
    
    //--- Draw midpoint buy and sell markers when their conditions are met
       if(buySig && (!InpFilterSignals || vTrend))
          DrawTriangle(tAnchor, low[i] - offset, InpColorBullish, true);
       if(sellSig && (!InpFilterSignals || !vTrend))
          DrawTriangle(tAnchor, high[i] + offset, InpColorBearish, false);
    
    //--- Optionally mark failed breaks of the outer boundaries
       if(InpShowX && fakeUp)
          DrawX(tAnchor, high[i] + offset, InpColorBearish, false);
       if(InpShowX && fakeDn)
          DrawX(tAnchor, low[i] - offset, InpColorBullish, true);
      }
    //--- Remove objects that have moved outside the display window
       PruneOldObjects(time, rates_total);
    
    //--- Refresh the chart to display the updated objects
       ChartRedraw(0);

    Explanation:

    The UpsertZone() function manages the upper and lower zone rectangles, while UpsertHLine() manages the horizontal boundary and midpoint levels. Both functions reuse existing objects by updating their ending time as the structure extends, creating new objects only when necessary. DrawO() places circle markers at the confirming candle's low for an upward breakout and at its high for a downward breakout, rather than directly on the broken boundary. The marker is anchored to the current completed bar on which the breakout condition is confirmed. The function generates a unique name from the marker time and boundary type, then creates the marker as a Wingdings text object and sets its font, size, color, and position. When debugging is enabled, additional information about the created marker is printed to the Experts log.

    DrawTriangle() creates the directional triangle markers used for bullish and bearish midpoint conditions. It generates a unique name based on the direction and bar time, then creates an arrow object using the appropriate Wingdings arrow code. The up parameter determines whether the marker represents a bullish or bearish condition and controls both its arrow shape and anchor position. The marker is also made non-selectable and hidden from the chart's object list.

    DrawX() places an X marker for failed breakouts, using a unique name based on the marker's time and position, then configuring its font, size, color, and placement. PruneOldObjects() removes indicator objects that have moved outside the configured display range, checking their ending or anchor time and deleting objects that are older than the display cutoff.

    Next, the program checks whether the current bar falls within the configured display range and whether a valid price structure exists. When both conditions are met, it uses the structure's starting time to create a unique object key, then draws or extends the upper and lower zones and the five horizontal levels from the structure's starting time to the current bar. This allows each structure to maintain its own zones and levels as new bars form.

    The indicator draws markers on the current completed bar when it falls within the configured display range. A small ATR-based offset keeps the markers visually separated from the candle. Confirmed upper and lower boundary breaks are marked with circles, while bullish and bearish midpoint conditions are marked with triangles when permitted by the optional trend filter. If failed-breakout markers are enabled, an X is placed when the price rejects either outer boundary. Finally, PruneOldObjects() removes indicator objects that have moved outside the configured display window, while ChartRedraw(0) refreshes the chart so the newly created, updated, or removed objects are immediately displayed.


    Conclusion

    In this article, we have developed an ATR-based price structure indicator in MQL5, covering volatility smoothing, boundary initialization and resets, midpoint conditions, breakout detection, and chart-object management. The indicator also supports optional directional filtering and X markers for potential failed breakouts. Each price structure retains its boundaries and midpoint levels until a completed candle confirms a boundary break. A new structure is then initialized using the confirming candle's midpoint and the smoothed ATR.

    The indicator uses two consecutive candles to identify potential reversal conditions. Once the second candle closes and confirms the condition, the corresponding arrow is displayed on the candle that confirms the signal. Compile the indicator and examine the resulting chart to verify its behavior. Keep in mind that these conditions describe price behavior; they do not independently confirm support and resistance or establish trading profitability.

    Attached files |
    Implementing a DST-aware Trading Day Resolver in MQL5 Implementing a DST-aware Trading Day Resolver in MQL5
    With CTradingDay, an EA can reset its daily loss limit at the time its rule names, such as the New York close, not at the end of the broker's feed. CServerClockFit finds the server time zone and its DST rule from hourly bars. On the tested server, the New York close falls one hour before server midnight between the US and EU clock changes. Unit tests and tester runs check these clock times for that server only.
    Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes
    We provide a controlled MQL5 test that sizes exposure from variance, applies a cap, and checks the implied next-bar standard deviation against a 0.75% target. Rolling-20 and EWMA-0.94 are audited against a fixed-exposure control using a generator with known next-bar variance. All sizing requests, caps, and conditional-risk deviations are recorded to CSV for detailed review.
    Features of Experts Advisors Features of Experts Advisors
    Creation of expert advisors in the MetaTrader trading system has a number of features.
    Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python
    Configuration is an essential part of almost every software application. Instead of hardcoding settings directly into the source code, developers can store them in configuration files, making programs easier to customize, maintain, and reuse. In this article, we will see how INI files work and implement an MQL5-friendly interface for reading, accessing, modifying, and writing configuration data similarly to Python's builtin module called configparser.