Trend
Distance From Moving Average
How far price has stretched from a moving average, expressed as a percentage oscillator with symmetric bands so the reading is comparable across instruments and prices.
indicator
//@version=6
indicator("Distance From Moving Average", "MA Dist", format = format.percent, precision = 2)
length = input.int(50, "MA length", minval = 1, group = "Settings")
band = input.float(3.0, "Band percent", minval = 0.1, step = 0.1, group = "Settings")
bull = input.color(#26A69A, "Above the average", group = "Style")
bear = input.color(#EF5350, "Below the average", group = "Style")
neutral = input.color(#787B86, "Bands", group = "Style")
basis = ta.sma(close, length)
dist = basis > 0 ? (close - basis) / basis * 100 : 0
plot(dist, "Distance", color = dist >= 0 ? bull : bear, linewidth = 2)
hline(0, "Average", color = color.new(neutral, 40))
hline(band, "Upper band", color = color.new(bull, 50), linestyle = hline.style_dashed)
hline(-band, "Lower band", color = color.new(bear, 50), linestyle = hline.style_dashed)
stretchedUp = ta.crossover(dist, band)
stretchedDown = ta.crossunder(dist, -band)
plotshape(stretchedUp, "Stretched up", location = location.top, style = shape.triangledown, color = bull, size = size.tiny)
plotshape(stretchedDown, "Stretched down", location = location.bottom, style = shape.triangleup, color = bear, size = size.tiny)
alertcondition(stretchedUp, "Stretched above the average", "Price moved further above the moving average than the upper band")
alertcondition(stretchedDown, "Stretched below the average", "Price moved further below the moving average than the lower band")
This runs in TradingView, not here
Pine Script only executes inside TradingView. Paste the source into the Pine Editor and add it to a chart to see it plotted.
What it will not do
- A stretched reading says the move is fast, not that it is finished. Strong trends spend long runs outside the bands.
- A fixed percentage band suits one instrument and not another. Volatile symbols live outside it while quiet ones never reach it.
- The distance falls when the average catches up as well as when price comes back, and the plot cannot tell you which of the two happened.
Written from this description
Plot the percentage difference between close and a moving average as an oscillator around zero, draw bands at a configurable percentage either side, and alert when the distance crosses a band.
Educational only, not financial advice. The maths is simple arithmetic on the numbers you enter; it knows nothing about your broker, fees, slippage or the market. Something wrong with it? Say so in Site Feedback.