MQL5 Indicator Tutorial: How to Make a Custom MT5 Indicator

Published November 22, 2026 · In Bot Development

An MQL5 indicator is a small program that reads price data, fills arrays called buffers, and lets MetaTrader 5 draw those values on a chart. This tutorial builds one from an empty file: the #property lines, OnInit and OnCalculate, buffers and plots, a short moving average example, compiling in MetaEditor and attaching the result to a chart. Every platform fact comes from the MQL5 Reference and the MetaTrader 5 and MetaEditor help, checked on 19 November 2026.

How an MQL5 indicator file is laid out

Every MQL5 indicator is one .mq5 source file. When you compile it, MetaEditor writes an .ex5 file next to it, and the terminal runs that file. Inside the source, the parts usually come in this order:

  1. #property lines that tell the terminal where to draw and how many buffers and plots exist.
  2. Input parameters, which the trader can change in the indicator’s settings window.
  3. Global arrays that become the indicator buffers.
  4. OnInit(), which runs once and binds those arrays to buffer numbers.
  5. OnCalculate(), which the terminal calls when price data changes.

The MQL5 Reference says OnCalculate is called in indicators “when the Calculate event occurs for processing price data changes”. It is the only handler an indicator must have. The MetaEditor wizard won’t even let you remove it, while OnInit is optional but almost always used.

MQL5 indicator file structure: property lines, inputs, buffer arrays, OnInit and OnCalculate in one .mq5 source file
Five parts of one .mq5 file, in the order they usually appear.

The #property lines at the top

The program properties page lists the indicator settings. These are the ones a first indicator needs:

Property MetaQuotes description
indicator_chart_window Show the indicator in the chart window
indicator_separate_window Show the indicator in a separate window
indicator_buffers Number of buffers for indicator calculation
indicator_plots Number of graphic series in the indicator
indicator_typeN Type of graphical plotting, from ENUM_DRAW_TYPE
indicator_colorN, indicator_widthN Color and line thickness of plot N
indicator_labelN Label of plot N in the Data Window

N starts at 1, so the first plot uses indicator_type1 and indicator_color1. A moving average sits on the price chart, so it uses indicator_chart_window. An oscillator such as RSI has its own scale and goes in a separate window.

Indicator buffers and plots

In an MQL5 indicator, a buffer is a double array that the terminal manages for you. A plot is one thing drawn on the chart, such as a line, a histogram or a row of arrows. Beginners often mix the two up, since the counts can differ.

The SetIndexBuffer() reference gives three buffer types. The default, INDICATOR_DATA, holds the values that are drawn. Color indexes for the buffer before it go in INDICATOR_COLOR_INDEX. Helper values that are never drawn go in INDICATOR_CALCULATIONS. So an indicator with one line and two helper arrays has three buffers but only one plot.

Each drawing style also needs a set number of data buffers. According to the drawing styles table, DRAW_LINE and DRAW_ARROW use one data buffer each, while DRAW_HISTOGRAM2 uses two. Color buffers are always bound after the value buffers of their plot.

Indicator buffers and plots in MT5: data, color index and calculation buffers mapped to the plots drawn on a chart
Buffers hold numbers. Plots draw some of them. Calculation buffers are never drawn.

OnInit and OnCalculate

OnInit runs once when the MQL5 indicator loads. Here you call SetIndexBuffer() for every buffer, set plot options, and check the inputs. If an input makes no sense, return INIT_PARAMETERS_INCORRECT and the indicator will not start.

OnCalculate has two forms in the OnCalculate() reference. The short form receives one price[] array. With it, the trader picks the price source in the “Apply to” list of the Parameters tab, for example Close or Median Price. The long form receives time, open, high, low, close, volumes and spread for the current timeframe.

Both forms get rates_total, the number of bars, and prev_calculated. The second value is whatever your OnCalculate returned on its previous call. Usually you return rates_total, so the next call only works on new bars. However, the terminal sets prev_calculated to zero itself when the price data changes, for example after a deeper history load or when gaps are filled. Your code must then rebuild everything.

How OnCalculate uses prev_calculated: full calculation on the first call, only new bars after that, full rebuild when the terminal resets it to zero
Return rates_total, and the next call starts where this one stopped.

A small working example: a moving average line

This MQL5 indicator draws a simple moving average on the price chart. It uses the short OnCalculate form, so the trader can apply it to any price. We wrote it with standard MQL5 functions and properties from the Reference, but we have not compiled or run it. Treat it as a teaching example to compile and check yourself.

// MQL5 example (not compiled or run): simple moving average line
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "SMA"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2

input int InpPeriod = 20;          // Period

double SmaBuffer[];

int OnInit()
  {
   if(InpPeriod < 1)
      return(INIT_PARAMETERS_INCORRECT);
   SetIndexBuffer(0, SmaBuffer, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpPeriod - 1);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetString(INDICATOR_SHORTNAME, "SMA(" + (string)InpPeriod + ")");
   return(INIT_SUCCEEDED);
  }

