Advanced Trading Tutorial — MT5 custom indicator development

A market can travel through the same net price distance using a remarkably different sequence of closing prices. One path may consist mainly of consecutive advances, while another alternates between advances and declines. Net return alone cannot distinguish these paths. Direction reversal density is a compact statistic that measures how frequently the direction of successive nonzero close-to-close changes reverses. This tutorial implements it as a native MQL5 indicator with a separate reference buffer, explicit handling of flat closes, and a minimum sample requirement.

Why measure the order of changes?

Consider two hypothetical sequences of six price changes. In the first, all six are positive. In the second, four positive changes and two negative changes are arranged in an alternating order. The second sequence might still end at a higher price than the first if its positive changes are sufficiently large. A measure of net movement therefore does not necessarily describe how often the market changes direction. The statistic presented here discards magnitude deliberately and focuses on the ordering of signs. It is complementary to magnitude-based indicators rather than a replacement for them.

Calculation and output contract

Choose N consecutive close-to-close changes ending at the candidate candle. Assign +1 to positive changes, -1 to negative changes and zero to unchanged closes. Remove the zero signs from this finite window without extending the window to retrieve replacement observations. Process the remaining signs in chronological order. If there are M nonzero signs, there are M minus one adjacent sign transitions, provided M is positive. Count how many transitions switch from positive to negative or negative to positive. Divide that count by the number of transitions and multiply by one hundred.

The default window contains twenty changes, requiring twenty-one completed closes. The minimum number of nonzero sign transitions is five, which requires at least six nonzero changes within that window. If fewer transitions exist, the output is EMPTY_VALUE instead of zero. This matters: zero density means that a sufficiently populated sample has no reversals; missing density means there is insufficient information under the configured rule. The default reference line is 65%. It does not produce an alert or execute orders.

Worked example

Take seven hypothetical closing prices in chronological order: 100, 103, 103, 101, 102, 104, 103. The six changes are +3, 0, -2, +1, +2 and -1. Removing zero produces five signs: positive, negative, positive, positive, negative. There are four eligible transitions, of which three reverse direction. The resulting density is 75%. To reproduce this result, set Changes to six and MinTransitions to four. With the default minimum of five, the same short sample is insufficient and produces no valid density. The distinction is essential when designing downstream filters.

Direction Reversal Density Indicator: Measuring Nonzero Close Direction Changes
The flat observation is skipped. Three reversals among four eligible transitions give 75%; the example requires a minimum transition count of four or less.

Complete MQL5 source code

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRoyalBlue
#property indicator_label1 "Reversal density"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrSeaGreen
#property indicator_style2 STYLE_DOT
#property indicator_label2 "Reference"
#property indicator_minimum 0
#property indicator_maximum 100

input int Changes = 20;
input int MinTransitions = 5;
input double Reference = 65.0;
double Density[], Ref[];

int OnInit()
{
    if(Changes < 2 || Changes > 1000 ||
       MinTransitions < 1 ||
       MinTransitions >= Changes ||
       Reference < 0 || Reference > 100)
        return(INIT_PARAMETERS_INCORRECT);
    SetIndexBuffer(0,Density,INDICATOR_DATA);
    SetIndexBuffer(1,Ref,INDICATOR_DATA);
    ArraySetAsSeries(Density,true);
    ArraySetAsSeries(Ref,true);
    PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);
    PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE);
    IndicatorSetString(INDICATOR_SHORTNAME,
                       "Direction Reversal Density");
    return(INIT_SUCCEEDED);
}

int OnCalculate(const int rates_total,
    const int 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 int &spread[])
{
    ArraySetAsSeries(close,true);
    if(prev_calculated == 0 ||
       prev_calculated > rates_total)
    {
        ArrayInitialize(Density,EMPTY_VALUE);
        ArrayInitialize(Ref,EMPTY_VALUE);
    }
    if(rates_total < Changes + 2) return(0);
    Density[0]=EMPTY_VALUE;
    Ref[0]=EMPTY_VALUE;
    int last=rates_total-1-Changes;
    int start=last;
    if(prev_calculated > 0 &&
       prev_calculated <= rates_total)
        start=(int)MathMin(last,
                          rates_total-prev_calculated+1);
    for(int i=start;i>=1;i--)
    {
        int prior=0, turns=0, transitions=0;
        // Process from oldest to newest inside window.
        for(int k=i+Changes-1;k>=i;k--)
        {
            double d=close[k]-close[k+1];
            int sign=(d>0 ? 1 : (d<0 ? -1 : 0));
            // Flat closes do not reset the prior sign.
            if(sign==0) continue;
            if(prior!=0)
            {
                transitions++;
                if(sign!=prior) turns++;
            }
            prior=sign;
        }
        Density[i]=(transitions>=MinTransitions ?
            100.0*turns/transitions : EMPTY_VALUE);
        Ref[i]=Reference;
    }
    return(rates_total);
}

