Intermediate Trading Tutorial | MT5 | MQL5 Custom Indicator

The Relative Strength Index is often discussed in terms of its location above or below fixed thresholds. A different question is how quickly the oscillator itself is changing. An RSI reading of 56 may have been reached from 44 over three candles or from 55 over the same interval. The final level is identical, but the net rate of change is not. This tutorial builds a MetaTrader 5 histogram that measures the average change in RSI points per bar using completed candles. It also demonstrates a reliable way to read a built-in indicator handle, align copied data with chart shifts, and handle missing calculations without converting them into false signals.

Define the slope precisely

Let R(s) denote the standard RSI value at chart shift s, where zero is the developing candle and one is the most recently completed candle. For a positive integer lookback N, define the slope at shift s as [R(s) − R(s+N)] / N. We use a 14-period RSI calculated from closing prices and N = 3 by default. A positive output represents a net increase in the oscillator, a negative output a net decrease, and zero means that the two endpoint values are identical.

This is a finite-difference slope, not a linear regression coefficient, percentage change in RSI, price rate of change, or visual angle on a chart. It has the convenient unit of RSI points per bar. Four RSI observations spanning three intervals are needed for a three-bar slope. The intermediate observations do not individually enter the formula, so an irregular path and a smooth path with identical endpoints produce the same result.

Worked example and interpretation

Consider four hypothetical closed RSI readings ordered from oldest to newest: 44, 49, 51 and 56. They correspond to shifts 4, 3, 2 and 1. The net change is 56 − 44 = 12 points over three intervals, giving a slope of +4 points per bar. The histogram draws +4 at shift one, not on the currently forming candle.

Build a Closed-Bar RSI Slope Histogram in MQL5 with CopyBuffer
Figure 1. Hypothetical RSI endpoints 44 and 56 span three completed-bar intervals. The resulting slope is +4 RSI points per bar.

Reverse the endpoints and the output becomes −4. If RSI starts and finishes at 50 but moves to 65 between those readings, the net slope is zero. Zero therefore does not prove that momentum was stable throughout the interval. Similarly, a positive slope while RSI remains below 50 is not equivalent to RSI already being above 50. Level and rate of change are separate measurements, and a user can evaluate them independently.

Complete MQL5 indicator source

// PatternSmart: confirmed RSI slope in RSI points per bar
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRoyalBlue
#property indicator_width1 3
#property indicator_label1 "RSI slope"
#property indicator_level1 0.0

input int RSIPeriod = 14;
input int SlopeBars = 3;

double SlopeBuffer[];
double RsiValues[];
int RsiHandle = INVALID_HANDLE;
datetime LastBarTime = 0;

int OnInit()
{
    if(RSIPeriod < 2 || SlopeBars < 1)
        return(INIT_PARAMETERS_INCORRECT);

    if(!SetIndexBuffer(0, SlopeBuffer, INDICATOR_DATA))
        return(INIT_FAILED);
    ArraySetAsSeries(SlopeBuffer, true);
    ArraySetAsSeries(RsiValues, true);
    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    IndicatorSetInteger(INDICATOR_DIGITS, 2);
    IndicatorSetString(INDICATOR_SHORTNAME, "Closed RSI Slope");

    RsiHandle = iRSI(_Symbol, _Period, RSIPeriod, PRICE_CLOSE);
    if(RsiHandle == INVALID_HANDLE)
        return(INIT_FAILED);
    LastBarTime = 0;
    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(time, true);
    if((long)rates_total < (long)RSIPeriod + SlopeBars + 2)
    {
        ArrayInitialize(SlopeBuffer, EMPTY_VALUE);
        return(0);
    }

    // Rebuild on a new bar or after a history reset.
    if(prev_calculated == rates_total && time[0] == LastBarTime)
    {
        SlopeBuffer[0] = EMPTY_VALUE;
        return(rates_total);
    }

    ArrayInitialize(SlopeBuffer, EMPTY_VALUE);
    if(BarsCalculated(RsiHandle) < rates_total)
        return(0);

    // Read only completed bars. With series indexing,
    // RsiValues[0] corresponds to chart shift 1.
    int count = rates_total - 1;
    if(CopyBuffer(RsiHandle, 0, 1, count, RsiValues) != count)
        return(0);

    int oldest = rates_total - 1 - RSIPeriod - SlopeBars;
    for(int shift = oldest; shift >= 1; --shift)
    {
        double recent = RsiValues[shift - 1];
        double earlier = RsiValues[shift + SlopeBars - 1];

        if(!MathIsValidNumber(recent) || !MathIsValidNumber(earlier))
            continue;
        if(recent == EMPTY_VALUE || earlier == EMPTY_VALUE ||
           recent < 0.0 || recent > 100.0 ||
           earlier < 0.0 || earlier > 100.0)
            continue;

        SlopeBuffer[shift] = (recent - earlier) / SlopeBars;
    }

    // Shift zero remains empty; no live-bar preview.
    LastBarTime = time[0];
    return(rates_total);
}

