本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Uncle_the_shooter
//@version=6
indicator("Stretch and Push Oscillator", shorttitle="SPO", overlay=false, precision=1, max_lines_count=500, max_labels_count=500, max_bars_back=500)
// ──────────────────────────── SETTING ────────────────────────────
grpLen = "① Oscillator components"
lenStretch = input.int(30, "Stretch: length", minval=2, group=grpLen, tooltip="Number of bars used to calculate the average price level and the typical candle range. Shows how far price has moved away from its “normal” level.\n\nHigher value: calmer reading, catches larger and longer overextensions.\nLower value: reacts faster to short breakouts.")
lenPush = input.int(6, "Push: length (fast)", minval=2, group=grpLen, tooltip="Number of recent bars used to assess the strength of buyers or sellers – whether consecutive candles print new highs/lows and how large they are.\n\nWhen price is still stretched but this strength fades, the move is running out of fuel and the odds of a reversal increase.\nLower value: faster reaction, more noise.")
smoothLen = input.int(3, "Smoothing", minval=1, group=grpLen, tooltip="Smooths the oscillator line. A higher value reduces random level crossings but delays signals by 1–2 bars.")
grpW = "② Weights and normalization"
wStretch = input.float(1.0, "Stretch weight", minval=0, step=0.1, group=grpW, tooltip="How strongly the distance of price from its mean affects the result. Increase it if the oscillator should mainly show that the market has gone “too far”.\n\n0 = component disabled.")
wPush = input.float(1.0, "Push weight", minval=0, step=0.1, group=grpW, tooltip="How strongly the current push of buyers or sellers affects the result. Increase it for earlier warnings of a tiring move – the oscillator reacts sooner when the push starts to fade.\n\n0 = component disabled.")
normLen = input.int(300, "Normalization window (bars)", minval=50, group=grpW, tooltip="Each component is compared with its own history over this many bars and rescaled to a −100 to +100 range. A reading of +80 means the current deviation is larger than 90% of readings in that period.\n\nThis way the weights reflect the real influence of each component.\nLonger window: more stable scale. Shorter: adapts faster to changes in market volatility.")
grpLevels = "③ Levels and zones"
OB = input.float(70, "OB / OS levels", minval=1, maxval=100, inline="lvl", group=grpLevels)
OS = input.float(-70, "", minval=-100, maxval=-1, inline="lvl", group=grpLevels, tooltip="Left field: overbought (OB), right field: oversold (OS).\n\nOverbought (OB): above this level the market is overextended to the upside.\nOversold (OS): below this level it is overextended to the downside.\n\nA return of the oscillator from the zone generates a REVERSAL signal. Levels closer to ±100 give fewer but more extreme signals.")
zoneFill = input.bool(true, "Fill OB/OS zones", group=grpLevels, tooltip="Highlights the area above the overbought level and below the oversold level.")
useDynamicLevels = input.bool(true, "Dynamic zone intensity", group=grpLevels, tooltip="The zone is barely visible when the oscillator is far away and becomes more pronounced as it approaches. Makes it easier to notice that the market is reaching an extreme.")
farTransp = input.int(92, "Transparency: far from zone", minval=0, maxval=100, group=grpLevels, active=useDynamicLevels, tooltip="Zone transparency when the oscillator is far from it (100 = invisible).")
zoneTransp = input.int(50, "Transparency: inside zone", minval=0, maxval=100, group=grpLevels, tooltip="Zone transparency when the oscillator is inside it (0 = full color).")
grpSig = "④ Oscillator average and histogram"
showSig = input.bool(true, "Show oscillator average", group=grpSig, tooltip="Moving average of the oscillator line. A cross between the oscillator and this line marks a change in short-term momentum, and the distance between them forms the histogram.")
sigLen = input.int(9, "Average length", minval=1, group=grpSig, tooltip="Lower value: the average follows the oscillator more closely, more crossings.\nHigher value: fewer but more reliable crossings.\n\nThe length also affects the histogram and therefore TREND signals (diamonds) – even when the average and histogram are hidden.")
sigWidth = input.int(1, "Average line width", minval=1, maxval=4, group=grpSig, active=showSig)
sigColMode = input.string("Neutral", "Average color", options=["Neutral", "Directional"], inline="sigc", group=grpSig, active=showSig)
sigNeutral = input.color(#B2B5BE, "", inline="sigc", group=grpSig, active=showSig and sigColMode == "Neutral", tooltip="Neutral: a single color chosen next to this field.\nDirectional: bullish color when the average is above zero, bearish color when it is below zero.")
showHist = input.bool(true, "Show histogram", group=grpSig, tooltip="Difference between the oscillator and its average. Bars above zero: bullish momentum, below zero: bearish momentum.\n\nStrong color: momentum is building.\nPale color: momentum is fading. If the oscillator is still in the OB/OS zone, this is an early warning that the move is exhausting.")
histStrong = input.int(55, "Transparency: momentum building", minval=0, maxval=100, group=grpSig, active=showHist)
histWeak = input.int(85, "Transparency: momentum fading", minval=0, maxval=100, group=grpSig, active=showHist, tooltip="The bigger the difference from the previous setting, the easier it is to tell the two phases apart.")
grpCommon = "⑤ Signals – common settings"
onClose = input.bool(true, "Signals on bar close only", group=grpCommon, tooltip="Applies to all signals (REVERSAL and TREND), divergences and warnings: they appear only once the bar closes – they don’t flicker or disappear while the bar is forming, and alerts trigger once, at bar close.\n\nThe oscillator line and the dashboard still update in real time.\nDisabled: live signals during the bar (they may disappear before it closes).")
markStyle = input.string("At levels", "Marker position", options=["At levels", "On oscillator line"], group=grpCommon, tooltip="Applies to both signal families. Only the position changes – the shape always shows the family:\n▲▼ triangle = REVERSAL, ◆ diamond = TREND.\n\nAt levels: REVERSAL below the OS level / above the OB level, TREND right next to the zero line (Buy below, Sell above) – easier to read on a busy chart.\nOn oscillator line: the marker is placed where the oscillator gave the signal.")
grpContra = "⑥ REVERSAL: return from OB/OS zone"
showContra = input.bool(true, "Zone return signals", group=grpContra, tooltip="Buy: the oscillator exits the oversold zone (OS) upwards.\nSell: the oscillator exits the overbought zone (OB) downwards.\n\nThese are signals against the current move. Only filters ⑦ (confirmation) and ⑧ (ADX) apply to them.\nDisabled: no markers, B/S labels or alerts for this family.")
divSigMode = input.string("Require", "Signals and divergence", options=["Ignore", "Mark", "Require"], group=grpContra, active=showContra, tooltip="Ignore: signals and divergences are shown independently.\nMark: when a signal and a divergence in the same direction occur close together, an extra B/S label appears – a higher-quality signal.\nRequire: only divergence-backed signals (B/S labels) are shown on the chart. The “REVERSAL Buy/Sell” alerts and the “Reversal signal” dashboard row still cover all signals – for divergence-backed signals only, use the “+ divergence” alerts.")
divValid = input.int(15, "Divergence linking window (bars)", minval=1, group=grpContra, active=showContra and divSigMode != "Ignore", tooltip="How many bars may separate a signal from a divergence in the same direction for them to be treated as one event and marked with a B/S label.\n\nA divergence is reported only after the second high/low is confirmed, often many bars after the signal – the B/S label then appears on the bar where the divergence is confirmed. Too small a window makes labels rare.")
grpConf = "⑦ REVERSAL: confirmation filter"
useConf = input.bool(false, "Confirm with signal candle breakout", group=grpConf, active=showContra, tooltip="Applies ONLY to REVERSAL signals (zone return). TREND signals (diamonds) are not confirmed.\n\nThe signal does not appear immediately after the oscillator leaves the zone.\nSell: only when a later candle closes below the low of the signal candle.\nBuy: only when a later candle closes above the high of the signal candle.\n\nFewer false signals at the cost of a later entry.")
confMaxBars = input.int(0, "Max bars to wait (0 = no limit)", minval=0, group=grpConf, active=showContra and useConf, tooltip="How many bars to wait for confirmation. Once the limit is exceeded, the pending signal is cancelled.\n0 = waits until confirmed or until a signal in the opposite direction appears.")
showPending = input.bool(true, "Show pending signals", group=grpConf, active=showContra and useConf, tooltip="A pale marker where the oscillator left the zone, visible before the signal is confirmed. Shown only for signals that passed the ADX filter. Lets you prepare for the entry.")
grpADX = "⑧ REVERSAL: ADX filter"
useAdx = input.bool(true, "ADX filter for zone return signals", group=grpADX, active=showContra, tooltip="Applies ONLY to REVERSAL signals (triangles and B/S labels). TREND signals (diamonds) are not filtered – they have their own trend wave filter (⑩).\n\nADX measures trend strength regardless of direction. When enabled, the filter lets zone return signals through only when the trend is weak or weakening – trading against a strong trend is the riskiest.")
adxLen = input.int(14, "DI length / ADX smoothing", minval=1, inline="adxl", group=grpADX, active=useAdx)
adxSmooth = input.int(14, "", minval=1, inline="adxl", group=grpADX, active=useAdx, tooltip="Left field: DI length, right field: ADX smoothing (classic values: 14 and 14). Shorter values reduce ADX lag at the cost of more noise.\n\nThese settings also affect the ADX row in the dashboard.")
adxRevThr = input.float(25, "Pass when ADX below", minval=0, maxval=100, step=1, group=grpADX, active=useAdx, tooltip="A zone return signal passes when ADX is below this level. This threshold also sets the “weak / strong trend” state in the dashboard.")
adxRevFall = input.bool(true, "…or when ADX is falling", group=grpADX, active=useAdx, tooltip="Also passes the signal at high ADX if ADX is falling – the trend is losing strength.\n\nRecommended: ADX lags heavily and is usually at its highest at the peak of a strong move, so the threshold alone would cut out some of the best reversal signals.")
adxFallBars = input.int(3, "ADX decline: lookback (bars)", minval=1, group=grpADX, active=useAdx and adxRevFall, tooltip="ADX is considered falling when it is lower than this many bars ago.")
adxDivBypass = input.bool(true, "Divergence bypasses filter", group=grpADX, active=useAdx, tooltip="A zone return signal backed by a divergence in the same direction (B/S label) appears despite the ADX filter.\n\nDivergences naturally occur while the trend is still strong, so without this option the filter would remove almost all B/S labels.")
adxStyle = input.string("Show faded", "Filtered signals", options=["Hide", "Show faded"], group=grpADX, active=useAdx, tooltip="Hide: filtered signals disappear.\nShow faded: they remain as a pale marker – you can see how many signals the filter removes. They do not trigger alerts and do not appear in the dashboard.")
adxFadeT = input.int(70, "Filtered signals transparency", minval=0, maxval=100, group=grpADX, active=useAdx and adxStyle == "Show faded", tooltip="Transparency of filtered signal markers (100 = invisible).")
grpTrend = "⑨ TREND: zero-line cross"
showTrend = input.bool(true, "Zero-line cross signals (diamonds)", group=grpTrend, tooltip="A signal with the move, not against it.\nBuy: the oscillator crosses above zero and the histogram above zero rises for at least the given number of consecutive bars.\nSell: the oscillator crosses below zero and the histogram below zero deepens for at least the given number of consecutive bars.\n\nOne signal per cross. Confirmation and ADX filters do not apply to this family; it can be filtered by the trend wave (⑩).")
trendHistBars = input.int(2, "Building histogram: min. consecutive bars", minval=1, group=grpTrend, active=showTrend, tooltip="How many of the latest histogram bars must build in a row in the direction of the move – these are the strong-colored bars.\nBuy: each above zero and higher than the previous one.\nSell: each below zero and lower than the previous one.\n\nA single fading (pale) bar or a bar on the wrong side of zero resets the count – no gaps allowed.\nHigher value: fewer false crosses, but later.")
trendWindow = input.int(5, "Max bars after zero cross", minval=0, group=grpTrend, active=showTrend, tooltip="If the histogram condition is not met on the cross bar, the signal can still appear for this many bars – as long as the oscillator stays on the same side of zero. After that the signal expires, to avoid entering the move too late.\n\n0 = on the cross bar only.")
grpWave = "⑩ TREND: trend wave"
showWave = input.bool(true, "Show trend wave", group=grpWave, tooltip="A long EMA of the oscillator line, shown as a semi-transparent wave between it and the zero line.\n\nWave above zero: buyers dominate, below zero: sellers dominate. Provides context for short oscillator swings.\nHiding the wave does not disable the diamond filter or the dashboard row.")
waveLen = input.int(50, "Wave length (oscillator EMA)", minval=2, group=grpWave, tooltip="Longer length: calmer wave, changes side of zero more slowly.\nShorter: reacts faster, but gives false direction changes more often.")
waveTransp = input.int(80, "Wave transparency", minval=0, maxval=100, group=grpWave, active=showWave, tooltip="Wave transparency at its edge; it fades out completely towards the zero line. 100 = invisible.")
useWaveFilt = input.bool(true, "Diamonds only in wave direction", group=grpWave, active=showTrend, tooltip="Buy (diamond) only when the wave is above zero.\nSell (diamond) only when the wave is below zero.\n\nRejects zero-line crosses against the broader direction of the move. Applies to diamonds only.")
grpDiv = "⑪ Divergences"
showDiv = input.bool(true, "Draw divergences", group=grpDiv, tooltip="Regular divergence.\nBullish: price makes a lower low while the oscillator makes a higher low.\nBearish: price makes a higher high while the oscillator makes a lower high.\n\nIndicates a weakening of the current move and a possible reversal.\nHiding divergences does not disable B/S labels, alerts or the dashboard row.")
showDivLines = input.bool(true, "Divergence lines", group=grpDiv, active=showDiv)
showDivLabels = input.bool(true, "“D” labels", group=grpDiv, active=showDiv, tooltip="Lines connect the two oscillator highs or lows that form the divergence. The “D” label marks the second of them.")
divLB = input.int(3, "High/low confirmation (bars)", minval=1, maxval=20, group=grpDiv, tooltip="An oscillator high or low is considered confirmed only when it has this many bars on each side without a new extreme. The divergence is therefore reported with this delay, but it never disappears afterwards.\n\nThe alert and the dashboard entry appear on the confirmation bar, while the line and the “D” label are drawn at the high/low itself.\nLower value: faster, but more weak divergences.")
divMaxGap = input.int(60, "Max distance between extremes (bars)", minval=5, maxval=450, group=grpDiv, tooltip="Maximum number of bars between the two highs/lows forming a divergence. Too large a value links extremes from different market phases.")
divZoneOnly = input.bool(true, "First extreme in OB/OS zone", group=grpDiv, tooltip="Bullish: the first oscillator low must lie in the oversold zone (≤ OS).\nBearish: the first oscillator high must lie in the overbought zone (≥ OB).\n\nEach subsequent low/high is compared with the latest extreme inside the zone, so smaller swings in between do not break the pattern.\nRejects divergences that were not preceded by an extreme market deviation.")
divCleanLine = input.bool(true, "Line must not cross the oscillator", group=grpDiv, tooltip="Between the two extremes the oscillator must stay above the divergence line (bullish) or below it (bearish). Rejects patterns interrupted by a move in between.")
divZeroSide = input.bool(true, "Second extreme on the correct side of zero", group=grpDiv, tooltip="Bullish: the second oscillator low must be below zero.\nBearish: the second oscillator high must be above zero.\n\nA divergence matters more when the market is still deviated.")
grpDash = "⑫ Dashboard"
showDash = input.bool(true, "Show dashboard", group=grpDash, tooltip="A table with the current market state: oscillator value, zone, momentum direction, latest REVERSAL and TREND signal, trend wave direction, latest divergence and trend strength by ADX, along with the number of bars since each event.")
dashPos = input.string("Top right", "Position / size", options=["Top right", "Top left", "Bottom right", "Bottom left"], inline="dp", group=grpDash, active=showDash)
dashSize = input.string("Small", "", options=["Small", "Normal"], inline="dp", group=grpDash, active=showDash, tooltip="Position and text size of the dashboard in the indicator pane.")
dashTheme = input.string("Dark", "Theme", options=["Dark", "Light"], group=grpDash, active=showDash, tooltip="Match it to your chart theme so the dashboard stays readable.")
grpStyle = "⑬ Appearance and colors"
bullC = input.color(#089981, "Colors: bullish / bearish", inline="cust", group=grpStyle)
bearC = input.color(#F23645, "", inline="cust", group=grpStyle, tooltip="Colors used across all indicator elements: for the buy side (up moves, Buy signals, oversold) and the sell side (down moves, Sell signals, overbought).")
lineWidth = input.int(2, "Oscillator line width", minval=1, maxval=4, group=grpStyle)
useGradLine = input.bool(true, "Line color by deviation strength", group=grpStyle, tooltip="The line is gray near zero and gains full color as it approaches the OB/OS levels – deviation strength is visible at a glance.\nDisabled: bullish color above zero and bearish color below zero.")
useGlow = input.bool(true, "Line glow", group=grpStyle, tooltip="A subtle glow around the oscillator line that improves its readability.")
// ─────────────────────────────── CONSTANTS ────────────────────────────
neutralC = #787B86
peakTransp = 60 // Transparency of the zero fill at the oscillator edge
float sigOff = 10.0 // Marker offset from the level (OB/OS or zero) in “At levels” mode
float divSigOff = 18.0 // B/S label offset from the OB/OS level
// Bar close gate – always true on history, in real time only on the bar's last tick
barClosed = not onClose or barstate.isconfirmed
markOnLine = markStyle == "On oscillator line"
norm(x) => ta.percentrank(x, normLen) * 2.0 - 100.0
candleRange = high - low
// === 1. STRETCH – distance of close from the mean in units of the typical range ===
// The raw value is not clipped: percentile rank is scale-independent,
// and clipping would create ties that understate readings in the oversold zone.
midSma = ta.sma(hl2, lenStretch)
band = ta.sma(candleRange, lenStretch)
stretchRaw = band > 0 ? (close - midSma) / band * 100 : 0.0
// === 2. PUSH – candle breakout direction weighted by its relative range ===
avgRange = ta.sma(candleRange, lenPush)
deltaHigh = high - high[1]
deltaLow = low[1] - low
dir = deltaHigh > deltaLow and deltaHigh > 0 ? 1 : deltaLow > deltaHigh and deltaLow > 0 ? -1 : 0
weight = avgRange > 0 ? math.min(candleRange / avgRange, 3.0) : 1.0
pushRaw = math.sum(dir * weight, lenPush) / lenPush * 100
// === NORMALIZATION – percentile rank in the ±100 range ===
stretchN = norm(stretchRaw)
pushN = norm(pushRaw)
// === OSCILLATOR – weighted average of the components, smoothed ===
wSum = wStretch + wPush
raw = wSum > 0 ? (wStretch * stretchN + wPush * pushN) / wSum : 0.0
osc = ta.ema(raw, smoothLen)
oscAboveZero = osc >= 0
oscEma = ta.ema(osc, sigLen)
// === HISTOGRAM – distance of the oscillator from its average ===
hist = osc - oscEma
histPrev = hist[1]
histColor = hist >= 0 ? color.new(bullC, hist > hist[1] ? histStrong : histWeak) : color.new(bearC, hist < hist[1] ? histStrong : histWeak)
// === ADX FILTER – trend strength (no direction); applies to REVERSAL signals only ===
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxSmooth)
adxFalling = adx < adx[adxFallBars]
revOK = not useAdx or adx < adxRevThr or (adxRevFall and adxFalling)
showFaded = useAdx and adxStyle == "Show faded"
// === REGULAR DIVERGENCES ===
// Checks whether the oscillator stays on the correct side of the divergence line between the two extremes
divLineClean(int idx1, float v1, int idx2, float v2, bool above) =>
bool ok = true
int gap = idx2 - idx1
// The loop runs only for a pair of extremes within the allowed distance
if not na(v1) and not na(v2) and gap > 1 and gap <= divMaxGap
for i = 1 to gap - 1
float lv = v1 + (v2 - v1) * i / gap
float ov = osc[bar_index - (idx1 + i)]
if above ? ov < lv : ov > lv
ok := false
break
ok
// Reference point: the previous oscillator low/high, or with the zone filter –
// the latest low inside the OS zone / high inside the OB zone
var float divBotOsc = na
var float divBotPrc = na
var int divBotIdx = na
var float divTopOsc = na
var float divTopPrc = na
var int divTopIdx = na
var int lastBullDivBar = na
var int lastBearDivBar = na
pl = ta.pivotlow(osc, divLB, divLB)
ph = ta.pivothigh(osc, divLB, divLB)
// Line cleanliness is calculated globally on every bar (consistent historical calculation),
// for the reference point stored before the update below
bool botLineClean = divLineClean(divBotIdx, divBotOsc, bar_index - divLB, pl, true)
bool topLineClean = divLineClean(divTopIdx, divTopOsc, bar_index - divLB, ph, false)
bullDiv = false
if not na(pl) and barClosed
pIdx = bar_index - divLB
pPrc = low[divLB]
if not na(divBotOsc) and pIdx - divBotIdx <= divMaxGap and pl > divBotOsc and pPrc < divBotPrc and (not divZoneOnly or divBotOsc <= OS) and (not divZeroSide or pl < 0) and (not divCleanLine or botLineClean)
bullDiv := true
lastBullDivBar := bar_index
if showDiv and showDivLines
line.new(divBotIdx, divBotOsc, pIdx, pl, color=bullC, width=1)
if showDiv and showDivLabels
label.new(pIdx, pl, "D", style=label.style_label_up, color=bullC, textcolor=color.white, size=size.tiny)
if not divZoneOnly or pl <= OS
divBotOsc := pl
divBotPrc := pPrc
divBotIdx := pIdx
bearDiv = false
if not na(ph) and barClosed
pIdx = bar_index - divLB
pPrc = high[divLB]
if not na(divTopOsc) and pIdx - divTopIdx <= divMaxGap and ph < divTopOsc and pPrc > divTopPrc and (not divZoneOnly or divTopOsc >= OB) and (not divZeroSide or ph > 0) and (not divCleanLine or topLineClean)
bearDiv := true
lastBearDivBar := bar_index
if showDiv and showDivLines
line.new(divTopIdx, divTopOsc, pIdx, ph, color=bearC, width=1)
if showDiv and showDivLabels
label.new(pIdx, ph, "D", style=label.style_label_down, color=bearC, textcolor=color.white, size=size.tiny)
if not divZoneOnly or ph >= OB
divTopOsc := ph
divTopPrc := pPrc
divTopIdx := pIdx
// === TREND: WAVE – long EMA of the oscillator (directional context) ===
wave = ta.ema(osc, waveLen)
waveUp = wave > 0
wavePrev = wave[1]
waveCrossUp = ta.crossover(wave, 0)
waveCrossDn = ta.crossunder(wave, 0)
waveTurnUp = barClosed and waveCrossUp
waveTurnDn = barClosed and waveCrossDn
// === ZONE INTENSITY – depends on the oscillator's distance from the level ===
remap(val, inMin, inMax, outMin, outMax) =>
outMin + (val - inMin) * (outMax - outMin) / (inMax - inMin)
obT = useDynamicLevels ? math.round(remap(math.max(0, math.min(OB - osc, OB)), 0, OB, zoneTransp, farTransp)) : zoneTransp
osT = useDynamicLevels ? math.round(remap(math.max(0, math.min(osc - OS, -OS)), 0, -OS, zoneTransp, farTransp)) : zoneTransp
obZoneC = bearC
osZoneC = bullC
// Line color: neutral near zero, full at the OB/OS levels
oscCol = not useGradLine ? (oscAboveZero ? bullC : bearC) : osc >= 0 ? color.from_gradient(osc, 0, OB, neutralC, bullC) : color.from_gradient(osc, OS, 0, bearC, neutralC)
// ─────────────────────────────── DRAWING ──────────────────────────────
// Invisible ±100 lines keep the pane scale fixed
hline(100, "Scale +100", color=color.new(color.gray, 100), editable=false)
hline(-100, "Scale −100", color=color.new(color.gray, 100), editable=false)
hline(0, "Zero line", color=color.new(neutralC, 55), linestyle=hline.style_dotted)
// OB/OS levels – the visible lines also serve as edges of the zone fills
pOBz = plot(OB, "OB level", color=color.new(obZoneC, math.min(obT, 65)), linewidth=1)
pOSz = plot(OS, "OS level", color=color.new(osZoneC, math.min(osT, 65)), linewidth=1)
pTop = plot(100, editable=false, display=display.none)
pBot = plot(-100, editable=false, display=display.none)
pZero = plot(0, editable=false, display=display.none)
// OB/OS zones – gradient from the level towards ±100 (the outer edge is fully transparent)
fill(pTop, pOBz, top_value=100, bottom_value=OB, top_color=color.new(bearC, 100), bottom_color=zoneFill ? color.new(obZoneC, obT) : na, title="OB zone")
fill(pOSz, pBot, top_value=OS, bottom_value=-100, top_color=zoneFill ? color.new(osZoneC, osT) : na, bottom_color=color.new(bullC, 100), title="OS zone")
// Trend wave – invisible line, only the fill from the wave to zero is visible (strongest at the wave edge)
pWave = plot(wave, "Trend wave", color=color.new(neutralC, 100), editable=false, display=display.none)
fill(pWave, pZero, top_value=waveUp ? wave : 0, bottom_value=waveUp ? 0 : wave, top_color=showWave ? (waveUp ? color.new(bullC, waveTransp) : color.new(bearC, 100)) : na, bottom_color=showWave ? (waveUp ? color.new(bullC, 100) : color.new(bearC, waveTransp)) : na, title="Trend wave")
plot(showHist ? hist : na, "Momentum histogram", style=plot.style_columns, color=histColor)
plot(showSig ? oscEma : na, "Oscillator average", color=sigColMode == "Neutral" ? color.new(sigNeutral, 30) : (oscEma >= 0 ? bullC : bearC), linewidth=sigWidth)
plot(useGlow ? osc : na, "Glow", color=color.new(oscCol, 82), linewidth=math.min(lineWidth + 3, 6), editable=false)
pOsc = plot(osc, "SPO", color=oscCol, linewidth=lineWidth)
// Fill between the oscillator and the zero line – a single fill for both sides
fill(pOsc, pZero, top_value=osc > 0 ? osc : 0, bottom_value=osc > 0 ? 0 : osc, top_color=osc > 0 ? color.new(bullC, peakTransp) : color.new(bearC, 100), bottom_color=osc > 0 ? color.new(bullC, 100) : color.new(bearC, peakTransp), title="Zero fill")
// ─────────────────────── REVERSAL SIGNALS (zone return) ────────────────
// Base signal: the oscillator returns from the OS zone (Buy) or the OB zone (Sell)
rawBuy = showContra and barClosed and osc[1] <= OS and osc > OS
rawSell = showContra and barClosed and osc[1] >= OB and osc < OB
var float buyTrig = na
var int buyBar = na
var bool buyTrigOK = true // ADX filter result stored on the zone exit bar
var float sellTrig = na
var int sellBar = na
var bool sellTrigOK = true
// Cancel pending signals once the bar limit is exceeded
if confMaxBars > 0
if not na(buyTrig) and bar_index - buyBar > confMaxBars
buyTrig := na
if not na(sellTrig) and bar_index - sellBar > confMaxBars
sellTrig := na
// Confirmation: close beyond the range of the signal candle
confBuy = barClosed and not na(buyTrig) and bar_index > buyBar and close > buyTrig
confSell = barClosed and not na(sellTrig) and bar_index > sellBar and close < sellTrig
confBuyOK = buyTrigOK
confSellOK = sellTrigOK
if confBuy
buyTrig := na
if confSell
sellTrig := na
// A new base signal sets the confirmation level and cancels a pending opposite signal.
// If an earlier signal in the same direction was confirmed on the same bar,
// no new pending signal is created – one entry instead of two.
// ADX is evaluated on the zone exit bar – confirmation does not change it.
// Cancelling the opposite signal also works for a filtered signal.
newBuyTrig = rawBuy and not confBuy
newSellTrig = rawSell and not confSell
if rawBuy
sellTrig := na
if newBuyTrig
buyTrig := high
buyBar := bar_index
buyTrigOK := revOK
if rawSell
buyTrig := na
if newSellTrig
sellTrig := low
sellBar := bar_index
sellTrigOK := revOK
// Signals before and after the ADX filter
buySignalAll = useConf ? confBuy : rawBuy
sellSignalAll = useConf ? confSell : rawSell
buyPass = useConf ? confBuyOK : revOK
sellPass = useConf ? confSellOK : revOK
buySignal = buySignalAll and buyPass
sellSignal = sellSignalAll and sellPass
buyBlocked = buySignalAll and not buyPass
sellBlocked = sellSignalAll and not sellPass
// Pending signals only for those that passed the filter
pendBuy = newBuyTrig and revOK
pendSell = newSellTrig and revOK
// Linking signals with a divergence in the same direction
var int lastBuySig = na
var int lastSellSig = na
var bool buyDivDone = false
var bool sellDivDone = false
var int usedBullDivBar = na // divergence already marked with a label – not linked a second time
var int usedBearDivBar = na
// With “Divergence bypasses filter”, signals from before the ADX filter are used for linking
buyForDiv = adxDivBypass ? buySignalAll : buySignal
sellForDiv = adxDivBypass ? sellSignalAll : sellSignal
if buyForDiv
lastBuySig := bar_index
buyDivDone := false
lastSellSig := na
if sellForDiv
lastSellSig := bar_index
sellDivDone := false
lastBuySig := na
recentBuySig = not na(lastBuySig) and bar_index - lastBuySig <= divValid
recentSellSig = not na(lastSellSig) and bar_index - lastSellSig <= divValid
recentBullDiv = not na(lastBullDivBar) and bar_index - lastBullDivBar <= divValid and (na(usedBullDivBar) or lastBullDivBar != usedBullDivBar)
recentBearDiv = not na(lastBearDivBar) and bar_index - lastBearDivBar <= divValid and (na(usedBearDivBar) or lastBearDivBar != usedBearDivBar)
buyDivSignal = not buyDivDone and recentBuySig and recentBullDiv
sellDivSignal = not sellDivDone and recentSellSig and recentBearDiv
if buyDivSignal
buyDivDone := true
usedBullDivBar := lastBullDivBar
if sellDivSignal
sellDivDone := true
usedBearDivBar := lastBearDivBar
// ─────────────────────── TREND SIGNALS (zero-line cross) ───────────────
// Number of consecutive bars the histogram builds in the direction of the move (strong bars):
// Buy – bar above zero and higher than the previous one, Sell – bar below zero and lower than the previous one.
// Any fading bar or bar on the wrong side of zero resets the count – no gaps allowed.
var int histUpRun = 0
var int histDnRun = 0
histUpRun := hist > 0 and hist > hist[1] ? histUpRun + 1 : 0
histDnRun := hist < 0 and hist < hist[1] ? histDnRun + 1 : 0
zeroUp = ta.crossover(osc, 0)
zeroDn = ta.crossunder(osc, 0)
// Each cross “arms” one signal; it expires after trendWindow bars
// or when the oscillator returns to the other side of zero
var int zeroUpBar = na
var int zeroDnBar = na
var bool trendUpDone = true
var bool trendDnDone = true
if zeroUp
zeroUpBar := bar_index
trendUpDone := false
if zeroDn
zeroDnBar := bar_index
trendDnDone := false
trendUp = showTrend and barClosed and not trendUpDone and osc > 0 and (not useWaveFilt or wave > 0) and bar_index - zeroUpBar <= trendWindow and histUpRun >= trendHistBars
trendDn = showTrend and barClosed and not trendDnDone and osc < 0 and (not useWaveFilt or wave < 0) and bar_index - zeroDnBar <= trendWindow and histDnRun >= trendHistBars
if trendUp
trendUpDone := true
if trendDn
trendDnDone := true
// ─────────────────────────────── MARKERS ──────────────────────────────
showPlainSig = divSigMode != "Require"
showDivSig = divSigMode != "Ignore"
// REVERSAL: divergence-backed signal – B / S label
plotshape(showDivSig and buyDivSignal ? OS - divSigOff : na, title="REVERSAL Buy + divergence", location=location.absolute, style=shape.labelup, color=bullC, text="B", textcolor=color.white, size=size.tiny)
plotshape(showDivSig and sellDivSignal ? OB + divSigOff : na, title="REVERSAL Sell + divergence", location=location.absolute, style=shape.labeldown, color=bearC, text="S", textcolor=color.white, size=size.tiny)
// REVERSAL: signals pending confirmation
plotshape(showPlainSig and useConf and showPending and pendBuy ? (markOnLine ? osc : OS - sigOff) : na, title="REVERSAL Buy pending", location=location.absolute, color=color.new(bullC, 70), style=shape.triangleup, size=size.tiny)
plotshape(showPlainSig and useConf and showPending and pendSell ? (markOnLine ? osc : OB + sigOff) : na, title="REVERSAL Sell pending", location=location.absolute, color=color.new(bearC, 70), style=shape.triangledown, size=size.tiny)
// REVERSAL: signals filtered out by ADX – faded
plotshape(showPlainSig and showFaded and buyBlocked ? (markOnLine ? osc : OS - sigOff) : na, title="REVERSAL Buy filtered (ADX)", location=location.absolute, color=color.new(bullC, adxFadeT), style=shape.triangleup, size=size.tiny)
plotshape(showPlainSig and showFaded and sellBlocked ? (markOnLine ? osc : OB + sigOff) : na, title="REVERSAL Sell filtered (ADX)", location=location.absolute, color=color.new(bearC, adxFadeT), style=shape.triangledown, size=size.tiny)
// REVERSAL: base signals
plotshape(showPlainSig and buySignal ? (markOnLine ? osc : OS - sigOff) : na, title="REVERSAL Buy (return from OS)", location=location.absolute, color=bullC, style=shape.triangleup, size=size.tiny)
plotshape(showPlainSig and sellSignal ? (markOnLine ? osc : OB + sigOff) : na, title="REVERSAL Sell (return from OB)", location=location.absolute, color=bearC, style=shape.triangledown, size=size.tiny)
// TREND: zero-line cross – diamond (next to the zero line or on the oscillator line)
plotshape(trendUp ? (markOnLine ? osc : -sigOff) : na, title="TREND Buy (zero cross)", location=location.absolute, color=bullC, style=shape.diamond, size=size.tiny)
plotshape(trendDn ? (markOnLine ? osc : sigOff) : na, title="TREND Sell (zero cross)", location=location.absolute, color=bearC, style=shape.diamond, size=size.tiny)
// ─────────────────────────────── DASHBOARD ────────────────────────────
var int lastSigBar = na
var int lastSigDir = 0
if buySignal
lastSigBar := bar_index
lastSigDir := 1
if sellSignal
lastSigBar := bar_index
lastSigDir := -1
var int lastTrendBar = na
var int lastTrendDir = 0
if trendUp
lastTrendBar := bar_index
lastTrendDir := 1
if trendDn
lastTrendBar := bar_index
lastTrendDir := -1
var int lastDivBar = na
var int lastDivDir = 0
if bullDiv
lastDivBar := bar_index
lastDivDir := 1
if bearDiv
lastDivBar := bar_index
lastDivDir := -1
dashPosition = switch dashPos
"Top right" => position.top_right
"Top left" => position.top_left
"Bottom right" => position.bottom_right
=> position.bottom_left
txtSize = dashSize == "Small" ? size.small : size.normal
dashBg = dashTheme == "Dark" ? color.new(#131722, 15) : color.new(#FFFFFF, 10)
dashTxt = dashTheme == "Dark" ? #D1D4DC : #131722
var table dash = table.new(dashPosition, 2, 8, bgcolor=dashBg, frame_color=color.new(neutralC, 60), frame_width=1, border_color=color.new(neutralC, 85), border_width=1)
// State of a value oscillating around zero: side of zero (name) + direction of change (arrow).
// “building” = moving away from zero, “fading” = returning towards zero.
// Color: color of the zero side; pale when the value is fading (like the histogram bars).
stateTxt(float v, float vPrev, string upName, string dnName) =>
bool above = v >= 0
bool rising = v > vPrev
bool strong = above ? rising : not rising
(above ? upName : dnName) + " · " + (rising ? "▲" : "▼") + (strong ? " building" : " fading")
stateCol(float v, float vPrev) =>
bool above = v >= 0
bool strong = above ? v > vPrev : v <= vPrev
color.new(above ? bullC : bearC, strong ? 0 : 50)
// “BUY/SELL · n bars ago” text for the latest event
evtTxt(int barIdx, int dirVal, string upTxt, string dnTxt) =>
na(barIdx) ? "—" : (dirVal == 1 ? upTxt : dnTxt) + " · " + str.tostring(bar_index - barIdx) + " bars ago"
if showDash and barstate.islast
zoneTxt = osc >= OB ? "Overbought" : osc <= OS ? "Oversold" : "Neutral"
zoneCol = osc >= OB ? obZoneC : osc <= OS ? osZoneC : dashTxt
momTxt = stateTxt(hist, histPrev, "Bullish", "Bearish")
momCol = stateCol(hist, histPrev)
sigTxt = showContra ? evtTxt(lastSigBar, lastSigDir, "BUY", "SELL") : "off"
sigCol = lastSigDir == 1 ? bullC : lastSigDir == -1 ? bearC : dashTxt
trTxt = showTrend ? evtTxt(lastTrendBar, lastTrendDir, "BUY", "SELL") : "off"
trCol = lastTrendDir == 1 ? bullC : lastTrendDir == -1 ? bearC : dashTxt
waveTxt = stateTxt(wave, wavePrev, "Bullish", "Bearish") + " · " + str.tostring(wave, "#0.0")
waveCol = stateCol(wave, wavePrev)
divTxt = evtTxt(lastDivBar, lastDivDir, "Bullish", "Bearish")
divCol = lastDivDir == 1 ? bullC : lastDivDir == -1 ? bearC : dashTxt
adxStTxt = adx < adxRevThr ? "weak trend" : "strong trend"
adxTxt = str.tostring(adx, "#0.0") + (adx > adx[1] ? " ▲" : " ▼") + " · " + adxStTxt
adxLbl = useAdx ? "ADX (reversal filter)" : "ADX"
table.cell(dash, 0, 0, "SPO", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 0, str.tostring(osc, "#0.0"), text_color=oscCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 1, "Zone", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 1, zoneTxt, text_color=zoneCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 2, "Momentum", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 2, momTxt, text_color=momCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 3, "Reversal signal", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 3, sigTxt, text_color=sigCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 4, "Trend signal", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 4, trTxt, text_color=trCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 5, "Trend wave", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 5, waveTxt, text_color=waveCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 6, "Divergence", text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 6, divTxt, text_color=divCol, text_size=txtSize, text_halign=text.align_right)
table.cell(dash, 0, 7, adxLbl, text_color=dashTxt, text_size=txtSize, text_halign=text.align_left)
table.cell(dash, 1, 7, adxTxt, text_color=dashTxt, text_size=txtSize, text_halign=text.align_right)
else if not showDash and barstate.islast
table.clear(dash, 0, 0, 1, 7)
// ─────────────────────────────── ALERTS ───────────────────────────────
alertcondition(buySignal, "SPO REVERSAL Buy", "SPO: return from oversold")
alertcondition(sellSignal, "SPO REVERSAL Sell", "SPO: return from overbought")
alertcondition(buyDivSignal, "SPO REVERSAL Buy + divergence", "SPO: return from oversold + bullish divergence")
alertcondition(sellDivSignal, "SPO REVERSAL Sell + divergence", "SPO: return from overbought + bearish divergence")
alertcondition(trendUp, "SPO TREND Buy", "SPO: upward zero cross confirmed by histogram")
alertcondition(trendDn, "SPO TREND Sell", "SPO: downward zero cross confirmed by histogram")
alertcondition(waveTurnUp, "SPO trend wave ▲", "SPO: trend wave crossed above zero")
alertcondition(waveTurnDn, "SPO trend wave ▼", "SPO: trend wave crossed below zero")
alertcondition(bullDiv, "SPO bullish divergence", "SPO: bullish divergence (confirmed)")
alertcondition(bearDiv, "SPO bearish divergence", "SPO: bearish divergence (confirmed)")