Build an MT5 indicator: buffers, OnCalculate and reliable recalculation

Build an MT5 indicator: buffers, OnCalculate and reliable recalculation

Start with a value you can explain

A useful custom indicator has a precise contract before it has attractive colours. Our example reports where the current close sits inside the highest-high to lowest-low range of the last N bars. It produces one number between 0 and 100, or an empty value while the window is incomplete. It does not send orders. This makes it suitable for learning calculation, display and verification as separate responsibilities.

Write the contract explicitly: use the chart symbol and timeframe, include the bar being calculated, use highs and lows rather than closes to establish the range, and return 50 for a flat window. A close outside its own bar's high–low range is inconsistent input to investigate, not a reason to silently clamp the output. These decisions matter more than the indicator's name.

The calculation is 100 × (close − lowest low) / (highest high − lowest low). This is a range-position teaching example, not a claim to reproduce the smoothed Stochastic indicator. If you later add smoothing, version the formula and its warm-up requirements.

Keep calculation and drawing contracts separate

Use one data buffer and one line plot. The terminal owns the bound buffer's size; your code supplies values. Choose oldest-first indexing explicitly after binding and for the input arrays used in the loop. Then index i refers to the same bar across high, low and close. Avoid mixing this convention with position-based CopyBuffer requests, where position zero means the current bar.

The first N−1 cells have no complete window. Give them EMPTY_VALUE and set the plot's empty-value property to the same sentinel. Zero is a valid range-position result and cannot double as “not ready”. PLOT_DRAW_BEGIN controls presentation, but explicitly initializing unavailable cells also makes the data contract easier to inspect.

Indicator buffer indices start at zero, whereas declaration suffixes such as indicator_type1 refer to the first plot. Document both the data buffer and the plot; they are not interchangeable identifiers.

A complete teaching implementation

Create a custom indicator in MetaEditor and use the following original example as its source. The code deliberately uses a transparent O(N) scan for each recalculated bar. It is a reference implementation to inspect and compile in your terminal, not a compiled delivery package or a benchmark claim.

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "Range position"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRoyalBlue
#property indicator_minimum 0
#property indicator_maximum 100
input int Period = 14;
double RangePosition[];

int OnInit()
{
   if(Period < 2) return INIT_PARAMETERS_INCORRECT;
   if(!SetIndexBuffer(0, RangePosition, INDICATOR_DATA))
      return INIT_FAILED;
   ArraySetAsSeries(RangePosition, false);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, Period - 1);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetInteger(INDICATOR_DIGITS, 2);
   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(high, false);
   ArraySetAsSeries(low, false);
   ArraySetAsSeries(close, false);
   bool reset = (prev_calculated <= 0 || prev_calculated > rates_total);
   if(reset) ArrayInitialize(RangePosition, EMPTY_VALUE);
   if(rates_total < Period) return 0;
   int start = reset ? Period - 1 : MathMax(Period - 1, prev_calculated - 1);
   for(int i = start; i < rates_total; ++i)
   {
      double hi = high[i], lo = low[i];
      for(int j = i - Period + 1; j < i; ++j)
      {
         hi = MathMax(hi, high[j]);
         lo = MathMin(lo, low[j]);
      }
      RangePosition[i] = (hi == lo) ? 50.0 :
                        100.0 * (close[i] - lo) / (hi - lo);
   }
   return rates_total;
}

Understand the four recalculation cases

On first load, calculate every complete window. During another tick of the same bar, recalculate the last bar: its high, low and close can change. When a new bar arrives, recalculate the former last bar and calculate the new one. When the terminal resets prev_calculated after a history change, rebuild the result rather than trusting the old prefix. The OnCalculate reference describes this reset behaviour.

Returning rates_total tells the next invocation how much was handled; it does not make the current bar final. A consumer that wants a closed-bar value still chooses an appropriate closed timestamp. The last plotted point moving during an unfinished candle is expected under this contract.

Do not optimize by keeping only a cached highest high unless you also handle the bar that supplied it leaving the window. A monotonic queue can reduce work, but then history reset, equal highs and current-bar revision all require explicit handling. Keep this simple version as a numerical oracle when introducing a faster algorithm.

Verify with a tiny numerical fixture

Use N=3 and oldest-first bars. Let highs be [12,13,14,15], lows [8,9,10,11] and closes [10,12,13,11]. The first two outputs are empty. At index 2, the range is 8 to 14 and the result is 83.333333. At index 3, the window advances to range 9 to 15 and the result is 33.333333. These are synthetic arithmetic examples, not market results.

Now change only the last close from 11 to 14: only the last output should change, to 83.333333. A flat three-bar window with all prices equal produces 50. Test an input period of 1 and confirm initialization rejects it. Test fewer than three bars and confirm the indicator exposes no manufactured zero signal.

Compare a full pass with incremental passes over the same fixture. Then prepend older bars and force a fresh calculation. Compare outputs by timestamp, allowing for the changed warm-up region. A visually smooth line is not enough to establish any of these properties.

Diagnose a blank or misleading plot

If nothing appears, check initialization results, available bars, plot type, empty-value settings and the Experts/Journal messages. Use the Data Window to distinguish a valid value hidden by styling from an uncalculated cell. A fixed 0–100 scale is appropriate here because the contract has that range; it would hide many price-denominated indicators.

When adding an EA reader later, document that buffer 0 is numeric range position, not a buy/sell signal. Record the selected bar timestamp with each value. A failed copy must remain a missing observation. This keeps display bugs, data-readiness problems and trading-rule decisions from being combined into one vague “indicator does not work” report.

Practice files

These CSV files contain synthetic teaching data, not market observations or investment results.

The MQ5 example has not been compiled or run in MT5 as part of this article.

Sources and further reading

Back to top

MQLume Bespoke

Built around your ambition.

Explore bespoke services →

Have something more specific in mind?

Ask us about advanced custom development. Share your requirements through private support or email; we will discuss the scope and quote separately.

100% committed to following up on your delivery and support requests.

Free downloads. Real source files.

FREE

Lizard [MQLume]

MQL5 / MT5Version v2.21

Free editable gold breakout project with six independently selectable cores, session filters and flexible position sizing.

US$149.00FREE
FREE

Scraper Gold [MQLume]

MQL5 / MT5Version v3.7

Free editable source with compiled EX5: four gold breakout engines with independent profiles, sizing, direction and exits.

US$95.00FREE
FREE

EA Black Dragon [MQLume]

MQL5 / MT5Version v13.0

Trend-based entries with optional grid additions, side controls and virtual exits.

US$30.00FREE
FREE

Hamster Scalping [MQLume]

MQL5 / MT5Version v21.0

RSI entries with two ATR filters, configurable sessions and optional grid management.

US$30.00FREE
MQLume

More to explore. A community to share it with.

Stay close to MQLume, wherever you like to learn.

YouTube

See our EAs in action. Explore backtests, walkthroughs and practical guides.

Watch on YouTube

Telegram

Meet other EA users, share ideas and keep up with what’s new.

Join the community Follow official updates

Cart

One personal-use licence per project. Each project can be added once.

Your cart is waiting for its first passenger.

Choose an EA or source edition to get started.

Continue shopping