void OnDeinit(const int reason)
{
    if(RsiHandle != INVALID_HANDLE)
        IndicatorRelease(RsiHandle);
}

Why buffer alignment matters

In MQL5, iRSI returns an indicator handle rather than an oscillator reading. The handle is created once in OnInit and released during deinitialization. BarsCalculated checks whether the source indicator has produced enough calculated bars. CopyBuffer requests buffer zero beginning at shift one, intentionally excluding the live bar.

The temporary RsiValues array uses series indexing. CopyBuffer physically places older data before newer data, and the series flag reverses the logical indexing direction. Consequently RsiValues[0] corresponds to chart shift one, not shift zero. For the default three-interval calculation at shift one, the endpoints are RsiValues[0] and RsiValues[3]. This explicit mapping prevents an off-by-one mistake that would silently measure a different interval. The custom indicator's output buffer uses normal chart-series shifts, so an EA reading its buffer zero at shift one receives the latest completed slope.

Data readiness and historical initialization

With a 14-period RSI and three intervals, the code conservatively requires at least 19 chart bars before attempting the newest completed value. It leaves the initial RSI warm-up area unplotted. A full requested copy is required, rather than accepting a partial result and continuing with an incomplete array. Invalid or unavailable values remain EMPTY_VALUE. A valid RSI reading of zero or 100 is not rejected, since those are legitimate oscillator endpoints.

The implementation rebuilds its completed-bar history when a new bar appears or when the terminal requests recalculation. Comparing the newest timestamp with LastBarTime catches a new bar even if the total chart-bar count remains unchanged. Repeated calls during the same bar avoid another full copy. Returning zero on a failed copy lets the platform retry on a subsequent calculation event. This is a deliberately straightforward design that prioritizes transparent alignment. On charts with very long histories it may be more expensive than an incremental implementation, especially if applied to many instruments. An optimized variant would copy only the required recent segment during routine updates while preserving the complete rebuild for history resets.

Installation and settings

  1. Open MetaTrader 5 and select File → Open Data Folder. Locate MQL5/Indicators.
  2. Create PS_Closed_RSI_Slope.mq5 in MetaEditor, paste the complete source and compile.
  3. Review compiler messages and refresh the Navigator if necessary. Attach the indicator to a chart.
  4. Add the standard RSI with period 14 and Close as the applied price. Use the Data Window to inspect the same closed candles.
  5. Set RSIPeriod and SlopeBars to suit the experiment. Start with the defaults before comparing alternatives.

Input Default Tradeoff
RSIPeriod 14 A shorter period tends to respond more quickly to recent price changes; a longer period tends to smooth the oscillator.
SlopeBars 3 Short intervals emphasize recent movement; longer intervals average net change over more bars and can hide temporary reversals.

A slope measured over three five-minute bars and one measured over three daily bars share a unit per bar but not per minute or per day. Do not directly compare them as time-normalized rates. Because the RSI range is bounded, the slope is also bounded by −100/N and +100/N. The size of typical readings changes with both the RSI period and slope horizon.

Validation checklist

  • Confirm the current bar is empty and the newest plotted value is located at shift one.
  • Use the built-in RSI values at shifts one and four and reproduce the default result manually.
  • Test equal endpoints, rising endpoints, and falling endpoints.
  • Change SlopeBars to one and confirm that the result is the difference between adjacent completed RSI values.
  • Refresh historical data and verify that the indicator reconstructs rather than preserves a stale result.
  • Check history-loading behavior and do not interpret missing values as zero.

The relevant API behavior was checked against the official MQL5 Reference for iRSI, CopyBuffer and BarsCalculated. The source has not been compiled or tested in a live terminal for this article. Verify it with your own terminal build before using it in an EA. Using only completed values avoids ordinary live-candle fluctuation but does not prevent revisions when historical data changes. RSI slope is not a prediction of price returns; no order handling, spread filter or position sizing is included. This educational example is not investment advice, and trading involves risk of loss.

If you would like to extend this free indicator with a regression slope, color-coded momentum regimes, or EA integration, contact us through our Custom Trading Software Development Services.

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.