Strong Recovery Zones | ProjectSyndicate

ProjectSyndicate · study · 852 行 · 点赞 1,146 · TradingView 原页

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

Pine Script

//@version=6
indicator("Strong Recovery Zones", "Strong Recovery Zones", overlay = true, max_labels_count = 500, max_boxes_count = 500, max_polylines_count = 20)
 
gZ = "═══ Zones ═══"
sideMode    = input.string("Both", "Zone Side", options = ["Both", "Demand Only", "Supply Only"], group = gZ)
leftBars    = input.int(10, "Pivot Left", minval = 2, maxval = 50, group = gZ)
rightBars   = input.int(3, "Pivot Right", minval = 1, maxval = 20, group = gZ)
minVolStr   = input.int(25, "Min Pivot Volume Rank (%)", minval = 0, maxval = 100, group = gZ, tooltip = "Percentile rank of the pivot window's volume against the window below. Pivots on thinner volume never become zones. 0 = off. Ignored on symbols without volume.")
volHiLen    = input.int(100, "Volume Rank Window", minval = 10, maxval = 500, group = gZ)
heightMode  = input.string("Normalized ATR", "Zone Height", options = ["Normalized ATR", "Volume Wick Band"], group = gZ, tooltip = "Normalized ATR: every zone has the same clean height centered on the swing. Volume Wick Band: from the swing extreme to the volume-weighted body edge of the pivot window, clamped to the min/max.")
heightAtr   = input.float(0.6, "Normalized Height (ATR)", minval = 0.05, maxval = 10.0, step = 0.05, group = gZ)
minHAtr     = input.float(0.3, "Band Min Height (ATR)", minval = 0.05, maxval = 5.0, step = 0.05, group = gZ)
maxHAtr     = input.float(1.0, "Band Max Height (ATR)", minval = 0.1, maxval = 10.0, step = 0.05, group = gZ)
atrLen      = input.int(200, "ATR Length", minval = 5, maxval = 500, group = gZ)
lookbackBars= input.int(3000, "Lookback (bars, 0 = all)", minval = 0, group = gZ)
maxZones    = input.int(40, "Max Live Zones", minval = 2, maxval = 120, group = gZ)
maxLife     = input.int(1000, "Max Zone Life (bars)", minval = 50, group = gZ)
mergeAtr    = input.float(1.0, "Min Zone Spacing (ATR)", minval = 0.0, maxval = 10.0, step = 0.1, group = gZ, tooltip = "A new pivot whose center lands within this distance of a live same-side zone is merged into it as confluence (refreshing it and adding its volume) instead of stacking a second box. Opposite-side pivots that close are skipped.")
breakTol    = input.float(0.2, "Break Tolerance (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = gZ, tooltip = "A close this far beyond the far border breaks the zone.")
flipBroken  = input.bool(true, "Flip Broken Zones Into Breakers", group = gZ)
showHist    = input.bool(true, "Keep Broken Zones As History", group = gZ)
maxHist     = input.int(20, "Max History Zones", minval = 1, maxval = 200, group = gZ)
 
gT = "═══ Test & Recovery Engine ═══"
recAtr      = input.float(1.0, "Recovery Target (ATR beyond zone)", minval = 0.2, maxval = 6.0, step = 0.1, group = gT, tooltip = "A test is HELD only when price closes this far beyond the near border inside the test window. Every test resolves once: held, stalled, broken or expired, and all count in the statistics.")
testWin     = input.int(20, "Test Window (bars)", minval = 3, maxval = 200, group = gT)
sweepAtr    = input.float(0.15, "Sweep Depth (ATR beyond far border)", minval = 0.02, maxval = 4.0, step = 0.01, group = gT)
reclaimDpt  = input.string("Far Border", "Sweep Reclaim Close", options = ["Far Border", "Midline", "Near Border"], group = gT)
wickMin     = input.float(0.4, "Rejection Wick Min (of bar range)", minval = 0.1, maxval = 0.95, step = 0.05, group = gT)
useRsi      = input.bool(false, "Require RSI Extreme For Signals", group = gT)
rsiLen      = input.int(14, "RSI Length", minval = 2, maxval = 100, group = gT)
rsiWin      = input.int(8, "RSI Extreme Window", minval = 1, maxval = 60, group = gT)
rsiOs       = input.int(40, "RSI Oversold ≤", minval = 5, maxval = 50, group = gT)
rsiOb       = input.int(60, "RSI Overbought ≥", minval = 50, maxval = 95, group = gT)
 
gS = "═══ Zone Score (0–10) ═══"
minScore    = input.float(0.0, "Min Score To Display", minval = 0.0, maxval = 10.0, step = 0.5, group = gS)
strongThr   = input.float(7.0, "Strong Zone Threshold", minval = 0.0, maxval = 10.0, step = 0.5, group = gS)
wVol        = input.float(0.30, "Weight · Pivot Volume", minval = 0.0, maxval = 1.0, step = 0.05, group = gS)
wDep        = input.float(0.30, "Weight · Departure", minval = 0.0, maxval = 1.0, step = 0.05, group = gS)
wDef        = input.float(0.25, "Weight · Defense Record", minval = 0.0, maxval = 1.0, step = 0.05, group = gS)
wSwp        = input.float(0.15, "Weight · Confluence & Sweeps", minval = 0.0, maxval = 1.0, step = 0.05, group = gS)
sweepNorm   = input.float(2.0, "Confluences + Reclaims For Full Credit", minval = 1.0, step = 0.5, group = gS)
useDecay    = input.bool(true, "Decay While Ignored", group = gS)
decayBars   = input.int(400, "Full Decay Over (idle bars)", minval = 20, maxval = 5000, group = gS)
decayFloor  = input.float(0.7, "Decay Floor", minval = 0.1, maxval = 1.0, step = 0.05, group = gS)
 
gG = "═══ Signal Score (0–10) ═══"
sigMinScore = input.float(4.5, "Min Signal Score", minval = 0.0, maxval = 10.0, step = 0.5, group = gG)
sigZoneMin  = input.float(5.0, "Min Zone Score For Signals", minval = 0.0, maxval = 10.0, step = 0.5, group = gG)
sigStrong   = input.float(7.0, "Strong Signal Threshold", minval = 0.0, maxval = 10.0, step = 0.5, group = gG)
volLen      = input.int(20, "Volume Baseline Length", minval = 2, group = gG)
depthRef    = input.float(1.0, "Grab Depth Ref (ATR)", minval = 0.2, maxval = 6.0, step = 0.1, group = gG)
dispRef     = input.float(1.0, "Reclaim Displacement Ref (ATR)", minval = 0.1, maxval = 6.0, step = 0.1, group = gG)
volRef      = input.float(2.0, "Volume Surge Ref (x)", minval = 1.1, maxval = 8.0, step = 0.1, group = gG)
twDepth     = input.float(1.0, "Weight · Grab Depth", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
twWick      = input.float(1.0, "Weight · Rejection Wick", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
twVol       = input.float(1.0, "Weight · Volume Surge", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
twBase      = input.float(1.0, "Weight · Zone Score", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
twDisp      = input.float(1.0, "Weight · Displacement", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
twSpeed     = input.float(1.0, "Weight · Speed", minval = 0.0, maxval = 3.0, step = 0.1, group = gG)
 
gP = "═══ Probability Engine ═══"
probOn      = input.bool(true, "Enable Monte Carlo Probabilities", group = gP, tooltip = "Simulates forward paths from recent returns. Every zone label shows the chance price touches it within the horizon; the nearest demand and supply zones also show which is reached first and the typical bars to touch.")
mcModel     = input.string("Historical Resample", "Return Model", options = ["Historical Resample", "Gaussian"], group = gP)
mcPaths     = input.int(1000, "Paths", minval = 100, maxval = 3000, step = 100, group = gP)
mcHz        = input.int(30, "Horizon (bars)", minval = 5, maxval = 150, step = 5, group = gP)
mcSample    = input.int(300, "Return Sample (bars)", minval = 30, maxval = 3000, step = 10, group = gP)
mcDrift     = input.bool(false, "Keep Drift", group = gP)
mcSeed      = input.int(7, "Random Seed", minval = 0, group = gP)
mcTick      = input.bool(false, "Update On Every Tick", group = gP, tooltip = "Off: recalculated on confirmed bars only, so probabilities stay fixed until the bar closes.")
holdPrior   = input.float(4.0, "Hold Estimate Prior Strength", minval = 0.5, maxval = 50.0, step = 0.5, group = gP, tooltip = "Hold % blends the zone's own record with its side's record across all zones. Higher = leans more on the side record until the zone has more tests.")
showCone    = input.bool(false, "Show Forecast Cone", group = gP)
coneLo      = input.int(10, "Cone Lower Percentile", minval = 1, maxval = 49, group = gP)
coneHi      = input.int(90, "Cone Upper Percentile", minval = 51, maxval = 99, group = gP)
 
gD = "═══ Labels & Signals ═══"
labMode     = input.string("Compact", "Zone Labels", options = ["Compact", "Detailed", "Full", "Off"], group = gD, tooltip = "Compact: one line with score, zone type, held/tests, Touch (chance price reaches the zone within the horizon), Hold (chance it holds), First (chance this zone is reached before the opposite one) and the live state. Detailed and Full add more lines.")
showPerSide = input.int(4, "Zones Shown Per Side (0 = all)", minval = 0, maxval = 50, group = gD, tooltip = "Only the nearest zones above and below price are drawn and labelled. Every zone is still tracked and scored in the background.")
labSize     = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
labOff      = input.int(2, "Label Offset (bars right)", minval = 0, maxval = 50, group = gD)
labGapPct   = input.float(4.5, "Label Spacing (% of recent range)", minval = 1.0, maxval = 20.0, step = 0.5, group = gD, tooltip = "Minimum vertical spacing between zone labels so they never overlap.")
showSig     = input.bool(true, "Show Recovery Signals", group = gD)
maxSigs     = input.int(20, "Max Signals Drawn", minval = 1, maxval = 200, group = gD)
sigSize     = input.string("Small", "Signal Size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
showHeld    = input.bool(true, "Mark Confirmed Holds (◆)", group = gD)
 
gC = "═══ Style ═══"
bullCol     = input.color(#21c997, "Demand Tone", group = gC)
bearCol     = input.color(#cc24e2, "Supply Tone", group = gC)
coneCol     = input.color(#8c93a8, "Cone Tone", group = gC)
fillTransp  = input.int(72, "Strong Zone Transparency", minval = 40, maxval = 95, group = gC)
weakTransp  = input.int(90, "Weak Zone Transparency", minval = 50, maxval = 98, group = gC)
showBord    = input.bool(true, "Show Zone Borders", group = gC)
bordTransp  = input.int(30, "Border Transparency", minval = 0, maxval = 100, group = gC)
histTransp  = input.int(93, "History Zone Transparency", minval = 70, maxval = 99, group = gC)
glowOn      = input.bool(true, "Brighten Zones Near Price", group = gC)
glowRange   = input.float(2.5, "Glow Range (ATR)", minval = 0.2, maxval = 20.0, step = 0.1, group = gC)
glowBoost   = input.int(16, "Glow Strength", minval = 0, maxval = 40, group = gC)
 
gA = "═══ Alerts ═══"
proxPct     = input.float(0.10, "Proximity (% of price)", minval = 0.0, step = 0.01, group = gA)
dynAlerts   = input.bool(true, "Detailed Signal Alerts (alert())", group = gA, tooltip = "Fires a detailed message on every recovery signal when the alert is created with 'Any alert() function call'.")
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
clamp01(float x) => math.min(math.max(x, 0.0), 1.0)
mix(float a, float b, float t) => a + (b - a) * t
f_stars(float sc) => sc >= 8 ? "★★★★" : sc >= 6.5 ? "★★★" : sc >= 5 ? "★★" : sc >= 3 ? "★" : "·"
f_tier(float sc)  => sc >= 8 ? "ELITE" : sc >= 6.5 ? "STRONG" : sc >= 5 ? "MODERATE" : sc >= 3 ? "WEAK" : "FORMING"
f_sc(float v)     => str.tostring(v, "0.0")
f_pct(float v)    => str.tostring(math.round(v)) + "%"
f_px(float v)     => str.tostring(v, format.mintick)
f_vol(float v)    => str.tostring(v, format.volume)
f_si(int d)       => d == 1 ? 0 : 1
 
n        = bar_index
atrRaw   = math.max(nz(ta.atr(atrLen), ta.cum(high - low) / (n + 1)), syminfo.mintick)
vol0     = nz(volume)
volBase  = ta.sma(vol0, volLen)
volHi    = ta.highest(vol0, volHiLen)
pvWinVol = math.sum(vol0, 3)
pvRank   = ta.percentrank(pvWinVol, volHiLen)
rngBar   = high - low
buyV     = rngBar > 0 ? vol0 * (close - low) / rngBar : vol0 * 0.5
sellV    = vol0 - buyV
flowWin  = leftBars + rightBars + 1
winB     = nz(math.sum(buyV, flowWin))
winS     = nz(math.sum(sellV, flowWin))
depB     = nz(math.sum(buyV, rightBars))
depS     = nz(math.sum(sellV, rightBars))
winV     = nz(math.sum(vol0, flowWin))
vwLoSum  = nz(math.sum(vol0 * math.min(open, close), flowWin))
vwHiSum  = nz(math.sum(vol0 * math.max(open, close), flowWin))
smaLo    = ta.sma(math.min(open, close), flowWin)
smaHi    = ta.sma(math.max(open, close), flowWin)
bodyLoVW = winV > 0 ? vwLoSum / winV : smaLo
bodyHiVW = winV > 0 ? vwHiSum / winV : smaHi
pvHi     = nz(volHi[rightBars])
hasVol   = pvHi > 0
pvStr    = hasVol ? clamp01(nz(pvRank[math.max(rightBars - 1, 0)]) / 100.0) : 0.5
rsiV     = ta.rsi(close, rsiLen)
rsiLoW   = ta.lowest(rsiV, rsiWin)
rsiHiW   = ta.highest(rsiV, rsiWin)
ph       = ta.pivothigh(leftBars, rightBars)
pl       = ta.pivotlow(leftBars, rightBars)
inWindow = lookbackBars <= 0 or last_bar_index - n <= lookbackBars
supOn    = sideMode != "Supply Only"
resOn    = sideMode != "Demand Only"
rcMul    = reclaimDpt == "Near Border" ? 1.0 : reclaimDpt == "Midline" ? 0.5 : 0.0
volSurge = volBase > 0 ? vol0 / volBase : 1.0
viewRng  = math.max(nz(ta.highest(high, 150) - ta.lowest(low, 150), atrRaw * 10.0), atrRaw)
 
f_tone(int d) => d == 1 ? bullCol : bearCol
 
type Zone
    int    dir      = 1
    float  top      = na
    float  bot      = na
    int    born     = 0
    int    lastAct  = 0
    float  volStr   = 0.0
    float  depF     = 0.0
    float  dispAtr  = 0.0
    float  fB       = 0.0
    float  fS       = 0.0
    int    tests    = 0
    int    wins     = 0
    int    stalls   = 0
    int    swWins   = 0
    int    merges   = 0
    float  bncSum   = 0.0
    int    bncN     = 0
    int    phase    = 0
    bool   armed    = false
    int    tStart   = 0
    float  tExt     = na
    bool   swept    = false
    float  mfe      = 0.0
    bool   sigOn    = false
    float  sigSc    = 0.0
    label  sig      = na
    string sigTxt   = ""
    string sigTip   = ""
    float  score    = 0.0
    float  pTouch   = na
    float  pFirst   = na
    float  tMed     = na
    bool   breaker  = false
    bool   flipReq  = false
    float  brkDisp  = 0.0
    bool   eStart   = false
    bool   eSweep   = false
    bool   eSig     = false
    bool   eWin     = false
    bool   eBreak   = false
    box    bx       = na
    label  tag      = na
    bool   dead     = false
 
var array<Zone>  zones   = array.new<Zone>()
var array<label> sigLbls = array.new<label>()
var array<box>   hist    = array.new<box>()
var array<int>   sTests  = array.new_int(2, 0)
var array<int>   sWins   = array.new_int(2, 0)
var array<int>   gRes    = array.new_int(2, 0)
var array<int>   gWin    = array.new_int(2, 0)
var array<float> rets    = array.new_float()
 
method calcScore(Zone z) =>
    float dF   = (z.wins + 1.2) / (z.tests + 2.0)
    float sF   = math.min((z.swWins + z.merges) / sweepNorm, 1.0)
    float wSum = wVol + wDep + wDef + wSwp
    float raw  = wSum > 0 ? (wVol * z.volStr + wDep * z.depF + wDef * dF + wSwp * sF) / wSum : 0.0
    float idle = float(n - z.lastAct)
    float dec  = useDecay ? math.max(1.0 - (1.0 - decayFloor) * math.min(idle / decayBars, 1.0), decayFloor) : 1.0
    math.min(math.max(raw * 10.0 * dec, 0.0), 10.0)
 
method holdEst(Zone z) =>
    int   si    = f_si(z.dir)
    int   sT    = sTests.get(si)
    float sRate = sT > 0 ? sWins.get(si) / float(sT) : 0.5
    (z.wins + holdPrior * sRate) / (z.tests + holdPrior)
 
method kill(Zone z) =>
    box.delete(z.bx)
    label.delete(z.tag)
    z.dead := true
 
method retire(Zone z) =>
    label.delete(z.tag)
    if showHist
        color tone = f_tone(z.dir)
        box.set_right(z.bx, n)
        box.set_bgcolor(z.bx, color.new(tone, histTransp))
        box.set_border_color(z.bx, color.new(tone, 65))
        box.set_border_style(z.bx, line.style_dotted)
        box.set_border_width(z.bx, 1)
        hist.push(z.bx)
        if hist.size() > maxHist
            box.delete(hist.shift())
    else
        box.delete(z.bx)
    z.dead := true
 
method recordBounce(Zone z) =>
    z.bncSum += z.mfe / atrRaw
    z.bncN   += 1
 
method resolveSig(Zone z, string tail, bool won) =>
    if z.sigOn
        int si = f_si(z.dir)
        gRes.set(si, gRes.get(si) + 1)
        if won
            gWin.set(si, gWin.get(si) + 1)
        if not na(z.sig)
            label.set_text(z.sig, z.sigTxt + (won ? " ✔" : " ✘"))
            label.set_color(z.sig, won ? color.new(f_tone(z.dir), 5) : color.new(#787b86, 25))
            label.set_tooltip(z.sig, z.sigTip + "\nOutcome: " + tail)
        z.sigOn := false
 
f_sigScore(Zone z, float wickFr, float far) =>
    int   d   = z.dir
    float sD  = z.swept ? clamp01(((far - z.tExt) * d) / atrRaw / depthRef) : 0.0
    float sW  = clamp01(wickFr)
    float sV  = clamp01((volSurge - 1.0) / math.max(volRef - 1.0, 0.1))
    float sB  = clamp01(z.score / 10.0)
    float sDp = clamp01(((close - far) * d) / atrRaw / dispRef)
    float sSp = clamp01(1.0 - (n - z.tStart) / float(testWin))
    float wS  = twDepth + twWick + twVol + twBase + twDisp + twSpeed
    float raw = wS > 0 ? (twDepth * sD + twWick * sW + twVol * sV + twBase * sB + twDisp * sDp + twSpeed * sSp) / wS : 0.0
    math.min(math.max(raw * 10.0, 0.0), 10.0)
 
method fireSig(Zone z, float sc, bool isRecl) =>
    int   d    = z.dir
    float hold = z.holdEst()
    z.sigOn   := true
    z.sigSc   := sc
    z.eSig    := true
    z.lastAct := n
    string head = (d == 1 ? "▲ " : "▼ ") + (isRecl ? "SWEEP RECLAIM " : "REJECTION ") + f_sc(sc)
    string tip  = head + "\nHold estimate " + f_pct(hold * 100.0) + "\nZone " + f_sc(z.score) + "/10 · held " + str.tostring(z.wins) + "/" + str.tostring(z.tests) + "\nZone " + f_px(z.bot) + " – " + f_px(z.top) + "\nVolume " + str.tostring(volSurge, "0.0") + "x" + (isRecl ? " · grab " + str.tostring((z.dir == 1 ? z.bot - z.tExt : z.tExt - z.top) / atrRaw, "0.00") + " ATR" : "")
    z.sigTip := tip
    z.sigTxt := (d == 1 ? "▲ " : "▼ ") + (isRecl ? "SWEEP RECLAIM " : "REJECTION ") + f_sc(sc)
    if showSig
        label lb = label.new(n, d == 1 ? low : high, z.sigTxt, style = d == 1 ? label.style_label_up : label.style_label_down, color = color.new(f_tone(d), 10), textcolor = color.white, size = f_size(sigSize), textalign = text.align_center, tooltip = tip)
        z.sig := lb
        sigLbls.push(lb)
        if sigLbls.size() > maxSigs
            label.delete(sigLbls.shift())
    else
        z.sig := na
    if dynAlerts
        string msg = syminfo.ticker + " " + timeframe.period + " · Strong Recovery Zones · " + head + " @ " + f_px(close) + " · zone " + f_px(z.bot) + "–" + f_px(z.top) + " · hold est " + f_pct(hold * 100.0) + " · record " + str.tostring(z.wins) + "/" + str.tostring(z.tests)
        alert(msg, alert.freq_once_per_bar_close)
    true
 
method step(Zone z) =>
    z.eStart := false
    z.eSweep := false
    z.eSig   := false
    z.eWin   := false
    z.eBreak := false
    int   d     = z.dir
    int   si    = f_si(d)
    float a     = atrRaw
    float near  = d == 1 ? z.top : z.bot
    float far   = d == 1 ? z.bot : z.top
    float probe = d == 1 ? low : high
    float fav   = d == 1 ? high : low
    if z.phase == 2
        z.mfe := math.max(z.mfe, (fav - near) * d)
        bool reentry = (near - probe) * d >= 0
        if reentry or n - z.lastAct >= testWin
            z.recordBounce()
            z.phase := 0
            z.armed := true
    if z.phase == 0
        if not z.armed and ((probe - near) * d > 0 or (far - close) * d > breakTol * a)
            z.armed := true
        if z.armed and (near - probe) * d >= 0
            z.phase   := 1
            z.tStart  := n
            z.tExt    := probe
            z.swept   := false
            z.mfe     := math.max((close - near) * d, 0.0)
            z.sigOn   := false
            z.eStart  := true
            z.lastAct := n
    if z.phase == 1
        z.tExt := d == 1 ? math.min(z.tExt, low) : math.max(z.tExt, high)
        if not z.eStart
            z.mfe := math.max(z.mfe, (fav - near) * d)
        if not z.swept and (far - probe) * d > sweepAtr * a
            z.swept  := true
            z.eSweep := true
        if (far - close) * d > breakTol * a
            z.tests   += 1
            sTests.set(si, sTests.get(si) + 1)
            z.recordBounce()
            z.resolveSig("✘ BROKEN", false)
            z.eBreak  := true
            z.lastAct := n
            z.brkDisp := (far - close) * d / a
            z.flipReq := flipBroken and not z.breaker
            z.retire()
        else
            if not z.sigOn and z.score >= sigZoneMin
                float rngB   = math.max(high - low, syminfo.mintick)
                float wickFr = d == 1 ? (math.min(open, close) - low) / rngB : (high - math.max(open, close)) / rngB
                float rcl    = far + d * rcMul * (z.top - z.bot)
                bool  isRecl = z.swept and (close - rcl) * d > 0
                bool  isRej  = not z.swept and (near - probe) * d >= 0 and (close - near) * d > 0 and wickFr >= wickMin
                bool  rsiOk  = not useRsi or (d == 1 ? rsiLoW <= rsiOs : rsiHiW >= rsiOb)
                if (isRecl or isRej) and rsiOk
                    float sc = f_sigScore(z, wickFr, far)
                    if sc >= sigMinScore
                        z.fireSig(sc, isRecl)
            if (close - near) * d >= recAtr * a
                z.tests   += 1
                z.wins    += 1
                if z.swept
                    z.swWins += 1
                sTests.set(si, sTests.get(si) + 1)
                sWins.set(si, sWins.get(si) + 1)
                z.resolveSig("✔ HELD +" + str.tostring(recAtr, "0.0") + " ATR", true)
                z.phase   := 2
                z.eWin    := true
                z.lastAct := n
            else if n - z.tStart >= testWin
                z.tests  += 1
                z.stalls += 1
                sTests.set(si, sTests.get(si) + 1)
                z.recordBounce()
                z.resolveSig("◦ STALLED", false)
                z.phase := 0
                z.armed := false
    true
 
method expire(Zone z) =>
    if z.phase == 1
        int si = f_si(z.dir)
        z.tests  += 1
        z.stalls += 1
        sTests.set(si, sTests.get(si) + 1)
        z.recordBounce()
        z.resolveSig("◦ EXPIRED", false)
    z.kill()
    true
 
f_countLT(array<float> arr, float x) =>
    int lo = 0
    int hi = arr.size()
    while lo < hi
        int m = int(math.floor((lo + hi) / 2.0))
        if arr.get(m) < x
            lo := m + 1
        else
            hi := m
    lo
 
f_countLE(array<float> arr, float x) =>
    int lo = 0
    int hi = arr.size()
    while lo < hi
        int m = int(math.floor((lo + hi) / 2.0))
        if arr.get(m) <= x
            lo := m + 1
        else
            hi := m
    lo
 
f_newZone(int d, float zt, float zb, int bornAt) =>
    Zone zn = Zone.new()
    zn.dir     := d
    zn.top     := zt
    zn.bot     := zb
    zn.born    := bornAt
    zn.lastAct := bornAt
    zn.armed   := false
    zn.bx      := box.new(bornAt, zt, n, zb, bgcolor = color.new(f_tone(d), 100), border_color = color.new(f_tone(d), 100), border_width = 1)
    zn
 
f_spawn(int d, float lvl) =>
    bool  made = false
    float a    = atrRaw
    float zt   = na
    float zb   = na
    if heightMode == "Normalized ATR"
        zt := lvl + heightAtr * a / 2.0
        zb := lvl - heightAtr * a / 2.0
    else
        float raw = d == 1 ? bodyLoVW - lvl : lvl - bodyHiVW
        float hgt = math.min(math.max(nz(raw, minHAtr * a), minHAtr * a), maxHAtr * a)
        zt := d == 1 ? lvl + hgt : lvl
        zb := d == 1 ? lvl : lvl - hgt
    bool  volOk = not hasVol or pvStr * 100.0 >= minVolStr
    float zMid  = (zt + zb) / 2.0
    int   hit   = -1
    float hitD  = na
    if zones.size() > 0
        for i = 0 to zones.size() - 1
            Zone z = zones.get(i)
            float dz = math.abs((z.top + z.bot) / 2.0 - zMid)
            if not z.dead and dz < mergeAtr * a and (na(hitD) or dz < hitD)
                hit  := i
                hitD := dz
    if volOk and hit >= 0
        Zone zm = zones.get(hit)
        if zm.dir == d
            zm.merges  += 1
            zm.lastAct := n
            zm.volStr  := math.max(zm.volStr, pvStr)
            zm.fB      += winB
            zm.fS      += winS
    if volOk and hit < 0
        float tot  = depB + depS
        float shr  = tot > 0 ? (d == 1 ? depB : depS) / tot : 0.5
        float disp = math.max(d == 1 ? (close - zt) / a : (zb - close) / a, 0.0)
        Zone zn = f_newZone(d, zt, zb, n - rightBars)
        zn.volStr  := pvStr
        zn.dispAtr := disp
        zn.depF    := 0.6 * clamp01(disp / 1.0) + 0.4 * clamp01(0.5 + (shr - 0.5) * 2.0)
        zn.fB      := winB
        zn.fS      := winS
        zones.push(zn)
        made := true
    made
 
f_flip(Zone o) =>
    float oMid = (o.top + o.bot) / 2.0
    int   hit  = -1
    float hitD = na
    if zones.size() > 0
        for i = 0 to zones.size() - 1
            Zone z = zones.get(i)
            float dz = math.abs((z.top + z.bot) / 2.0 - oMid)
            if not z.dead and dz < mergeAtr * atrRaw and (na(hitD) or dz < hitD)
                hit  := i
                hitD := dz
    if hit >= 0
        Zone zm = zones.get(hit)
        if zm.dir == -o.dir
            zm.merges  += 1
            zm.lastAct := n
    else
        Zone zn = f_newZone(-o.dir, o.top, o.bot, n)
        zn.breaker := true
        zn.volStr  := o.volStr
        zn.dispAtr := o.brkDisp
        zn.depF    := clamp01(o.brkDisp / 1.0)
        zn.fB      := o.fB
        zn.fS      := o.fS
        zones.push(zn)
    true
 
f_focus(int d) =>
    int   idx  = -1
    float best = na
    if zones.size() > 0
        for i = 0 to zones.size() - 1
            Zone z = zones.get(i)
            if not z.dead and z.dir == d and (z.score >= minScore or z.phase == 1)
                float dist = math.abs(close - (z.top + z.bot) / 2.0)
                if na(best) or dist < best
                    best := dist
                    idx  := i
    idx
 
f_label(Zone z, bool isF) =>
    int    d     = z.dir
    float  sc    = z.score
    float  hold  = z.holdEst()
    string kind  = (d == 1 ? "DEMAND" : "SUPPLY") + (z.breaker ? " ⟲" : "")
    string state = z.phase == 1 ? (z.swept ? "  ⚡ SWEPT" : "  ⚠ TESTING") : ""
    string rec   = z.tests > 0 ? "Held " + str.tostring(z.wins) + "/" + str.tostring(z.tests) : "Fresh"
    string conf  = z.merges > 0 ? "  ·  ×" + str.tostring(z.merges + 1) : ""
    string swp   = z.swWins > 0 ? "  ·  ⚡" + str.tostring(z.swWins) : ""
    string pT    = na(z.pTouch) ? "n/a" : f_pct(z.pTouch)
    string first = isF and not na(z.pFirst) ? "  ·  First " + f_pct(z.pFirst) + (na(z.tMed) ? "" : " ~" + str.tostring(z.tMed, "0") + "b") : ""
    string txt   = ""
    if labMode == "Compact"
        string nm = (z.breaker ? "BREAKER " : "") + (d == 1 ? "DEMAND" : "SUPPLY")
        string rc = z.tests > 0 ? "Held " + str.tostring(z.wins) + "/" + str.tostring(z.tests) : "Fresh"
        string ic = z.phase == 1 ? (z.swept ? " · SWEPT" : " · TESTING") : ""
        string f1 = isF and not na(z.pFirst) ? " · First " + f_pct(z.pFirst) : ""
        txt := f_stars(sc) + " " + f_sc(sc) + " " + nm + " · " + rc + " · Touch " + pT + " · Hold " + f_pct(hold * 100.0) + f1 + ic
    else
        string l1 = f_stars(sc) + " " + f_sc(sc) + " " + kind + "  ·  " + rec + conf + swp + state
        string l2 = "Touch " + pT + "  ·  Hold " + f_pct(hold * 100.0) + first
        txt := l1 + "\n" + l2
        if labMode == "Full"
            float  dl  = z.fB - z.fS
            float  tot = z.fB + z.fS
            string l3  = f_px(z.bot) + " – " + f_px(z.top) + "  ·  Vol rank " + f_pct(z.volStr * 100.0) + "  ·  Δ " + (tot > 0 ? (dl >= 0 ? "+" : "") + f_pct(100.0 * dl / tot) : "n/a") + "  ·  Edge " + (na(z.pTouch) ? "n/a" : f_pct(z.pTouch * hold)) + "  ·  React " + (z.bncN > 0 ? str.tostring(z.bncSum / z.bncN, "0.0") + " ATR" : "n/a")
            txt := txt + "\n" + l3
    txt
 
f_draw(Zone z, bool isF, float y, int xR) =>
    float distN = close > z.top ? close - z.top : close < z.bot ? z.bot - close : 0.0
    float glow  = glowOn ? clamp01(1.0 - distN / (glowRange * atrRaw)) : 0.0
    float baseT = mix(float(weakTransp), float(fillTransp), clamp01(z.score / 10.0))
    int   fT    = int(math.round(math.max(baseT - glowBoost * glow, 30.0)))
    color tone  = f_tone(z.dir)
    box.set_right(z.bx, xR)
    box.set_bgcolor(z.bx, color.new(tone, fT))
    box.set_border_color(z.bx, color.new(tone, showBord ? bordTransp : 100))
    box.set_border_style(z.bx, z.breaker ? line.style_dashed : line.style_solid)
    box.set_border_width(z.bx, isF ? 2 : 1)
    string tt = labMode != "Off" ? f_label(z, isF) : ""
    color  tc = color.new(tone, z.score >= strongThr or isF ? 0 : 20)
    if na(z.tag)
        z.tag := label.new(xR, y, tt, style = label.style_label_left, color = color.new(color.black, 100), textcolor = tc, size = f_size(labSize), textalign = text.align_left)
    else
        label.set_xy(z.tag, xR, y)
        label.set_text(z.tag, tt)
        label.set_textcolor(z.tag, tc)
    true
 
bool evNewB = false
bool evNewR = false
if supOn and not na(pl) and inWindow
    evNewB := f_spawn(1, pl)
if resOn and not na(ph) and inWindow
    evNewR := f_spawn(-1, ph)
 
bool evTest      = false
bool evSweep     = false
bool evSigB      = false
bool evSigR      = false
bool evSigStrong = false
bool evWinB      = false
bool evWinR      = false
bool evBreak     = false
array<Zone> pend = array.new<Zone>()
 
if zones.size() > 0
    for z in zones
        if not z.dead
            if n - z.born >= maxLife
                z.expire()
            else
                int dPre = z.dir
                z.step()
                if not z.dead
                    z.score := z.calcScore()
                if z.flipReq
                    pend.push(z)
                evTest      := evTest or z.eStart
                evSweep     := evSweep or z.eSweep
                evBreak     := evBreak or z.eBreak
                evSigB      := evSigB or (z.eSig and dPre == 1)
                evSigR      := evSigR or (z.eSig and dPre == -1)
                evSigStrong := evSigStrong or (z.eSig and z.sigSc >= sigStrong)
                evWinB      := evWinB or (z.eWin and dPre == 1)
                evWinR      := evWinR or (z.eWin and dPre == -1)
 
if zones.size() > 0
    for i = zones.size() - 1 to 0
        if zones.get(i).dead
            zones.remove(i)
 
if pend.size() > 0
    for o in pend
        f_flip(o)
 
if zones.size() > 0
    for z in zones
        if z.breaker and z.born == n
            z.score := z.calcScore()
 
while zones.size() > maxZones
    int   wi = 0
    float wk = na
    for i = 0 to zones.size() - 1
        Zone zc  = zones.get(i)
        float key = zc.score + (zc.phase == 1 ? 100.0 : 0.0)
        if na(wk) or key < wk
            wk := key
            wi := i
    zones.remove(wi).expire()
 
fB = f_focus(1)
fR = f_focus(-1)
 
float proxD      = close * proxPct / 100.0
bool  nearB      = false
bool  nearR      = false
bool  nearStrong = false
if fB >= 0
    Zone zb0 = zones.get(fB)
    nearB      := math.max(close - zb0.top, 0.0) <= proxD
    nearStrong := nearStrong or (nearB and zb0.score >= strongThr)
if fR >= 0
    Zone zr0 = zones.get(fR)
    nearR      := math.max(zr0.bot - close, 0.0) <= proxD
    nearStrong := nearStrong or (nearR and zr0.score >= strongThr)
 
lr = close[1] > 0 ? math.log(close / close[1]) : float(na)
if not na(lr)
    rets.push(lr)
    if rets.size() > mcSample
        rets.shift()
 
MC_WORK = 200000
mcN     = math.max(100, math.min(mcPaths, int(MC_WORK / mcHz)))
snapN   = math.min(mcHz, 15)
 
var array<float> pMin   = array.new_float(mcN, 0.0)
var array<float> pMax   = array.new_float(mcN, 0.0)
var array<int>   hitB   = array.new_int(mcN, -1)
var array<int>   hitR   = array.new_int(mcN, -1)
var array<int>   snapAt = array.new_int()
if snapAt.size() == 0
    for j = 1 to snapN
        snapAt.push(int(math.round(j * mcHz / float(snapN))))
 
f_ret(float mu, float sd, float meanR, int sz) =>
    float r = 0.0
    if mcModel == "Gaussian"
        float u1 = math.random(1e-10, 1.0, mcSeed)
        float u2 = math.random(0.0, 1.0, mcSeed)
        r := mu + sd * math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
    else
        int k = math.min(int(math.floor(math.random(0, sz, mcSeed))), sz - 1)
        r := rets.get(k) - meanR + mu
    r
 
f_batch(int b, int perB, float p0, float bT, float rB, matrix<float> st, float mu, float sd, float meanR, int sz) =>
    int first = b * perB
    int last  = math.min(mcN, first + perB) - 1
    if first <= last
        for pId = first to last
            float px   = p0
            float mn   = p0
            float mx   = p0
            int   hb   = not na(bT) and p0 <= bT ? 0 : -1
            int   hr   = not na(rB) and p0 >= rB ? 0 : -1
            int   sIdx = 0
            for s = 1 to mcHz
                px *= math.exp(f_ret(mu, sd, meanR, sz))
                mn := math.min(mn, px)
                mx := math.max(mx, px)
                if hb < 0 and not na(bT) and px <= bT
                    hb := s
                if hr < 0 and not na(rB) and px >= rB
                    hr := s
                if sIdx < snapN
                    if s == snapAt.get(sIdx)
                        st.set(sIdx, pId, px)
                        sIdx += 1
            pMin.set(pId, mn)
            pMax.set(pId, mx)
            hitB.set(pId, hb)
            hitR.set(pId, hr)
    true
 
var polyline coneFill = na
var polyline coneMed  = na
 
doRun = probOn and rets.size() >= 30 and (mcTick ? barstate.islast : (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed)))
 
if doRun
    float meanR = rets.avg()
    float sdR   = rets.stdev()
    float mu    = mcDrift ? meanR : 0.0
    int   sz    = rets.size()
    float bT    = fB >= 0 ? zones.get(fB).top : float(na)
    float rB    = fR >= 0 ? zones.get(fR).bot : float(na)
    matrix<float> st = matrix.new<float>(snapN, mcN, close)
    int perB = int(math.ceil(mcN / 10.0))
    f_batch(0, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(1, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(2, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(3, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(4, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(5, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(6, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(7, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(8, perB, close, bT, rB, st, mu, sdR, meanR, sz)
    f_batch(9, perB, close, bT, rB, st, mu, sdR, meanR, sz)
 
    int cB = 0
    int cR = 0
    array<int> tB = array.new_int()
    array<int> tR = array.new_int()
    for p = 0 to mcN - 1
        int hb = hitB.get(p)
        int hr = hitR.get(p)
        if hb >= 0
            tB.push(hb)
        if hr >= 0
            tR.push(hr)
        if hb >= 0 and (hr < 0 or hb < hr)
            cB += 1
        else if hr >= 0 and (hb < 0 or hr < hb)
            cR += 1
 
    array<float> sMin = pMin.copy()
    array<float> sMax = pMax.copy()
    sMin.sort(order.ascending)
    sMax.sort(order.ascending)
    if zones.size() > 0
        for z in zones
            z.pTouch := na
            z.pFirst := na
            z.tMed   := na
            if not z.dead
                if close >= z.bot and close <= z.top
                    z.pTouch := 100.0
                else
                    int cnt = z.top < close ? f_countLE(sMin, z.top) : mcN - f_countLT(sMax, z.bot)
                    z.pTouch := 100.0 * cnt / mcN
    if fB >= 0
        Zone zb1 = zones.get(fB)
        zb1.pFirst := 100.0 * cB / mcN
        zb1.tMed   := tB.size() > 0 ? float(tB.median()) : float(na)
    if fR >= 0
        Zone zr1 = zones.get(fR)
        zr1.pFirst := 100.0 * cR / mcN
        zr1.tMed   := tR.size() > 0 ? float(tR.median()) : float(na)
 
    if not na(coneFill)
        coneFill.delete()
    if not na(coneMed)
        coneMed.delete()
    if showCone
        array<chart.point> pts = array.new<chart.point>()
        array<chart.point> med = array.new<chart.point>()
        array<float>       his = array.new_float()
        pts.push(chart.point.from_index(n, close))
        med.push(chart.point.from_index(n, close))
        for j = 0 to snapN - 1
            array<float> row = st.row(j)
            his.push(row.percentile_linear_interpolation(coneHi))
            pts.push(chart.point.from_index(n + snapAt.get(j), row.percentile_linear_interpolation(coneLo)))
            med.push(chart.point.from_index(n + snapAt.get(j), row.percentile_linear_interpolation(50)))
        for j = snapN - 1 to 0
            pts.push(chart.point.from_index(n + snapAt.get(j), his.get(j)))
        coneFill := polyline.new(pts, curved = true, closed = true, line_color = color.new(coneCol, 80), fill_color = color.new(coneCol, 92), line_width = 1)
        coneMed  := polyline.new(med, curved = true, line_color = color.new(coneCol, 40), line_style = line.style_dashed, line_width = 1)
 
if barstate.islast and zones.size() > 0
    int   xR  = n + labOff
    float gap = viewRng * labGapPct / 100.0 * (labMode == "Full" ? 1.5 : labMode == "Compact" ? 0.6 : 1.0)
    array<int>   upI = array.new_int()
    array<float> upD = array.new_float()
    array<int>   dnI = array.new_int()
    array<float> dnD = array.new_float()
    for i = 0 to zones.size() - 1
        Zone z = zones.get(i)
        if not z.dead
            box.set_bgcolor(z.bx, color.new(f_tone(z.dir), 100))
            box.set_border_color(z.bx, color.new(f_tone(z.dir), 100))
            if not na(z.tag)
                label.set_text(z.tag, "")
            if z.score >= minScore or z.phase == 1
                float mid = (z.top + z.bot) / 2.0
                if mid >= close
                    upI.push(i)
                    upD.push(mid - close)
                else
                    dnI.push(i)
                    dnD.push(close - mid)
    array<int> upO    = upD.sort_indices(order.ascending)
    array<int> dnO    = dnD.sort_indices(order.ascending)
    int        upShow = showPerSide > 0 ? math.min(showPerSide, upO.size()) : upO.size()
    int        dnShow = showPerSide > 0 ? math.min(showPerSide, dnO.size()) : dnO.size()
    float      prevY  = na
    float      dnTop  = na
    if dnShow > 0
        for k = 0 to dnShow - 1
            int   zi  = dnI.get(dnO.get(k))
            Zone  zz  = zones.get(zi)
            float mid = (zz.top + zz.bot) / 2.0
            float y   = na(prevY) ? mid : math.min(mid, prevY - gap)
            prevY := y
            if k == 0
                dnTop := y
            f_draw(zz, zi == fB or zi == fR, y, xR)
    prevY := dnTop
    if upShow > 0
        for k = 0 to upShow - 1
            int   zi  = upI.get(upO.get(k))
            Zone  zz  = zones.get(zi)
            float mid = (zz.top + zz.bot) / 2.0
            float y   = na(prevY) ? mid : math.max(mid, prevY + gap)
            prevY := y
            f_draw(zz, zi == fB or zi == fR, y, xR)
 
plotshape(showHeld and evWinB, "Demand Hold Confirmed", shape.diamond, location.belowbar, color.new(bullCol, 0), size = size.tiny)
plotshape(showHeld and evWinR, "Supply Hold Confirmed", shape.diamond, location.abovebar, color.new(bearCol, 0), size = size.tiny)
 
alertcondition(evNewB or evNewR,  "New Recovery Zone",          "A new volume-qualified recovery zone formed.")
alertcondition(evTest,            "Zone Test",                  "Price entered a recovery zone.")
alertcondition(evSweep,           "Zone Sweep",                 "Price swept beyond a zone's far border. Watch for a reclaim.")
alertcondition(evSigB,            "Bullish Recovery Signal",    "Bullish sweep-reclaim or rejection at a demand zone.")
alertcondition(evSigR,            "Bearish Recovery Signal",    "Bearish sweep-reclaim or rejection at a supply zone.")
alertcondition(evSigB or evSigR,  "Any Recovery Signal",        "A recovery signal fired.")
alertcondition(evSigStrong,       "Strong Recovery Signal",     "A recovery signal scored at or above the strong threshold.")
alertcondition(evWinB,            "Demand Hold Confirmed",      "A demand zone test resolved as HELD.")
alertcondition(evWinR,            "Supply Hold Confirmed",      "A supply zone test resolved as HELD.")
alertcondition(evBreak,           "Zone Broken / Flipped",      "A zone was broken by a close beyond its far border.")
alertcondition(nearB,             "Approaching Demand Zone",    "Price is within proximity of the nearest demand zone.")
alertcondition(nearR,             "Approaching Supply Zone",    "Price is within proximity of the nearest supply zone.")
alertcondition(nearStrong,        "Approaching Strong Zone",    "Price is within proximity of a strong zone.")

← 返回列表