Delta Cluster Zone Rejection Pyramid

TaninWiselyWealth · study · 277 行 · 点赞 55 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator(title = "Delta Cluster Zone Rejection Pyramid", shorttitle = "DCZR Pyramid", overlay = true, max_boxes_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════ INPUTS ═══════════════════════════════
grpZ = "Zone Engine"
pivLen     = input.int(5, "Pivot Length", minval = 1, group = grpZ, tooltip = "Bars on each side required to confirm a swing high/low. Higher = fewer, more significant zones but confirmed later. Lower = more zones, faster but noisier.")
zoneAtrLen = input.int(14, "Zone ATR Length", minval = 1, group = grpZ, tooltip = "ATR length used to size each zone at the moment its pivot formed. Higher = steadier zone widths.")
zoneMult   = input.float(0.5, "Zone Half-Width (ATR x)", minval = 0.05, step = 0.05, group = grpZ, tooltip = "Zone extends this many ATRs above and below the pivot price. Higher = wider zones, more touches and signals. Lower = tighter, more precise zones.")
strLen     = input.int(100, "Strength Lookback", minval = 10, group = grpZ, tooltip = "Bars used to rank the pivot's cluster volume as a percentile. Higher = strength compared against a longer history.")
minStrRes  = input.float(60.0, "Min Resistance Strength %", minval = 0.0, maxval = 100.0, step = 5.0, group = grpZ, tooltip = "Only swing highs whose cluster volume ranks at or above this percentile become resistance zones. Higher = fewer, stronger zones.")
minStrSup  = input.float(60.0, "Min Support Strength %", minval = 0.0, maxval = 100.0, step = 5.0, group = grpZ, tooltip = "Only swing lows whose cluster volume ranks at or above this percentile become support zones. Higher = fewer, stronger zones.")
maxZones   = input.int(5, "Max Zones Per Side", minval = 1, maxval = 20, group = grpZ, tooltip = "Maximum active zones kept per side. When exceeded, the oldest zone is dropped. Higher = more levels on chart.")
useFlip    = input.bool(true, "Polarity Flip", group = grpZ, tooltip = "A broken resistance becomes a new support zone and a broken support becomes a new resistance zone, so retests after breakouts can trigger signals.")
 
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. Fewer counter-trend bounces but may miss major reversals.")
trendLen      = input.int(200, "Trend EMA Length", minval = 10, group = grpF, tooltip = "Length of the trend EMA. Higher = slower long-term trend. Lower = reacts faster to trend changes.")
showTrend     = input.bool(false, "Show Trend EMA", group = grpF, tooltip = "Plot the trend EMA on the chart.")
useVolFilter  = input.bool(true, "Volatility Filter", group = grpF, tooltip = "Block signals when 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, break buffer and label spacing. Higher = smoother 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 active markets, fewer signals.")
useDelta      = input.bool(false, "Delta Confirmation", group = grpF, tooltip = "Support signals need net buying in the zone's pivot cluster; resistance signals need net selling. Fewer but better-backed signals.")
useTouchLimit = input.bool(true, "Touch Limit", group = grpF, tooltip = "Stop signalling from a zone after it has been touched too many times, since repeatedly tested levels tend to weaken and break.")
maxTouches    = input.int(3, "Max Touches Per Zone", minval = 1, group = grpF, tooltip = "Number of fresh touches a zone may take and still produce signals. Lower = only first tests are traded.")
useAge        = input.bool(true, "Zone Age Limit", group = grpF, tooltip = "Remove zones older than the set number of bars so stale levels do not trigger signals.")
maxAge        = input.int(300, "Max Zone Age (Bars)", minval = 10, group = grpF, tooltip = "Bars after the pivot before a zone expires. Higher = older levels stay active longer.")
breakBuf      = input.float(0.1, "Break Buffer (ATR x)", minval = 0.0, step = 0.05, group = grpF, tooltip = "Close must pass the zone edge by this many ATRs to count as a break. Higher = fewer false breaks, zones survive wicks longer.")
useMerge      = input.bool(true, "Merge Overlapping Zones", group = grpF, tooltip = "When a new zone overlaps an existing one on the same side, keep only the stronger zone. Reduces clutter and duplicate 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 zones still form on symbols without volume (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"
showZones    = input.bool(true, "Show Zones", group = grpV, tooltip = "Draw active support and resistance zones as boxes extending to the current bar.")
showZoneText = input.bool(true, "Show Zone Strength & Delta", group = grpV, tooltip = "Write the zone's volume strength percentile and buy-minus-sell delta inside each box.")
textSizeIn   = input.string("small", "Zone Text Size", options = ["tiny", "small", "normal", "large"], group = grpV, tooltip = "Font size of the text inside zone boxes.")
zoneTransp   = input.int(82, "Zone Fill Transparency", minval = 0, maxval = 100, group = grpV, tooltip = "Transparency of zone fill. Higher = lighter, less intrusive zones.")
showLabels   = input.bool(true, "Show Order Number Labels", group = grpV, tooltip = "Show B1, B2... and S1, S2... labels for each order.")
resCol       = input.color(color.rgb(82, 151, 255), "Resistance Color", group = grpV, tooltip = "Color of resistance zones.")
supCol       = input.color(color.rgb(38, 166, 91), "Support Color", group = grpV, tooltip = "Color of support zones.")
 
// ═══════════════════════════════ TYPES & HELPERS ═══════════════════════════════
type Zone
    float top
    float bot
    float strength
    float buyVol
    float sellVol
    int   startBar
    int   born
    int   touches
    box   bx
 
txtSize = switch textSizeIn
    "tiny"   => size.tiny
    "normal" => size.normal
    "large"  => size.large
    => size.small
 
f_zoneText(bool isRes, float strength, float bV, float sV) =>
    (isRes ? "R " : "S ") + str.tostring(strength, "#") + "% | Δ " + str.tostring(bV - sV, format.volume)
 
// Adds a zone; with merging, an overlapping weaker zone is replaced and a stronger one blocks the new zone
f_addZone(array<Zone> zones, bool isRes, float top, float bot, float strength, float bV, float sV, int startBar, color col) =>
    bool skip = false
    if useMerge and zones.size() > 0
        for i = zones.size() - 1 to 0
            Zone z = zones.get(i)
            bool overlap = top >= z.bot and bot <= z.top
            if overlap and not skip
                if z.strength >= strength
                    skip := true
                else
                    box.delete(z.bx)
                    zones.remove(i)
    if not skip
        box bx = na
        if showZones
            bx := box.new(startBar, top, bar_index, bot, border_color = color.new(col, 40), bgcolor = color.new(col, zoneTransp), text = showZoneText ? f_zoneText(isRes, strength, bV, sV) : "", text_color = col, text_size = txtSize, text_halign = text.align_right, text_valign = text.align_center)
        zones.push(Zone.new(top, bot, strength, bV, sV, startBar, bar_index, 0, bx))
        if zones.size() > maxZones
            Zone old = zones.shift()
            box.delete(old.bx)
    not skip
 
// ═══════════════════════════════ VOLUME / DELTA ENGINE ═══════════════════════════════
float rng = math.max(high - low, syminfo.mintick)
 
// FIX: no-volume fallback
bool  volMissing = na(volume) or volume <= 0
float vol        = volFallback and volMissing ? 1.0 : nz(volume)
 
// Close-location split: share of each bar's volume assigned to buyers vs sellers
float buyPart  = vol * (close - low) / rng
float sellPart = vol - buyPart
 
int   win      = pivLen * 2 + 1
float winBuy   = math.sum(buyPart, win)
float winSell  = math.sum(sellPart, win)
float winVol   = math.sum(vol, win)
float strength = ta.percentrank(winVol, strLen)   // 0..100 percentile of the pivot cluster volume
 
float zoneAtr = ta.atr(zoneAtrLen)
float atrV    = ta.atr(atrLen)
float atrBase = ta.sma(atrV, atrBaseLen)
float trendMA = ta.ema(close, trendLen)
 
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
 
var array<Zone> resZones = array.new<Zone>()
var array<Zone> supZones = array.new<Zone>()
 
// New zones from confirmed pivots (window of win bars ending now is centred on the pivot)
if not na(ph) and not na(strength) and not na(zoneAtr[pivLen]) and strength >= minStrRes
    float hw = zoneAtr[pivLen] * zoneMult
    f_addZone(resZones, true, ph + hw, ph - hw, strength, winBuy, winSell, bar_index - pivLen, resCol)
 
if not na(pl) and not na(strength) and not na(zoneAtr[pivLen]) and strength >= minStrSup
    float hw = zoneAtr[pivLen] * zoneMult
    f_addZone(supZones, false, pl + hw, pl - hw, strength, winBuy, winSell, bar_index - pivLen, supCol)
 
// ═══════════════════════════════ ZONE MAINTENANCE & TOUCHES ═══════════════════════════════
float breakBufV = nz(atrV) * breakBuf
float prevHigh  = high[1]
float prevLow   = low[1]
 
bool resHit = false
bool supHit = false
 
if resZones.size() > 0
    for i = resZones.size() - 1 to 0
        Zone z = resZones.get(i)
        bool broken  = close > z.top + breakBufV
        // FIX: stale zone expiry
        bool expired = useAge and (bar_index - z.startBar) > maxAge
        if broken or expired
            box.delete(z.bx)
            resZones.remove(i)
            if broken and useFlip
                f_addZone(supZones, false, z.top, z.bot, z.strength, z.buyVol, z.sellVol, bar_index, supCol)
        else
            if not na(z.bx)
                z.bx.set_right(bar_index)
            if bar_index > z.born
                bool freshTouch = high >= z.bot and prevHigh < z.bot
                if freshTouch
                    z.touches += 1
                // Rejection: wick into zone, bearish close back below the zone bottom
                bool rejection = high >= z.bot and close < z.bot and close < open
                // FIX: touch limit
                bool touchOk = not useTouchLimit or z.touches <= maxTouches
                bool deltaOk = not useDelta or z.sellVol >= z.buyVol
                if rejection and touchOk and deltaOk
                    resHit := true
 
if supZones.size() > 0
    for i = supZones.size() - 1 to 0
        Zone z = supZones.get(i)
        bool broken  = close < z.bot - breakBufV
        bool expired = useAge and (bar_index - z.startBar) > maxAge
        if broken or expired
            box.delete(z.bx)
            supZones.remove(i)
            if broken and useFlip
                f_addZone(resZones, true, z.top, z.bot, z.strength, z.buyVol, z.sellVol, bar_index, resCol)
        else
            if not na(z.bx)
                z.bx.set_right(bar_index)
            if bar_index > z.born
                bool freshTouch = low <= z.top and prevLow > z.top
                if freshTouch
                    z.touches += 1
                // Rejection: wick into zone, bullish close back above the zone top
                bool rejection = low <= z.top and close > z.top and close > open
                bool touchOk = not useTouchLimit or z.touches <= maxTouches
                bool deltaOk = not useDelta or z.buyVol >= z.sellVol
                if rejection and touchOk and deltaOk
                    supHit := true
 
// ═══════════════════════════════ FILTERS ═══════════════════════════════
// FIX: volatility filter against dead/choppy markets
bool volOk  = not useVolFilter or (not na(atrBase) and atrV >= atrBase * minVolRatio)
// FIX: repaint protection — act only on closed bars
bool confOk = not useConfirmed or barstate.isconfirmed
// FIX: trend filter
bool trendBuyOk  = not useTrend or close > trendMA
bool trendSellOk = not useTrend or close < trendMA
 
// ═══════════════════════════════ SIGNAL LOGIC ═══════════════════════════════
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  = supHit and trendBuyOk and volOk
bool sellRaw = resHit and trendSellOk and volOk
 
// 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
// Counters reset when the opposite main signal fires.
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
if showLabels and (buySignal or pyrBuy)
    label.new(bar_index, low - nz(atrV) * 0.8, "B" + str.tostring(buyCount), style = label.style_label_up, color = buySignal ? color.green : color.new(color.green, 40), textcolor = color.white, size = size.small)
if showLabels and (sellSignal or pyrSell)
    label.new(bar_index, high + nz(atrV) * 0.8, "S" + str.tostring(sellCount), style = label.style_label_down, color = sellSignal ? color.red : color.new(color.red, 40), textcolor = color.white, size = size.small)
 
// ═══════════════════════════════ PLOTS ═══════════════════════════════
plot(showTrend ? trendMA : na, "Trend EMA", color = color.new(color.gray, 20), linewidth = 2)
 
// First order = triangle, pyramid add = small circle
plotshape(buySignal, "Buy", shape.triangleup, location.belowbar, color.green, size = size.small)
plotshape(pyrBuy, "Pyramid Buy", shape.circle, location.belowbar, color.new(color.green, 30), size = size.tiny)
plotshape(sellSignal, "Sell", shape.triangledown, location.abovebar, color.red, size = size.small)
plotshape(pyrSell, "Pyramid Sell", shape.circle, location.abovebar, color.new(color.red, 30), size = size.tiny)
 
// ═══════════════════════════════ ALERTS ═══════════════════════════════
alertcondition(buySignal, "DCZR Buy", "DCZR Buy (support rejection) on {{ticker}} at {{close}}")
alertcondition(sellSignal, "DCZR Sell", "DCZR Sell (resistance rejection) on {{ticker}} at {{close}}")
alertcondition(pyrBuy, "DCZR Pyramid Buy", "DCZR Pyramid Buy add on {{ticker}} at {{close}}")
alertcondition(pyrSell, "DCZR Pyramid Sell", "DCZR Pyramid Sell add on {{ticker}} at {{close}}")

← 返回列表