Installation and buffer access

Open MetaEditor from MetaTrader 5 and create a custom indicator in the Indicators directory. Name it DirectionReversalDensity, replace the generated template with the source above, and compile. Attach the indicator from Navigator to a normal chart. The blue line is the measured reversal density and the dotted green line is the reference level. No trade or alert logic is included. Buffer zero exposes the density, while buffer one exposes the configured reference. An Expert Advisor can obtain a handle with iCustom using the three inputs in their declared order and request one element from buffer zero at position one through CopyBuffer. Check the returned element count and EMPTY_VALUE before using that result; release the handle when it is no longer needed. The code has not been compiled in a terminal for this article.

Closed-bar consistency and indexing

The OnCalculate handler explicitly applies series indexing to the close array and to both indicator buffers. Index zero is the currently forming candle and is deliberately left empty. For an output index i, the oldest required close is i plus Changes. The nested loop starts with the oldest change and progresses toward the candidate, never accessing a candle newer than i. No direction state is inherited from outside the window. This ensures that the definition of the feature remains the same regardless of the available earlier history. On a fresh calculation, the buffers are initialized to EMPTY_VALUE; subsequent calls recalculate the relevant recent values. When a new bar is created, the newly completed bar becomes eligible. This design avoids changing the score solely because the current candle is moving, although corrected market data or a changed chart aggregation can still change historical observations.

Parameter tradeoffs and interpretation

A short window responds rapidly to a shift from persistent to alternating signs. Its denominator may be small, making the score jump in large discrete increments. A longer window usually offers finer resolution but can retain earlier behavior after a regime change. The minimum transition count guards against an apparently extreme value generated by very few observations. Raising it improves the minimum sample size at the cost of more missing outputs in quiet or illiquid markets. Choose a value below Changes, since N changes can create at most N minus one transitions.

A high reading describes frequent sign changes, not necessarily a sideways market: a strongly rising series can alternate between large advances and small declines. A low reading does not identify bullish or bearish direction, because an uninterrupted decline and an uninterrupted advance both have zero reversal density when the sample is valid. If directional classification is needed, combine this feature with a separately defined directional measure. If magnitude matters, consider a separate volatility or path-length statistic rather than modifying the sign-counting definition without documenting the change.

Practical validation checklist

  • Reproduce the seven-close example with six changes and four minimum transitions.
  • Check all-positive and all-negative samples: both should produce zero with adequate transitions.
  • Check a strictly alternating sequence: it should produce 100 with adequate transitions.
  • Check all-flat or one-nonzero-change samples: density should be EMPTY_VALUE.
  • Confirm that flat changes are ignored only within the original window, with no additional history pulled into the count.
  • Confirm that buffer zero at shift zero remains empty and that the completed value remains stable as a new candle forms.
  • Compare the indicator with manually calculated values after reloading the same historical data and test broker session gaps.

Limitations and customization

The feature treats a one-tick movement and a very large movement as equivalent signs. It can therefore be sensitive to small alternating changes, especially on very short aggregations. A flat close might represent an active intrabar market that returned to its starting level, so ignoring flat changes does not establish that no trading occurred. Adjacent transitions share observations and are not independent statistical samples. The 65% reference is illustrative, not an empirically calibrated probability threshold. For a customized deadband, session reset, dashboard or integration into an existing Expert Advisor, contact us through our Custom MT5 indicator Development Services.

Trading involves risk of loss. This is an educational implementation and the worked data are hypothetical. Neither historical reversal density nor any particular threshold establishes a profitable trading rule. Validate code, market data and execution assumptions before live use.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.