Beginner Trading Tutorial — Confirmed Prior SMA Percentage Deviation in MT5
How far has the latest completed candle moved from its recent price reference? A moving average supplies a convenient baseline, but the raw distance between price and average is difficult to compare across instruments with different price levels. This tutorial builds a native MQL5 indicator that measures the percentage deviation of each completed close from a simple moving average of the preceding candles. The calculation is intentionally transparent, making it a practical first project for learning indicator buffers, array indexing and historical data requirements in MetaTrader 5.
Choose a baseline before evaluating price
A conventional simple moving average (SMA) at a particular bar often includes that bar's close. Here we deliberately exclude the candle being evaluated. The reference therefore represents information already available before the evaluated candle closes. For a lookback of N, add the preceding N closing prices and divide by N. Then calculate 100 multiplied by the difference between the evaluated close and that baseline, divided by the baseline. This produces a signed percentage rather than a currency or point distance.
A positive value means the evaluated close lies above the reference; a negative value means it lies below. Zero indicates equality. Unlike an oscillator with a fixed upper and lower bound, this measure has no symmetric fixed range. A large value may reflect an unusual move, a persistent trend, a gap or simply a very small denominator. It does not measure the probability of a reversal. The implementation assumes positive baseline prices and omits observations when that assumption is not satisfied.

Walk through a numerical example
Set Period to three for an easy manual calculation. Suppose the preceding closes are 98, 100 and 102. Their sum is 300 and their arithmetic average is 100. If the next completed candle closes at 104, its deviation is 100 × (104 − 100) / 100 = +4%. If it closes at 96 instead, the result is −4%. If it closes exactly at 100, the result is zero. These are separate hypothetical outcomes using the same reference, not three successive candles.
For comparison, including the evaluated close of 104 in a three-bar SMA would replace 98 with 104 and produce an average of 102. The resulting deviation would be approximately 1.96%, rather than 4%. Both definitions are mathematically valid, but answer different questions. Our design measures a new close relative to the preceding price reference. When the next candle is evaluated, the reference window advances by one bar. Do not keep using 100 as the baseline for all subsequent candles unless their preceding closes happen to produce the same average.
Complete MQL5 indicator source
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "Prior SMA deviation (%)"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrSteelBlue
#property indicator_width1 2
#property indicator_level1 0
input int Period = 20;
double Deviation[];
int OnInit()
{
// Bound the lookback to a positive, practical integer.
if(Period < 1 || Period > 10000)
return(INIT_PARAMETERS_INCORRECT);
SetIndexBuffer(0, Deviation, INDICATOR_DATA);
ArraySetAsSeries(Deviation, true);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
IndicatorSetInteger(INDICATOR_DIGITS, 2);
IndicatorSetString(INDICATOR_SHORTNAME,
"Confirmed Prior SMA Deviation (" +
IntegerToString(Period) + ")");
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);
bool reset = (prev_calculated <= 0 ||
prev_calculated > rates_total);
if(reset)
ArrayInitialize(Deviation, EMPTY_VALUE);
if(rates_total < Period + 2)
{
ArrayInitialize(Deviation, EMPTY_VALUE);
return(0);
}
int oldest = rates_total - Period - 1;
int start = oldest;
if(!reset)
start = (int)MathMin(oldest,
rates_total - prev_calculated + 1);
// Never expose a provisional value on the forming candle.
Deviation[0] = EMPTY_VALUE;
for(int i = start; i >= 1; --i)
{
// Reference only the Period bars preceding bar i.
double sum = 0.0;
for(int j = 1; j <= Period; ++j)
sum += close[i+j];
double sma = sum / Period;
// Percentage interpretation assumes a positive baseline.
if(sma <= 0.0 || !MathIsValidNumber(sma) ||
!MathIsValidNumber(close[i]))
Deviation[i] = EMPTY_VALUE;
else
Deviation[i] = 100.0 * (close[i] - sma) / sma;
}
return(rates_total);
}
Understand the indicator implementation
The property declarations create a separate indicator window with a single histogram plot and a zero reference level. The output buffer is called Deviation and is registered as INDICATOR_DATA. The default input Period is 20, but a user can change it in the indicator settings. OnInit rejects invalid lookback lengths and assigns the empty-value representation. It also configures the display precision to two decimal places; this affects presentation rather than the precision of the calculation.
MQL5 provides price arrays to OnCalculate. Do not assume their indexing direction without explicitly setting it. This implementation calls ArraySetAsSeries on the close array and on the indicator buffer, after the buffer is bound. With series indexing, zero refers to the currently forming bar, one refers to the most recent completed bar, and larger indices refer to progressively older data. To evaluate bar i, we read close[i] and average close[i+1] through close[i+Period]. None of those reference observations occurs after the evaluated candle.
The oldest valid index is rates_total minus Period minus one. We need at least Period preceding candles, one evaluated completed candle, and one live candle. If this history requirement is not met, the indicator initializes the buffer to EMPTY_VALUE and returns zero. On a full calculation it clears the buffer and processes every eligible historical bar. During incremental calculations it updates a small recent section based on the previous calculation count. A direct summation is used for clarity. For very long lookbacks and extensive histories, a rolling sum or a carefully aligned moving-average handle could be more efficient.
Installation and use
Open MetaEditor from MetaTrader 5 and create a custom indicator called ConfirmedPriorSMADeviation. Replace the generated source with the code above, save it in MQL5/Indicators, and compile. Resolve any compiler messages before loading it into a chart. Return to the terminal and refresh the Navigator if necessary. Attach the indicator and set Period to three while following the example. For normal research, choose the lookback according to the chart timeframe and your hypothesis rather than assuming the default is optimal. Use the Data Window to examine exact completed-bar readings. This source has not been compiled or run in MT5 here.
Closed-bar behavior and repainting
A price deviation computed from an unfinished close changes as incoming quotes arrive. That is not necessarily a programming defect, but it is unsuitable when a rule requires confirmed data. Our indicator explicitly keeps bar zero empty. When the next bar begins, the previous bar becomes index one and is evaluated using its completed close. Although the histogram is drawn on the completed candle, the confirmed value only becomes available when the terminal recognizes the new candle. Do not assume it was available earlier during that candle.
There is no look-ahead reference and no intentional modification of finalized results. Broker history corrections, changes in chart construction, and changes to the Period input can legitimately alter historical output. An Expert Advisor can obtain a handle with iCustom and read buffer zero at shift one using CopyBuffer, checking both the return count and EMPTY_VALUE before using the result. The EA should release its indicator handle when no longer needed.
Testing, interpretation and limitations
Start with the numerical example and check the oldest valid index, insufficient history, a flat sequence and the first tick of a new candle. Confirm that the active candle remains empty and that an identical dataset produces consistent results after reloading. Compare the indicator with a spreadsheet using exactly the preceding N closes rather than a moving average that includes the evaluated close. A persistent positive reading can occur throughout a rising market; it is not automatically an overbought signal. The measure ignores volatility, volume and execution costs. Compare different periods and market regimes using out-of-sample observations before relying on any rule.
For configurable thresholds, volatility normalization, multi-timeframe analysis or EA integration, contact our Custom MT5 indicator Development Services.
Risk disclosure: this tutorial is educational, not investment advice. Trading involves risk of loss; hypothetical calculations do not demonstrate profitability.