本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title = "Delta Pressure Divergence Pyramid", shorttitle = "DPD Pyramid", overlay = false, max_labels_count = 500, max_lines_count = 500)
// ═══════════════════════════════ INPUTS ═══════════════════════════════
grpE = "Delta Engine"
deltaLen = input.int(20, "Delta Window", minval = 2, group = grpE, tooltip = "Number of bars summed to build the volume-weighted pressure ratio. Higher = smoother, slower oscillator. Lower = faster, noisier oscillator.")
clvWeight = input.float(0.5, "Close-Location Weight", minval = 0.0, maxval = 1.0, step = 0.1, group = grpE, tooltip = "Blend between candle body direction (0) and close position inside the bar range (1). Higher values react more to wicks and closing strength.")
smoothLen = input.int(3, "Oscillator Smoothing", minval = 1, group = grpE, tooltip = "EMA length applied to the raw pressure ratio. Higher = fewer whipsaws but more lag. 1 disables smoothing.")
sigLen = input.int(9, "Signal EMA Length", minval = 1, group = grpE, tooltip = "EMA of the oscillator used as the trigger line. Higher = fewer, later crossovers. Lower = more, earlier crossovers.")
zoneLevel = input.float(30.0, "OB/OS Level (±)", minval = 5.0, maxval = 95.0, step = 1.0, group = grpE, tooltip = "Oscillator level marking strong buying (+) or selling (-) pressure. Higher = rarer zone signals. Lower = more frequent zone signals.")
zoneMemory = input.int(10, "Zone Memory Bars", minval = 1, group = grpE, tooltip = "How many recent bars may have touched the OB/OS zone for a crossover to count as a zone trigger. Higher = more permissive.")
grpD = "Divergence"
pivL = input.int(5, "Pivot Left Bars", minval = 1, group = grpD, tooltip = "Bars to the left that must be lower/higher to confirm an oscillator pivot. Higher = fewer, more significant pivots.")
pivR = input.int(2, "Pivot Right Bars", minval = 1, group = grpD, tooltip = "Bars to the right needed to confirm a pivot. Higher = more reliable pivots but divergences are detected later.")
maxGap = input.int(60, "Max Bars Between Pivots", minval = 5, group = grpD, tooltip = "Ignore divergences whose two pivots are farther apart than this. Lower = only fresh, local divergences.")
divWindow = input.int(8, "Divergence Valid Window", minval = 1, group = grpD, tooltip = "Bars after a confirmed divergence during which a signal-line crossover can trigger a trade. Higher = more permissive.")
showDivLines = input.bool(true, "Show Divergence Lines", group = grpD, tooltip = "Draw lines between the two oscillator pivots that formed a divergence.")
grpS = "Signal Triggers"
useDivTrigger = input.bool(true, "Divergence Trigger", group = grpS, tooltip = "Allow signals when a recent divergence is followed by an oscillator/signal crossover.")
useZoneTrigger = input.bool(true, "Zone Crossover Trigger", group = grpS, tooltip = "Allow signals when the oscillator crosses its signal line after recently visiting the OB/OS zone.")
grpF = "Weakness Fixes"
useConfirmed = input.bool(true, "Confirmed Bars Only (No Repaint)", group = grpF, tooltip = "Signals and pyramid adds are only generated after the bar closes, so they never appear and disappear on the live bar.")
useTrend = input.bool(true, "Trend Filter", group = grpF, tooltip = "Buy only above the trend EMA and sell only below it. Reduces counter-trend signals but may miss early reversals.")
trendLen = input.int(200, "Trend EMA Length", minval = 10, group = grpF, tooltip = "Length of the trend EMA. Higher = slower, long-term trend definition. Lower = reacts faster to trend changes.")
divOverride = input.bool(true, "Divergence Overrides Trend", group = grpF, tooltip = "Let divergence-based signals ignore the trend filter, so genuine reversals can still trigger.")
useVolFilter = input.bool(true, "Volatility Filter", group = grpF, tooltip = "Block signals when current ATR is well below its average, avoiding dead or choppy markets.")
atrLen = input.int(14, "Volatility ATR Length", minval = 1, group = grpF, tooltip = "ATR length used by the volatility filter. Higher = smoother volatility reading.")
atrBaseLen = input.int(100, "Volatility Baseline Length", minval = 10, group = grpF, tooltip = "SMA length of ATR used as the normal volatility baseline. Higher = longer reference period.")
minVolRatio = input.float(0.8, "Min ATR / Baseline Ratio", minval = 0.1, step = 0.05, group = grpF, tooltip = "Signals require ATR at least this fraction of its baseline. Higher = only trade in active markets, fewer signals.")
useAdx = input.bool(false, "ADX Sideways Filter", group = grpF, tooltip = "Block signals when ADX is below the threshold, filtering range-bound markets. Adds lag to reversal signals.")
adxLen = input.int(14, "ADX Length", minval = 1, group = grpF, tooltip = "DI and ADX smoothing length. Higher = smoother but slower ADX.")
adxMin = input.float(18.0, "ADX Minimum", minval = 1.0, step = 1.0, group = grpF, tooltip = "Minimum ADX required for a signal. Higher = only strong trends, fewer signals.")
cooldown = input.int(5, "Signal Cooldown Bars", minval = 0, group = grpF, tooltip = "Minimum bars between two main signals of any side. Higher = fewer back-to-back or flip-flop signals.")
oneDir = input.bool(true, "Block Repeated Same-Side Signals", group = grpF, tooltip = "After a Buy, another main Buy is ignored until a Sell occurs (and vice versa). Extra entries come only from the pyramid engine.")
volFallback = input.bool(true, "No-Volume Fallback", group = grpF, tooltip = "If a bar has no volume data, weight it as 1 so the oscillator still works on symbols without volume (e.g. some FX/CFD feeds).")
grpP = "Pyramid Orders"
usePyr = input.bool(true, "Enable Pyramid", group = grpP, tooltip = "Allow extra orders in the direction of the active signal when price moves the set distance from the last order.")
maxOrders = input.int(4, "Max Orders Per Side", minval = 1, maxval = 10, group = grpP, tooltip = "Total orders allowed per side, including the first signal. Higher = larger possible position and risk.")
pyrDir = input.string("Against (Average In)", "Pyramid Direction", options = ["Against (Average In)", "With Trend (Scale In)"], group = grpP, tooltip = "Average In: add Buy when price drops (Sell when it rises) by the step. Scale In: add Buy when price rises (Sell when it falls) by the step.")
distMode = input.string("ATR", "Step Distance Mode", options = ["ATR", "Ticks"], group = grpP, tooltip = "Measure the distance between pyramid orders in ATR multiples (adapts to volatility) or a fixed number of ticks.")
distTicks = input.int(200, "Step Distance (Ticks)", minval = 1, group = grpP, tooltip = "Distance in ticks (syminfo.mintick) between pyramid orders when mode is Ticks. Higher = fewer, wider-spaced adds.")
distAtrLen = input.int(14, "Step ATR Length", minval = 1, group = grpP, tooltip = "ATR length for the step distance when mode is ATR. Higher = steadier step size.")
distAtrMul = input.float(1.0, "Step ATR Multiplier", minval = 0.1, step = 0.1, group = grpP, tooltip = "Step distance = ATR x this value. Higher = fewer, wider-spaced pyramid adds.")
grpV = "Visuals"
showLabels = input.bool(true, "Show Order Number Labels", group = grpV, tooltip = "Show B1, B2... and S1, S2... labels on the price chart for each order.")
showRaw = input.bool(true, "Show Raw Pressure Columns", group = grpV, tooltip = "Display the per-bar unsmoothed pressure ratio as columns behind the oscillator.")
bullCol = input.color(color.rgb(38, 166, 91), "Bullish Color", group = grpV, tooltip = "Color for buying pressure, bullish divergences and Buy orders.")
bearCol = input.color(color.rgb(229, 57, 53), "Bearish Color", group = grpV, tooltip = "Color for selling pressure, bearish divergences and Sell orders.")
sigCol = input.color(#ffb74d, "Signal Line Color", group = grpV, tooltip = "Color of the signal EMA line.")
// ═══════════════════════════════ PRESSURE ENGINE ═══════════════════════════════
float rng = math.max(high - low, syminfo.mintick)
float bodyPart = (close - open) / rng // -1..+1 body direction & size
float clvPart = ((close - low) - (high - close)) / rng // -1..+1 close location in range
float pressure = (1.0 - clvWeight) * bodyPart + clvWeight * clvPart
// FIX: no-volume fallback so symbols without volume still produce a reading
bool volMissing = na(volume) or volume <= 0
float vol = volFallback and volMissing ? 1.0 : nz(volume)
float sumDelta = math.sum(pressure * vol, deltaLen)
float sumVol = math.sum(vol, deltaLen)
float rawOsc = sumVol > 0 ? 100.0 * sumDelta / sumVol : 0.0 // bounded -100..+100
float osc = ta.ema(rawOsc, smoothLen)
float sig = ta.ema(osc, sigLen)
float barPress = 100.0 * pressure
// ═══════════════════════════════ FILTERS ═══════════════════════════════
float trendMA = ta.ema(close, trendLen)
float atrV = ta.atr(atrLen)
float atrBase = ta.sma(atrV, atrBaseLen)
[diPlus, diMinus, adxV] = ta.dmi(adxLen, adxLen)
// FIX: volatility filter against dead/choppy markets
bool volOk = not useVolFilter or (not na(atrBase) and atrV >= atrBase * minVolRatio)
// FIX: ADX filter against sideways markets
bool adxOk = not useAdx or (not na(adxV) and adxV >= adxMin)
// FIX: repaint protection — act only on closed bars
bool confOk = not useConfirmed or barstate.isconfirmed
// ═══════════════════════════════ DIVERGENCE ═══════════════════════════════
float ph = ta.pivothigh(osc, pivL, pivR)
float pl = ta.pivotlow(osc, pivL, pivR)
int pivBar = bar_index - pivR
var float prevPhOsc = na
var float prevPhPrice = na
var int prevPhBar = na
var float prevPlOsc = na
var float prevPlPrice = na
var int prevPlBar = na
var int lastBullDivBar = na
var int lastBearDivBar = na
bool bullDivNow = false
bool bearDivNow = false
float pivHighPrice = high[pivR]
float pivLowPrice = low[pivR]
if not na(pl)
// Bullish: price lower low, oscillator higher low, pivot in negative territory, pivots not too far apart (FIX: stale divergence)
if not na(prevPlOsc) and (pivBar - prevPlBar) <= maxGap and pl > prevPlOsc and pivLowPrice < prevPlPrice and pl < 0
bullDivNow := true
lastBullDivBar := bar_index
if showDivLines
line.new(prevPlBar, prevPlOsc, pivBar, pl, color = bullCol, width = 2)
prevPlOsc := pl
prevPlPrice := pivLowPrice
prevPlBar := pivBar
if not na(ph)
// Bearish: price higher high, oscillator lower high, pivot in positive territory
if not na(prevPhOsc) and (pivBar - prevPhBar) <= maxGap and ph < prevPhOsc and pivHighPrice > prevPhPrice and ph > 0
bearDivNow := true
lastBearDivBar := bar_index
if showDivLines
line.new(prevPhBar, prevPhOsc, pivBar, ph, color = bearCol, width = 2)
prevPhOsc := ph
prevPhPrice := pivHighPrice
prevPhBar := pivBar
// ═══════════════════════════════ SIGNAL LOGIC ═══════════════════════════════
bool crossUp = ta.crossover(osc, sig)
bool crossDn = ta.crossunder(osc, sig)
bool wasOS = ta.lowest(osc, zoneMemory) <= -zoneLevel
bool wasOB = ta.highest(osc, zoneMemory) >= zoneLevel
bool bullDivRecent = not na(lastBullDivBar) and (bar_index - lastBullDivBar) <= divWindow
bool bearDivRecent = not na(lastBearDivBar) and (bar_index - lastBearDivBar) <= divWindow
// Divergence trigger: recent divergence + crossover (or divergence confirmed while already above/below signal)
bool divBuy = useDivTrigger and bullDivRecent and (crossUp or (bullDivNow and osc > sig))
bool divSell = useDivTrigger and bearDivRecent and (crossDn or (bearDivNow and osc < sig))
// Zone trigger: crossover after a recent visit to OB/OS zone
bool zoneBuy = useZoneTrigger and wasOS and crossUp
bool zoneSell = useZoneTrigger and wasOB and crossDn
// FIX: trend filter (divergence may override)
bool trendBuyOk = not useTrend or close > trendMA or (divOverride and divBuy)
bool trendSellOk = not useTrend or close < trendMA or (divOverride and divSell)
var int side = 0 // 1 = buy side active, -1 = sell side active
var int buyCount = 0
var int sellCount = 0
var float lastBuyPrice = na
var float lastSellPrice = na
var int lastSignalBar = na
// FIX: cooldown against back-to-back / flip-flop signals
bool cdOk = na(lastSignalBar) or (bar_index - lastSignalBar) > cooldown
bool buyRaw = (divBuy or zoneBuy) and trendBuyOk and volOk and adxOk
bool sellRaw = (divSell or zoneSell) and trendSellOk and volOk and adxOk
// FIX: block repeated same-side signals
bool buySignal = buyRaw and confOk and cdOk and (not oneDir or side != 1)
bool sellSignal = sellRaw and confOk and cdOk and (not oneDir or side != -1) and not buySignal
// ═══════════════════════════════ PYRAMID ENGINE ═══════════════════════════════
// Average In : Buy adds when close <= lastBuyPrice - step ; Sell adds when close >= lastSellPrice + step
// Scale In : Buy adds when close >= lastBuyPrice + step ; Sell adds when close <= lastSellPrice - step
float stepAtr = ta.atr(distAtrLen) * distAtrMul
float stepDist = distMode == "Ticks" ? distTicks * syminfo.mintick : stepAtr
bool averageIn = pyrDir == "Against (Average In)"
bool pyrBuy = false
bool pyrSell = false
if buySignal
side := 1
buyCount := 1
lastBuyPrice := close
sellCount := 0
lastSellPrice := na
lastSignalBar := bar_index
else if sellSignal
side := -1
sellCount := 1
lastSellPrice := close
buyCount := 0
lastBuyPrice := na
lastSignalBar := bar_index
else if usePyr and confOk and not na(stepDist)
if side == 1 and buyCount < maxOrders and not na(lastBuyPrice)
bool hitBuy = averageIn ? close <= lastBuyPrice - stepDist : close >= lastBuyPrice + stepDist
if hitBuy
buyCount += 1
lastBuyPrice := close
pyrBuy := true
else if side == -1 and sellCount < maxOrders and not na(lastSellPrice)
bool hitSell = averageIn ? close >= lastSellPrice + stepDist : close <= lastSellPrice - stepDist
if hitSell
sellCount += 1
lastSellPrice := close
pyrSell := true
// Numbered order labels on the price chart
if showLabels and (buySignal or pyrBuy)
label.new(bar_index, low - atrV * 0.8, "B" + str.tostring(buyCount), style = label.style_label_up, color = buySignal ? bullCol : color.new(bullCol, 40), textcolor = color.white, size = size.small, force_overlay = true)
if showLabels and (sellSignal or pyrSell)
label.new(bar_index, high + atrV * 0.8, "S" + str.tostring(sellCount), style = label.style_label_down, color = sellSignal ? bearCol : color.new(bearCol, 40), textcolor = color.white, size = size.small, force_overlay = true)
// ═══════════════════════════════ PLOTS ═══════════════════════════════
hline(0, "Zero", color = color.gray, linestyle = hline.style_dashed)
hline(zoneLevel, "Overbought", color = color.new(bearCol, 50), linestyle = hline.style_dotted)
hline(-zoneLevel, "Oversold", color = color.new(bullCol, 50), linestyle = hline.style_dotted)
plot(showRaw ? barPress : na, "Raw Pressure", color = barPress >= 0 ? color.new(bullCol, 75) : color.new(bearCol, 75), style = plot.style_columns)
plot(osc, "Pressure Oscillator", color = osc >= sig ? bullCol : bearCol, linewidth = 2)
plot(sig, "Signal EMA", color = sigCol, linewidth = 1)
plot(bullDivNow ? pl : na, "Bull Divergence Pivot", color = bullCol, style = plot.style_circles, linewidth = 4, offset = -pivR)
plot(bearDivNow ? ph : na, "Bear Divergence Pivot", color = bearCol, style = plot.style_circles, linewidth = 4, offset = -pivR)
// Price-chart markers: first order = triangle, pyramid add = small circle
plotshape(buySignal, "Buy", shape.triangleup, location.belowbar, color.green, size = size.small, force_overlay = true)
plotshape(pyrBuy, "Pyramid Buy", shape.circle, location.belowbar, color.new(color.green, 30), size = size.tiny, force_overlay = true)
plotshape(sellSignal, "Sell", shape.triangledown, location.abovebar, color.red, size = size.small, force_overlay = true)
plotshape(pyrSell, "Pyramid Sell", shape.circle, location.abovebar, color.new(color.red, 30), size = size.tiny, force_overlay = true)
// ═══════════════════════════════ ALERTS ═══════════════════════════════
alertcondition(buySignal, "DPD Buy", "DPD Buy on {{ticker}} at {{close}}")
alertcondition(sellSignal, "DPD Sell", "DPD Sell on {{ticker}} at {{close}}")
alertcondition(pyrBuy, "DPD Pyramid Buy", "DPD Pyramid Buy add on {{ticker}} at {{close}}")
alertcondition(pyrSell, "DPD Pyramid Sell", "DPD Pyramid Sell add on {{ticker}} at {{close}}")