Hands-On Guide: Building a Custom Moving Average Distance Indicator in MQL5
While built-in indicators in MetaTrader 5 cover the basics, creating your own custom indicators gives you complete control over how data is calculated and displayed on your charts.
In this hands-on tutorial, we will build a custom MQL5 indicator that measures the distance between price and a Moving Average, helping you spot overextended market conditions.
---------------------------------------------------
1. Creating a New Indicator in MetaEditor
To start building your custom indicator:
1. Open MetaEditor (press F4 inside MT5).
2. Click New on the top toolbar to launch the MQL5 Wizard.
3. Select Indicator (template) and click Next.
4. Name your indicator (e.g., CustomMADistance), set your output parameters, and click Finish.
---------------------------------------------------
2. Understanding Indicator Properties & Buffers
Custom indicators require special preprocessor directives and indicator buffers to draw lines or histograms on the chart window:
• #property indicator_separate_window: Plots the indicator in a separate sub-window beneath the main price chart.
• #property indicator_buffers: Defines how many data arrays will be plotted.
• Indicator Buffers: Dynamic arrays that store calculated values for every historical bar.
---------------------------------------------------
3. Complete Custom MQL5 Indicator Code
Clear your newly opened file and paste the following MQL5 code:
//+------------------------------------------------------------------+
//| CustomMADistance.mq5 |
//| Copyright 2026, Tech & Code |
//+------------------------------------------------------------------+
#property copyright "Tech & Code Lab"
#property link ""
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
// --- Plot Settings
#property indicator_label1 "MA Distance"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
// --- Inputs
input int MAPeriod = 20; // Moving Average Period
// --- Indicator Buffers
double MADistanceBuffer[];
int maHandle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Map indicator buffer
SetIndexBuffer(0, MADistanceBuffer, INDICATOR_DATA);
ArraySetAsSeries(MADistanceBuffer, true);
// Initialize Moving Average handle
maHandle = iMA(_Symbol, _Period, MAPeriod, 0, MODE_SMA, PRICE_CLOSE);
if(maHandle == INVALID_HANDLE)
{
Print("Failed to create MA handle.");
return(INIT_FAILED);
}
Print("Custom MA Distance Indicator Initialized Successfully!");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
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 long &spread[])
{
// Check available bars
if(rates_total < MAPeriod) return(0);
// Determine starting point for calculations
int limit = prev_calculated == 0 ? rates_total - MAPeriod : rates_total - prev_calculated;
// Copy MA values to a temporary array or calculate directly
double maValues[];
ArraySetAsSeries(maValues, true);
if(CopyBuffer(maHandle, 0, 0, limit + 1, maValues) <= 0) return(0);
// Main calculation loop
for(int i = limit; i >= 0 && !IsStopped(); i--)
{
// Distance = Current Close Price minus Moving Average Value
MADistanceBuffer[i] = close[i] - maValues[i];
}
return(rates_total);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
IndicatorRelease(maHandle);
Print("Custom Indicator Removed.");
}
---------------------------------------------------
4. Compiling & Attaching to Your Chart
1. Press F7 in MetaEditor to compile your code (ensure 0 errors).
2. Go back to MetaTrader 5, open the Navigator panel (Ctrl + N), and look under **Indicators**.
3. Drag `CustomMADistance` onto any chart window to view your custom calculations plotted live in a sub-window!
---------------------------------------------------
Final Thoughts
Building custom indicators gives you raw analytical power in MT5. You can easily feed these calculated indicator buffer values into your Expert Advisors to trigger automated trades when thresholds are crossed.
Stay tuned for our next hands-on guide as we power toward our content goals!
Comments
Post a Comment