NinjaTrader 8 ships a DPO indicator, and the from-scratch version is a short C# loop
around a displaced SMA. See the explainer.
What you’ll need
- NinjaTrader 8 and the NinjaScript Editor (New → Indicator)
The built-in
// Anywhere in OnBarUpdate:
double dpoVal = DPO(20)[0]; // 20-period Detrended Price Oscillator
From scratch
To own the math and see the displacement:
public class AlgoGenDPO : Indicator
{
private int period = 20;
private int shift;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "AlgoGen DPO";
IsOverlay = false;
AddPlot(Brushes.DodgerBlue, "DPO");
AddLine(Brushes.Gray, 0, "Zero");
}
else if (State == State.Configure)
{
shift = period / 2 + 1; // displacement = N/2 + 1
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < period + shift)
return;
// N-period SMA ending `shift` bars ago.
double sum = 0;
for (int k = 0; k < period; k++)
sum += Close[shift + k];
double smaPast = sum / period;
Value[0] = Close[0] - smaPast; // close - displaced SMA
}
[NinjaScriptProperty]
[Range(2, int.MaxValue)]
[Display(Name = "Period", GroupName = "Parameters", Order = 0)]
public int Period
{
get { return period; }
set { period = Math.Max(2, value); }
}
}
Close[shift + k] walks the N-bar window that ends shift bars ago, giving the
displaced SMA; Close[0] - smaPast is the DPO — the detrended line around zero in the
output chart. For a 20-period DPO, shift is 11.
Gotchas
shift = period / 2 + 1. The+1is part of the definition.- The SMA window is in the past.
Close[shift + k], notClose[k]; that backward alignment is the whole indicator. - Warm-up guard.
if (CurrentBar < period + shift) return;— you read the window plus its displacement. - Not momentum. The DPO measures cycle spacing; don’t read the latest value as a real-time trend signal.
Reading the cycle
The DPO’s job is cycle length — eyeball the bars between successive DPO peaks, then test a rule around that cycle in AlgoGen.
Same indicator elsewhere: Python, MQL5, Pine Script, EasyLanguage.
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
- NinjaScript system indicator methods (NinjaTrader)
