MetaTrader has an A/D indicator, but building your own makes the close-location logic explicit and lets you feed the buffer into an Expert Advisor. See the explainer for the concept.
What you’ll need
- MetaTrader 5 with MetaEditor
- Save as
AlgoGen.AD.mq5underMQL5/Indicators/
The source
//+------------------------------------------------------------------+
//| AlgoGen.AD.mq5 |
//| Copyright 2026, AlgoGen |
//| https://www.algogen.io |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, AlgoGen"
#property link "https://www.algogen.io"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "A/D"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrMediumSeaGreen
#property indicator_width1 2
input bool InpUseRealVolume = true;
double ADBuffer[];
int OnInit()
{
SetIndexBuffer(0, ADBuffer, INDICATOR_DATA);
IndicatorSetString(INDICATOR_SHORTNAME, "AlgoGen A/D Line");
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[])
{
if(rates_total < 1) return(0);
int start;
if(prev_calculated == 0) { ADBuffer[0] = 0.0; start = 1; }
else start = prev_calculated - 1;
for(int i = start; i < rates_total; i++)
{
double rng = high[i] - low[i];
double vol = InpUseRealVolume ? (double)volume[i] : (double)tick_volume[i];
double mfm = (rng == 0.0) ? 0.0
: ((close[i] - low[i]) - (high[i] - close[i])) / rng;
ADBuffer[i] = ADBuffer[i - 1] + mfm * vol; // cumulative
}
return(rates_total);
}
//+------------------------------------------------------------------+
Install & compile
- Drop it in
MQL5/Indicators/, press F7. - Drag onto a chart — a separate window shows the cumulative A/D Line, matching the output chart.
Gotchas
- Cumulative recurrence.
ADBuffer[i] = ADBuffer[i-1] + mfvis the running total; theprev_calculatedfast path must continue from the last value, never restart. - Flat-bar guard.
rng == 0.0 ? 0.0avoids dividing by zero on a locked bar. - Volume source. Real volume is ideal; on FX feeds you’ll usually have only tick
volume, making it a proxy. MQL5 also has
iADif you prefer the built-in — the custom version exposes the multiplier and the volume choice.
Same indicator elsewhere: Python, Pine Script, EasyLanguage, NinjaScript. Then test an A/D filter in AlgoGen.
This post is educational, not financial advice. Indicators describe the past; they don’t predict the future. Backtest anything before you risk real money on it.
Sources and further reading
- Technical indicator functions (MetaQuotes)