int OnCalculate(const int rates_total, const int prev_calculated,
                const int begin, const double &price[])
  {
   int first = begin + InpPeriod - 1;           // first bar with a full window
   if(rates_total <= first)
      return(0);
   ArraySetAsSeries(price, false);              // index 0 = oldest bar
   ArraySetAsSeries(SmaBuffer, false);
   if(prev_calculated == 0)                     // first call or a reset
      for(int i = 0; i < first; i++)
         SmaBuffer[i] = EMPTY_VALUE;
   int start = (prev_calculated > first) ? prev_calculated - 1 : first;
   for(int i = start; i < rates_total; i++)
     {
      double sum = 0.0;
      for(int k = 0; k < InpPeriod; k++)
         sum += price[i - k];
      SmaBuffer[i] = sum / InpPeriod;
     }
   return(rates_total);
  }

What each part does

The #property block asks for one buffer and one line plot on the price chart. OnInit binds SmaBuffer to buffer 0, hides the first bars that have no full window, and sets the name shown in the Data Window.

In OnCalculate, the start index skips bars already done and recalculates the last one, because the newest bar is still forming. A full average is rebuilt for each bar, which is slow for a long period but easy to read. A running sum would be faster. The begin value matters when the indicator is applied to another indicator’s data, which may have empty bars at the start.

Create and compile it in MetaEditor

The MetaEditor wizard help describes the steps:

  1. In MetaEditor, click New in the File menu or toolbar and choose Custom Indicator.
  2. Enter a name, which also becomes the file name, and add any input parameters.
  3. Pick the OnCalculate form. You can choose its type but not remove it.
  4. Choose the chart window or a separate window, set up the plots, and click Finish.

The template goes into the MQL5/Indicators folder. Paste the example over the generated code, then compile with Compile in the File menu or F7. According to the compile help, the log appears on the Errors tab of the Toolbox window. Errors stop the build, so no .ex5 file is made. Warnings still let the executable file be created, but read them anyway.

Steps from MetaEditor to chart: File New, Custom Indicator wizard, compile with F7, check the Errors tab, then drag the indicator from the Navigator
From an empty template to a checked line on the chart.

Attach it to a chart and test it

The MetaTrader 5 help says the easiest way to apply an indicator is to drag it from the Navigator window onto a chart. The Indicators command in the Insert menu also works. A settings window then opens, where you set the inputs and, for the short form, the “Apply to” price.

Next, check a few values of the new MQL5 indicator by hand. Open the Data Window, point at a bar, and compare the SMA with the average of the last 20 closes. Then try a second symbol and a lower timeframe, because some bugs show up only with more bars or different digits. To see the line form bar by bar, add it to a visual run in the Strategy Tester; our guide to MT5 backtesting covers the tester settings.

Common mistakes in a first MQL5 indicator

Trading belongs in an Expert Advisor. The EA can read your values with iCustom() and CopyBuffer(), and CopyBuffer counts back from the present, so position 0 is the current bar. A signal read from that unfinished bar can still change, which is a common source of repainting.

Six common MQL5 indicator mistakes: buffer count, bar indexing, return value, prev_calculated reset, slow loops and trade calls
Check these six points before you blame the data.

When to hire it out

A single line, a cross or a simple level makes a good first MQL5 indicator. Some jobs grow fast, though. A tool that reads a higher timeframe without repainting needs care. So does a panel that scans many symbols, or zone logic with lots of exceptions. So does porting a TradingView script, since Pine Script and MQL5 run in different ways; our Pine Script vs MQL comparison explains the gap.

For those cases, our MT4/MT5 indicator development service builds it from your rules and a chart screenshot. You can also describe the indicator on WhatsApp for a fixed quote.

MQL5 indicator: FAQ

What is the difference between indicator_buffers and indicator_plots?

indicator_buffers counts every array bound with SetIndexBuffer(), including calculation and color buffers. indicator_plots counts only the graphic series drawn on the chart.

Why does my indicator recalculate all bars?

OnCalculate probably returns 0, or the loop ignores prev_calculated. Return rates_total and start the loop near prev_calculated. The terminal still sends zero after a history change.

Where is the .ex5 file saved?

MetaEditor writes it in the same folder as the main source file, usually MQL5/Indicators. If compilation shows errors, no .ex5 file is created.

Can an MT5 indicator open trades?

No. MetaQuotes prohibits OrderSend() and OrderCheck() in custom indicators. An Expert Advisor can read the indicator with iCustom() and CopyBuffer() and place the orders.

Should my loop count from the oldest or the newest bar?

Either works if you set it on purpose. Bound buffers start at the oldest bar, and ArraySetAsSeries() after SetIndexBuffer() reverses that.

Risk warning: Trading forex, CFDs and other leveraged products carries a high risk of loss. An indicator only shows calculations on past and current prices and does not predict results. Test any indicator or EA on a demo account first. This article is for education only and is not investment advice.

Want this built for you?

We develop it as a service — reliable, tested, and yours to own.

Message Us on WhatsApp
WhatsApp