Detrended Price Oscillator in MetaTrader (MQL5) — Full Source

A displaced SMA subtracted from price

Detrended Price Oscillator in MetaTrader MQL5
Detrended Price Oscillator in MetaTrader MQL5

MetaTrader 5 doesn’t ship the DPO as standard, so you build it — and it’s short: an SMA, a backward index shift, and a subtraction. See the explainer.

What you’ll need

  • MetaTrader 5 and the MetaEditor
  • A new Custom Indicator, plotted in a separate window with a zero line.

The source

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "DPO"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2
#property indicator_level1  0

input int InpPeriod = 20;   // period

double DpoBuffer[];
int    Shift;

int OnInit()
{
    SetIndexBuffer(0, DpoBuffer, INDICATOR_DATA);
    Shift = InpPeriod / 2 + 1;              // displacement = N/2 + 1
    return(INIT_SUCCEEDED);
}

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[])
{
    if(rates_total < InpPeriod + Shift) return(0);

    int start = (prev_calculated > InpPeriod + Shift)
                ? prev_calculated - 1 : InpPeriod + Shift - 1;

    for(int i = start; i < rates_total; i++)
    {
        // N-period SMA ending `Shift` bars ago.
        double sum = 0.0;
        for(int k = 0; k < InpPeriod; k++)
            sum += price[i - Shift - k];
        double smaPast = sum / InpPeriod;

        DpoBuffer[i] = price[i] - smaPast;  // close - displaced SMA
    }
    return(rates_total);
}

Shift = InpPeriod / 2 + 1 is the displacement. The inner loop computes the N-period SMA ending Shift bars in the past, and price[i] - smaPast is the DPO — the detrended line oscillating around zero in the output chart.

Gotchas

  • Shift = N/2 + 1. Mind the +1; it’s the standard displacement.
  • The SMA is in the past. price[i - Shift - k] walks the window that ends Shift bars ago, not the current window. That backward alignment is the whole indicator.
  • Warm-up needs InpPeriod + Shift bars. You’re reading the SMA window plus its displacement, so guard for both.
  • Not a momentum line. The DPO is for cycle spacing; don’t treat the latest value as a real-time trend signal.

Same indicator elsewhere: Python, Pine Script, EasyLanguage, NinjaScript. Then test it 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

  1. Technical indicator functions (MetaQuotes)

Historical research from the Algogen archive. Not investment advice.

Blog

Have a strategy idea?

Describe it in plain English, preview where your rules fire, then decide whether the evidence is worth a backtest.

Keep me postedHow it works