The DPO in Pine is a moving average and an offset. Pine’s built-in DPO study exists, but it’s genuinely worth writing from scratch here because the offset direction is the one thing you need to understand. See the explainer.
What you’ll need
- A TradingView account (free tier is fine)
- The Pine Editor
The source (non-centered)
//@version=5
indicator("AlgoGen Detrended Price Oscillator", shorttitle="AG DPO", overlay=false)
length = input.int(20, "Length")
offset = length / 2 + 1 // displacement = N/2 + 1
sma = ta.sma(close, length)
dpo = close - sma[offset] // close minus SMA from `offset` bars ago
plot(dpo, "DPO", color=#2a78d6, linewidth=2)
hline(0, "Zero", color=color.gray)
sma[offset] is the SMA value from offset bars ago — Pine’s history-referencing
operator does the displacement. close - sma[offset] is the detrended cycle, the line
around zero in the output chart. For a 20-length DPO, offset is 11.
The centered version
If you want the classic centered DPO — shifted into the past so it centres on its data —
use plot’s offset argument to draw it back:
//@version=5
indicator("AlgoGen DPO (centered)", overlay=false)
length = input.int(20, "Length")
off = length / 2 + 1
dpo = close - ta.sma(close, length)
plot(dpo, "DPO", color=#2a78d6, linewidth=2, offset=-off) // drawn `off` bars back
hline(0, color=color.gray)
Here offset=-off shifts the plot backward, so the DPO centres on its window but the
last off bars are empty at the right edge. Same indicator, different display — know which
one you’re looking at.
Which to use
Use the non-centered version for anything you’ll compute on or reference at the current bar (it has a value on the last bar). Use the centered version purely for visual cycle analysis, where lining the oscillator up with its data matters more than the right edge.
Gotchas
offset = length / 2 + 1. The+1is part of the definition; don’t drop it.sma[offset]vsplot(..., offset=). The first shifts the data (non-centered); the second shifts the drawing (centered). Very different results.- Not momentum. The DPO measures cycle spacing; reading its latest value as a trend signal misuses it.
overlay=false. It oscillates around zero — put it in its own pane.
Same indicator elsewhere: Python, MQL5, EasyLanguage, NinjaScript. Then test a cycle rule 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
- Pine Script built-ins (TradingView)
