Range Sonar [Deriv Range Break]

Deriv · study · 600 行 · 点赞 50 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  RANGE SONAR v2 — Deriv Range Break Indices (Range Break 100 / 200)
//
//   • Price lives in a corridor between a CEILING and a FLOOR and bounces off
//     them. On each border hit there is a small fixed chance (1/N, N = 100 or
//     200) that the border breaks and a NEW range is created. Memoryless:
//     a break is never "due", and its direction is 50/50.
//   • Inside a range the price is a driftless diffusion between two reflecting
//     borders → next-border odds follow gambler's ruin: P(ceiling first) is
//     simply (price − floor) / (ceiling − floor).
//   • Ranges are found by searching the most recent stretch of swings that
//     cluster at two borders (stale swings cannot poison a new range). A break
//     needs several closes beyond a border; moves that return are fake-outs.
//   • Deriv counts border HITS inside its generator; a chart shows VISITS. The
//     script measures the real break chance per visit from history (Auto).
//   • No volume, no sessions, no gaps in time, no news (24/7) → none is used.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Range Sonar [Deriv Range Break]", shorttitle="RANGE SONAR", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=100, max_bars_back=1000)
 
// ───────────────────────────── INPUTS ─────────────────────────────
gI = "① Instrument"
idxMode = input.string("Auto (from symbol name)", "Range Break index (N hits per break)", options=["Auto (from symbol name)", "100", "200", "Custom"], group=gI)
customN = input.int(100, "Custom / fallback N", minval=10, group=gI)
rateSrc = input.string("Auto", "Break-chance source", options=["Auto", "Spec", "Measured"], group=gI, tooltip="Spec = 1/N per border hit. A chart shows border VISITS, which can contain several hits, so the real chance per visit can differ. Auto = use the measured chance per visit once at least 5 breaks were observed.")
robLen  = input.int(300, "Robust noise window (bars)", minval=50, maxval=1000, group=gI)
 
gB = "② Range detection"
pvLen      = input.int(3, "Swing strength (bars each side)", minval=2, maxval=20, group=gB)
tolWpct    = input.float(8.0, "Border tolerance (% of range width)", minval=1.0, maxval=25.0, step=1.0, group=gB, tooltip="How close a swing must be to a border to count as a touch. Raise it if ranges never lock.")
tolSig     = input.float(0.15, "Tolerance floor (σ of one bar)", minval=0.0, maxval=2.0, step=0.05, group=gB)
minT       = input.int(3, "Touches per border to lock a range", minval=2, maxval=6, group=gB, tooltip="Higher = fewer but more convincing ranges. 2 locks too easily on a random walk.")
minW       = input.float(3.0, "Min range width (σ of one bar)", minval=0.5, step=0.5, group=gB)
maxW       = input.float(150.0, "Max range width (σ of one bar)", minval=10.0, step=10.0, group=gB)
brkK       = input.float(1.0, "Break: close beyond border by (σ of one bar)", minval=0.0, maxval=3.0, step=0.1, group=gB)
brkConfirm = input.int(3, "Break must hold for (consecutive closes)", minval=1, maxval=10, group=gB, tooltip="A move beyond a border that returns inside before this many closes is logged as a fake-out, not a break.")
 
gD = "③ Display"
showHist    = input.bool(true, "Keep past ranges on the chart", group=gD)
maxRanges   = input.int(25, "Past ranges kept", minval=2, maxval=45, group=gD)
showConn    = input.bool(true, "Connectors between ranges (level shift)", group=gD)
showHits    = input.bool(true, "Border-visit dots", group=gD)
showTraps   = input.bool(true, "Fake-out markers", group=gD)
showLadder  = input.bool(true, "Odds ladder on the live range", group=gD)
showArrows  = input.bool(true, "Next-border arrows", group=gD)
showProv    = input.bool(true, "Provisional corridor while searching", group=gD)
provBars    = input.int(60, "Provisional corridor window (bars)", minval=20, maxval=200, group=gD)
ext         = input.int(12, "Right extension (bars)", minval=4, maxval=40, group=gD, tooltip="Keep a few bars of empty space on the right of the chart.")
zoneFracPct = input.float(15.0, "Border zone (% of range width)", minval=5.0, maxval=40.0, step=1.0, group=gD)
 
gF = "④ Hold planner"
holdMin = input.float(10.0, "Planned holding time (minutes)", minval=0.5, step=0.5, group=gF)
 
gV = "⑤ Look (Blueprint theme)"
cCandUp = input.color(#E4DBFF, "Up candles", group=gV)
cCandDn = input.color(#7A5FD0, "Down candles / range fill", group=gV)
cCeil   = input.color(#FF7A8A, "Ceiling colour", group=gV)
cFloor  = input.color(#62B6FF, "Floor colour", group=gV)
cMid    = input.color(#C9BFE8, "Mid-line colour", group=gV)
cBrk    = input.color(#FFE45C, "Break / connector colour", group=gV)
cTxt    = input.color(#F1ECFF, "Text colour", group=gV)
cPanel  = input.color(#0D0A1A, "Panel colour", group=gV)
showWater = input.bool(true, "Instrument watermark", group=gV)
colorCandles = input.bool(true, "Blueprint-coloured candles", group=gV)
showDash = input.bool(true, "Dashboard", group=gV)
dashPos  = input.string("Auto", "Dashboard position", options=["Auto", "Top left", "Top right", "Bottom left", "Bottom right"], group=gV)
autoTL   = input.bool(false, "Auto may use top-left", group=gV, tooltip="Off by default: the broker's BUY/SELL panel sits top-left.")
dashW    = input.int(38, "Auto: panel footprint, % of chart width", minval=15, maxval=60, group=gV)
dashH    = input.int(46, "Auto: panel footprint, % of chart height", minval=15, maxval=60, group=gV)
dashSize = input.string("Small", "Dashboard text size", options=["Tiny", "Small", "Normal"], group=gV)
 
txtSz = dashSize == "Tiny" ? size.tiny : dashSize == "Normal" ? size.normal : size.small
tolW  = tolWpct / 100.0
zoneFrac = zoneFracPct / 100.0
color cOK   = #67E39B
color cBad  = #FFB454
color cNone = color.new(color.black, 100)
 
// ───────────────────────────── INSTRUMENT ─────────────────────────────
string nameU = str.upper(syminfo.ticker + " " + syminfo.description)
float nDet  = str.contains(nameU, "200") ? 200.0 : str.contains(nameU, "100") ? 100.0 : na
float nIn   = idxMode == "Auto (from symbol name)" ? nz(nDet, float(customN)) : idxMode == "Custom" ? float(customN) : str.tonumber(idxMode)
bool  autoOK = idxMode == "Auto (from symbol name)" and not na(nDet)
 
tfSec  = timeframe.in_seconds()
barSec = (na(tfSec) or tfSec <= 0) ? 60.0 : float(tfSec)
 
// ───────────────────────────── HELPERS ─────────────────────────────
f_dur(float sec) =>
    na(sec) ? "—" : sec < 90 ? str.tostring(sec, "0") + " s" : sec < 5400 ? str.tostring(sec / 60.0, "0.0") + " min" : sec < 172800 ? str.tostring(sec / 3600.0, "0.0") + " h" : str.tostring(sec / 86400.0, "0.0") + " d"
 
f_pct(float p) => na(p) ? "—" : str.tostring(p * 100, "0") + "%"
 
f_meter(float p) =>
    int n = int(math.round(nz(p) * 10))
    string s = ""
    for i = 0 to 9
        s := s + (i < n ? "█" : "░")
    s
 
// ───────────────────────────── NOISE SCALE ─────────────────────────────
r      = math.log(close / close[1])
medR   = ta.median(r, robLen)
madR   = ta.median(math.abs(r - medR), robLen)
sigB   = math.max(1.4826 * nz(madR), 0.0000001)        // robust σ of one bar (log)
sigPx  = close * sigB                                    // … in price units
 
// ───────────────────────────── RANGE STATE ─────────────────────────────
var int   rStart = 0                 // where the current search started (after the last break)
var int   rVis   = 0                 // first swing of the locked range (left edge of its box)
var array<float> pHP = array.new<float>()
var array<int>   pHI = array.new<int>()
var array<float> pLP = array.new<float>()
var array<int>   pLI = array.new<int>()
var bool  est  = false
var float U    = na
var float L    = na
var int   hitsU = 0
var int   hitsL = 0
var int   tuF   = 0
var int   tlF   = 0
var bool  wasInU = false
var bool  wasInL = false
var int   cntU = 0
var int   cntL = 0
var int   fbU  = 0
var int   fbL  = 0
var float prevMid = na
var int   prevEnd = 0
var float provHi = na
var float provLo = na
 
var int   nBreaks = 0
var int   nBrkUp  = 0
var int   nBrkDn  = 0
var int   nVisDone = 0
var int   nVisAll  = 0
var int   nTraps   = 0
var float timeDone = 0.0
var array<float> wA = array.new<float>()
 
// drawing bundles for past + current ranges
var array<box>   rBox = array.new<box>()
var array<line>  rCl  = array.new<line>()
var array<line>  rFl  = array.new<line>()
var array<line>  cLn  = array.new<line>()
var array<label> cLb  = array.new<label>()
 
if barstate.isfirst
    rStart := bar_index
    rVis   := bar_index
 
ph = ta.pivothigh(high, pvLen, pvLen)
pl = ta.pivotlow(low, pvLen, pvLen)
 
// Does a locked range exist if we only use swings from bar t0 onward?
f_try(int t0) =>
    float Uc = na
    float Lc = na
    if pHP.size() > 0
        for i = 0 to pHP.size() - 1
            if pHI.get(i) >= t0
                Uc := na(Uc) ? pHP.get(i) : math.max(Uc, pHP.get(i))
    if pLP.size() > 0
        for i = 0 to pLP.size() - 1
            if pLI.get(i) >= t0
                Lc := na(Lc) ? pLP.get(i) : math.min(Lc, pLP.get(i))
    bool ok = false
    int tu = 0
    int tlc = 0
    if not na(Uc) and not na(Lc)
        float wC = Uc - Lc
        float tC = math.max(math.max(syminfo.mintick * 2.0, tolW * wC), tolSig * sigPx)
        for i = 0 to pHP.size() - 1
            if pHI.get(i) >= t0 and pHP.get(i) >= Uc - tC
                tu += 1
        for i = 0 to pLP.size() - 1
            if pLI.get(i) >= t0 and pLP.get(i) <= Lc + tC
                tlc += 1
        ok := wC > 0 and tu >= minT and tlc >= minT and wC >= minW * sigPx and wC <= maxW * sigPx
    [ok, Uc, Lc, tu, tlc]
 
bool visU   = false
bool visL   = false
bool trapU  = false
bool trapL  = false
bool brkUpC = false
bool brkDnC = false
bool lockedNow = false
 
float tolNow = est ? math.max(math.max(syminfo.mintick * 2.0, tolW * (U - L)), tolSig * sigPx) : na
 
if barstate.isconfirmed
    if est
        // ── visits to the borders ──
        bool inU = high >= U - tolNow
        bool inL = low <= L + tolNow
        if inU and not wasInU
            hitsU += 1
            nVisAll += 1
            visU := true
        if inL and not wasInL
            hitsL += 1
            nVisAll += 1
            visL := true
        wasInU := inU
        wasInL := inL
 
        // ── breaks must hold for several closes; otherwise they are fake-outs ──
        bool beyondU = close > U + brkK * sigPx
        bool beyondL = close < L - brkK * sigPx
        if beyondU
            if cntU == 0
                fbU := bar_index
            cntU += 1
        else
            if cntU > 0 and cntU < brkConfirm
                trapU := true
                nTraps += 1
            cntU := 0
        if beyondL
            if cntL == 0
                fbL := bar_index
            cntL += 1
        else
            if cntL > 0 and cntL < brkConfirm
                trapL := true
                nTraps += 1
            cntL := 0
        brkUpC := cntU >= brkConfirm
        brkDnC := cntL >= brkConfirm
 
        if brkUpC or brkDnC
            int   endX   = brkUpC ? fbU : fbL
            int   back   = math.min(bar_index - rVis, 900)
            float durSec = math.max(0.0, (time_close - time[back]) / 1000.0)
            nBreaks += 1
            if brkUpC
                nBrkUp += 1
            else
                nBrkDn += 1
            nVisDone += hitsU + hitsL
            timeDone += durSec
            wA.push(math.log(U / L) / sigB)
            // finalise the drawing of the finished range
            if rBox.size() > 0
                box bF = rBox.last()
                box.set_left(bF, math.max(rVis, bar_index - 480))
                box.set_right(bF, endX)
                box.set_bgcolor(bF, color.new(cCandDn, 95))
                box.set_text(bF, "#" + str.tostring(nBreaks) + " · " + str.tostring(hitsU + hitsL) + " visits · " + f_dur(durSec) + (brkUpC ? " → ▲" : " → ▼"))
                box.set_text_color(bF, color.new(cTxt, 45))
                line.set_x1(rCl.last(), math.max(rVis, bar_index - 480))
                line.set_x2(rCl.last(), endX)
                line.set_color(rCl.last(), color.new(cCeil, 55))
                line.set_width(rCl.last(), 1)
                line.set_x1(rFl.last(), math.max(rVis, bar_index - 480))
                line.set_x2(rFl.last(), endX)
                line.set_color(rFl.last(), color.new(cFloor, 55))
                line.set_width(rFl.last(), 1)
            prevMid := (U + L) / 2.0
            prevEnd := endX
            // a NEW search begins right after the break started
            est := false
            U := na
            L := na
            hitsU := 0
            hitsL := 0
            tuF := 0
            tlF := 0
            pHP.clear()
            pHI.clear()
            pLP.clear()
            pLI.clear()
            rStart := endX
            cntU := 0
            cntL := 0
            wasInU := false
            wasInL := false
            if not showHist
                while rBox.size() > 1
                    box.delete(rBox.shift())
                    line.delete(rCl.shift())
                    line.delete(rFl.shift())
        else if rBox.size() > 0
            box bA = rBox.last()
            box.set_left(bA, math.max(rVis, bar_index - 480))
            box.set_right(bA, bar_index + 1)
            box.set_text(bA, "#" + str.tostring(nBreaks + 1) + " · " + str.tostring(hitsU + hitsL) + " visits")
            line.set_x1(rCl.last(), math.max(rVis, bar_index - 480))
            line.set_x2(rCl.last(), bar_index + 1)
            line.set_x1(rFl.last(), math.max(rVis, bar_index - 480))
            line.set_x2(rFl.last(), bar_index + 1)
    else
        // ── searching: collect swings after the last break, search for the best locked segment ──
        bool newPiv = false
        if not na(ph) and (bar_index - pvLen) > rStart
            pHP.push(ph)
            pHI.push(bar_index - pvLen)
            newPiv := true
            if pHP.size() > 24
                pHP.shift()
                pHI.shift()
        if not na(pl) and (bar_index - pvLen) > rStart
            pLP.push(pl)
            pLI.push(bar_index - pvLen)
            newPiv := true
            if pLP.size() > 24
                pLP.shift()
                pLI.shift()
        if newPiv and pHP.size() > 0 and pLP.size() > 0
            int   bestT = 999999999
            float bUv = na
            float bLv = na
            int   btu = 0
            int   btl = 0
            int   prog = -1
            for i = 0 to pHP.size() - 1
                int t0 = pHI.get(i)
                [ok1, u1, l1, a1, b1] = f_try(t0)
                if math.min(a1, b1) > prog
                    prog := math.min(a1, b1)
                    tuF := a1
                    tlF := b1
                if ok1
                    bestT := t0
                    bUv := u1
                    bLv := l1
                    btu := a1
                    btl := b1
                    break
            for i = 0 to pLP.size() - 1
                int t1 = pLI.get(i)
                if t1 >= bestT
                    break
                [ok2, u2, l2, a2, b2] = f_try(t1)
                if math.min(a2, b2) > prog
                    prog := math.min(a2, b2)
                    tuF := a2
                    tlF := b2
                if ok2
                    bestT := t1
                    bUv := u2
                    bLv := l2
                    btu := a2
                    btl := b2
                    break
            if bestT < 999999999
                est := true
                U := bUv
                L := bLv
                hitsU := btu
                hitsL := btl
                rVis := bestT
                nVisAll += btu + btl
                float tC2 = math.max(math.max(syminfo.mintick * 2.0, tolW * (bUv - bLv)), tolSig * sigPx)
                wasInU := high >= bUv - tC2
                wasInL := low <= bLv + tC2
                cntU := 0
                cntL := 0
                lockedNow := true
                int lx = math.max(bestT, bar_index - 480)
                box bx = box.new(lx, U, bar_index + 1, L, border_color=color.new(cCandDn, 40), border_width=1, bgcolor=color.new(cCandDn, 90), text="#" + str.tostring(nBreaks + 1), text_size=size.small, text_color=color.new(cTxt, 15), text_halign=text.align_left, text_valign=text.align_top)
                rBox.push(bx)
                rCl.push(line.new(lx, U, bar_index + 1, U, color=cCeil, width=2))
                rFl.push(line.new(lx, L, bar_index + 1, L, color=cFloor, width=2))
                if showConn and not na(prevMid)
                    float newMid = (U + L) / 2.0
                    float chgPct = (newMid / prevMid - 1.0) * 100.0
                    int   px0 = math.max(prevEnd, bar_index - 480)
                    cLn.push(line.new(px0, prevMid, lx, newMid, color=color.new(cBrk, 25), style=line.style_dotted, width=1))
                    cLb.push(label.new(int((px0 + lx) / 2), (prevMid + newMid) / 2.0, (chgPct >= 0 ? "▲ +" : "▼ ") + str.tostring(chgPct, "0.00") + "%", style=label.style_label_center, color=cNone, textcolor=cBrk, size=size.tiny))
                while rBox.size() > maxRanges
                    box.delete(rBox.shift())
                    line.delete(rCl.shift())
                    line.delete(rFl.shift())
                while cLn.size() > maxRanges
                    line.delete(cLn.shift())
                    label.delete(cLb.shift())
 
// ───────────────────────────── DERIVED STATS ─────────────────────────────
int   nowTs   = barstate.isrealtime ? timenow : time_close
int   backNow = math.min(math.max(bar_index - rVis, 0), 900)
float ageSec  = est ? math.max(0.0, (nowTs - time[backNow]) / 1000.0) : 0.0
int   visCur  = hitsU + hitsL
 
float hSpec   = 1.0 / nIn
float hMeas   = (nBreaks >= 5 and nVisDone > 0) ? nBreaks / float(nVisDone) : na
bool  useMeas = (rateSrc == "Measured" or rateSrc == "Auto") and not na(hMeas)
float hUse    = useMeas ? hMeas : hSpec
 
f_pBrk(float k) => 1.0 - math.pow(1.0 - hUse, k)
 
float pos     = est ? math.max(0.0, math.min(1.0, (close - L) / (U - L))) : na
float sigPS   = sigPx / math.sqrt(barSec)
float eT      = est ? math.max(close - L, 0.0) * math.max(U - close, 0.0) / (sigPS * sigPS) : na
float visGapSec = (nVisDone + visCur) >= 5 ? (timeDone + ageSec) / (nVisDone + visCur) : na
float pAlive  = math.pow(1.0 - hUse, visCur)
float lifeSec = na(visGapSec) ? na : visGapSec / hUse
float visHold = na(visGapSec) ? na : holdMin * 60.0 / visGapSec
float pHoldSurv = na(visHold) ? na : math.pow(1.0 - hUse, visHold)
float typW    = wA.size() > 0 ? wA.median() : na
float curWSig = est ? math.log(U / L) / sigB : na
float trapRate = nVisAll >= 10 ? nTraps / float(nVisAll) : na
bool  nearU   = est and pos >= 1.0 - zoneFrac
bool  nearL   = est and pos <= zoneFrac
 
// ───────────────────────────── VISIBLE-RANGE SCAN (auto layout) ─────────────────────────────
bool inView = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
var array<float> vH = array.new<float>()
var array<float> vL = array.new<float>()
var float rHi = na
var float rLo = na
if inView and barstate.isconfirmed
    vH.push(high)
    vL.push(low)
    rHi := na(rHi) ? high : math.max(rHi, high)
    rLo := na(rLo) ? low : math.min(rLo, low)
 
// ───────────────────────────── CHART MARKERS ─────────────────────────────
barcolor(colorCandles ? (close >= open ? cCandUp : cCandDn) : na)
 
plotshape(showHits and visU ? U : na, "Ceiling visit", shape.circle, location.absolute, color=cCeil, size=size.tiny)
plotshape(showHits and visL ? L : na, "Floor visit", shape.circle, location.absolute, color=cFloor, size=size.tiny)
plotshape(showTraps and trapU ? U : na, "Fake-out above ceiling", shape.xcross, location.absolute, color=cBrk, size=size.tiny)
plotshape(showTraps and trapL ? L : na, "Fake-out below floor", shape.xcross, location.absolute, color=cBrk, size=size.tiny)
plotshape(brkUpC, "Break up", shape.labeldown, location.abovebar, color=cBrk, textcolor=color.black, text="BREAK ▲", size=size.small, offset=-(brkConfirm - 1))
plotshape(brkDnC, "Break down", shape.labelup, location.belowbar, color=cBrk, textcolor=color.black, text="BREAK ▼", size=size.small, offset=-(brkConfirm - 1))
 
alertcondition(brkUpC, "Range Sonar: BREAK UP", "Range Sonar: the ceiling broke, a new range begins")
alertcondition(brkDnC, "Range Sonar: BREAK DOWN", "Range Sonar: the floor broke, a new range begins")
alertcondition(visU, "Range Sonar: ceiling visit", "Range Sonar: price is at the ceiling")
alertcondition(visL, "Range Sonar: floor visit", "Range Sonar: price is at the floor")
alertcondition(lockedNow, "Range Sonar: range locked", "Range Sonar: a new range has been confirmed")
 
// ───────────────────────────── LIVE RANGE DRAWING (last bar only) ─────────────────────────────
var array<line>  dLines = array.new<line>()
var array<label> dLbls  = array.new<label>()
var array<box>   dBoxes = array.new<box>()
 
if barstate.islast
    while dLines.size() > 0
        line.delete(dLines.pop())
    while dLbls.size() > 0
        label.delete(dLbls.pop())
    while dBoxes.size() > 0
        box.delete(dBoxes.pop())
 
    int xR = bar_index + ext
 
    if est
        int   xL  = math.max(rVis, bar_index - 450)
        float w   = U - L
        float mid = (U + L) / 2.0
        if showLadder
            for k = 0 to 5
                float topK = U - w * k / 6.0
                float botK = U - w * (k + 1) / 6.0
                float puK  = 1.0 - (k + 0.5) / 6.0           // P(next border = ceiling) for price inside this band
                color cb = color.from_gradient(puK, 0.0, 1.0, cFloor, cCeil)
                dBoxes.push(box.new(xL, topK, xR, botK, border_color=cNone, bgcolor=color.new(cb, 88)))
            dLbls.push(label.new(xR, L + w * 0.75, "▲ 75%", style=label.style_label_left, color=cNone, textcolor=color.new(cTxt, 25), size=size.tiny))
            dLbls.push(label.new(xR, L + w * 0.50, "◆ 50%", style=label.style_label_left, color=cNone, textcolor=color.new(cTxt, 25), size=size.tiny))
            dLbls.push(label.new(xR, L + w * 0.25, "▲ 25%", style=label.style_label_left, color=cNone, textcolor=color.new(cTxt, 25), size=size.tiny))
        dLines.push(line.new(xL, U, xR, U, color=cCeil, width=3))
        dLines.push(line.new(xL, L, xR, L, color=cFloor, width=3))
        dLines.push(line.new(xL, mid, xR, mid, color=color.new(cMid, 45), style=line.style_dashed, width=1))
        dLbls.push(label.new(xR, U, "CEILING " + str.tostring(U, format.mintick) + " · " + str.tostring(hitsU) + " visits", style=label.style_label_left, color=color.new(cPanel, 15), textcolor=cCeil, size=size.small))
        dLbls.push(label.new(xR, L, "FLOOR " + str.tostring(L, format.mintick) + " · " + str.tostring(hitsL) + " visits", style=label.style_label_left, color=color.new(cPanel, 15), textcolor=cFloor, size=size.small))
        if showArrows
            int xA = xR - 2
            dLines.push(line.new(bar_index, close, xA, U, color=color.new(cCeil, 35), style=line.style_dotted, width=2))
            dLines.push(line.new(bar_index, close, xA, L, color=color.new(cFloor, 35), style=line.style_dotted, width=2))
            dLbls.push(label.new(xA, (close + U) / 2.0, "▲ next " + f_pct(pos), style=label.style_label_right, color=color.new(cPanel, 20), textcolor=cCeil, size=size.small))
            dLbls.push(label.new(xA, (close + L) / 2.0, "▼ next " + f_pct(1.0 - pos), style=label.style_label_right, color=color.new(cPanel, 20), textcolor=cFloor, size=size.small))
    else
        // searching: show the best current guess as a dashed provisional corridor
        int nP = math.min(math.min(provBars, bar_index - rStart), 400)
        if nP >= 8
            float hV = high
            float lV = low
            for i = 0 to nP - 1
                hV := math.max(hV, high[i])
                lV := math.min(lV, low[i])
            provHi := hV
            provLo := lV
            if showProv
                dBoxes.push(box.new(bar_index - nP + 1, hV, xR, lV, border_color=color.new(cMid, 30), border_style=line.style_dashed, border_width=1, bgcolor=color.new(cMid, 94), text="PROVISIONAL · touches ▲" + str.tostring(tuF) + " ▼" + str.tostring(tlF) + " of " + str.tostring(minT), text_size=size.small, text_color=color.new(cMid, 10), text_halign=text.align_left, text_valign=text.align_top))
 
// ───────────────────────────── WATERMARK ─────────────────────────────
var table wm = table.new(position.middle_center, 1, 1)
if barstate.islast
    if showWater
        table.cell(wm, 0, 0, "RANGE " + str.tostring(nIn, "0"), text_color=color.new(cCandDn, 88), text_size=size.huge, bgcolor=color.new(color.black, 100))
    else
        table.clear(wm, 0, 0, 0, 0)
 
// ───────────────────────────── DASHBOARD (4 anchor tables, only one is filled) ─────────────────────────────
var table tTL = table.new(position.top_left, 2, 15, border_width=1, border_color=color.new(cCandDn, 70))
var table tTR = table.new(position.top_right, 2, 15, border_width=1, border_color=color.new(cCandDn, 70))
var table tBL = table.new(position.bottom_left, 2, 15, border_width=1, border_color=color.new(cCandDn, 70))
var table tBR = table.new(position.bottom_right, 2, 15, border_width=1, border_color=color.new(cCandDn, 70))
 
f_row(table t, int r0, string k, string v, color vCol) =>
    table.cell(t, 0, r0, k, text_color=color.new(cTxt, 30), text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cPanel, 6))
    table.cell(t, 1, r0, v, text_color=vCol, text_size=txtSz, text_halign=text.align_right, bgcolor=color.new(cPanel, 6))
 
f_fill(table t) =>
    table.cell(t, 0, 0, "▣ RANGE BREAK " + str.tostring(nIn, "0") + (autoOK ? " (auto)" : "") + "  ·  RANGE SONAR", text_color=cTxt, text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cCandDn, 45))
    table.merge_cells(t, 0, 0, 1, 0)
 
    string stTxt = est ? "LOCKED #" + str.tostring(nBreaks + 1) + " · " + f_dur(ageSec) + " · " + str.tostring(visCur) + " visits (▲" + str.tostring(hitsU) + " ▼" + str.tostring(hitsL) + ")" : "SEARCHING · touches ▲" + str.tostring(tuF) + " ▼" + str.tostring(tlF) + " of " + str.tostring(minT)
    f_row(t, 1, "Range", stTxt, est ? cTxt : cMid)
 
    string coTxt = est ? "floor " + str.tostring(L, format.mintick) + " · ceiling " + str.tostring(U, format.mintick) + " · " + str.tostring((U / L - 1) * 100, "0.00") + "% = " + str.tostring(curWSig, "0") + "σ" : (na(provHi) ? "—" : "provisional " + str.tostring(provLo, format.mintick) + " – " + str.tostring(provHi, format.mintick))
    f_row(t, 2, "Corridor", coTxt, est ? cTxt : color.new(cTxt, 45))
 
    f_row(t, 3, "Position in range", est ? "floor " + f_meter(pos) + " ceiling  " + str.tostring(pos * 100, "0") + "%" : "—", est ? (nearU ? cCeil : nearL ? cFloor : cTxt) : color.new(cTxt, 50))
 
    f_row(t, 4, "Next border (odds · ETA)", est ? "▲ ceiling " + f_pct(pos) + " · ▼ floor " + f_pct(1.0 - pos) + " · ≈ " + f_dur(eT) : "—", est ? cTxt : color.new(cTxt, 50))
 
    f_row(t, 5, "At a border", "bounce " + str.tostring((1.0 - hUse) * 100, "0.0") + "% · break " + str.tostring(hUse * 100, "0.0") + "%  (" + (useMeas ? "measured" : "spec") + ", per visit)", useMeas ? cBad : cTxt)
 
    f_row(t, 6, "Break risk next 10/50/100 visits", f_pct(f_pBrk(10.0)) + " / " + f_pct(f_pBrk(50.0)) + " / " + f_pct(f_pBrk(100.0)), cTxt)
 
    string alTxt = est ? "P(survived " + str.tostring(visCur) + " visits) = " + str.tostring(pAlive * 100, "0") + "%" + (pAlive < 0.1 ? "  · long-lived, still not 'due'" : "  · normal") : "—"
    f_row(t, 7, "Not-due check", alTxt, est ? cTxt : color.new(cTxt, 50))
 
    string cadTxt = na(visGapSec) ? "collecting…" : "1 visit / " + f_dur(visGapSec) + " · life left ≈ " + f_dur(lifeSec)
    f_row(t, 8, "Cadence · expected life", cadTxt, na(visGapSec) ? color.new(cTxt, 40) : cTxt)
 
    string likeTxt = not est ? "◇ no locked range yet · wait" : nearU ? "▼ SHORT zone · bounce " + str.tostring((1.0 - hUse) * 100, "0.0") + "%" : nearL ? "▲ LONG zone · bounce " + str.tostring((1.0 - hUse) * 100, "0.0") + "%" : "◆ MID-RANGE · next " + (pos >= 0.5 ? "▲ ceiling " + f_pct(pos) : "▼ floor " + f_pct(1.0 - pos))
    f_row(t, 9, "Likeliest", likeTxt, not est ? cMid : nearU ? cCeil : nearL ? cFloor : cTxt)
 
    f_row(t, 10, "Hold " + str.tostring(holdMin, "0") + " min", na(pHoldSurv) ? "collecting…" : "range survives " + f_pct(pHoldSurv) + " · break risk " + f_pct(1.0 - pHoldSurv), na(pHoldSurv) ? color.new(cTxt, 40) : pHoldSurv >= 0.8 ? cOK : cBad)
 
    string hiTxt = nBreaks < 3 ? "collecting… (" + str.tostring(nBreaks) + " breaks)" : str.tostring(nBreaks) + " breaks (▲" + str.tostring(nBrkUp) + " ▼" + str.tostring(nBrkDn) + ") · 1 per " + str.tostring(nVisDone / float(nBreaks), "0") + " visits · spec 1/" + str.tostring(nIn, "0") + " hits"
    f_row(t, 11, "History", hiTxt, nBreaks < 3 ? color.new(cTxt, 40) : cTxt)
 
    string bqTxt = na(trapRate) ? "collecting…" : (trapRate < 0.15 ? "✓ hard borders · " : "⚠ soft borders · ") + str.tostring(trapRate * 100, "0") + "% of visits end in a fake-out" + (trapRate < 0.15 ? "" : " → raise tolerance")
    f_row(t, 12, "Border quality", bqTxt, na(trapRate) ? color.new(cTxt, 40) : trapRate < 0.15 ? cOK : cBad)
 
    string noteTxt = barSec > 900 ? "⚠ chart TF too high · use ≤ 15m" : (na(typW) ? "typical width: —" : "typical width ≈ " + str.tostring(typW, "0") + "σ") + " · break dir 50/50"
    f_row(t, 13, "Notes", noteTxt, barSec > 900 ? cBad : color.new(cTxt, 50))
 
    table.cell(t, 0, 14, " ", text_size=size.small, bgcolor=cNone)
    table.cell(t, 1, 14, " ", text_size=size.small, bgcolor=cNone)
 
f_show(table t, bool on) =>
    if on
        f_fill(t)
    else
        table.clear(t, 0, 0, 1, 14)
 
if barstate.islast
    string chosen = dashPos
    if dashPos == "Auto"
        chosen := "Bottom left"
        int nV = array.size(vH)
        if nV >= 5 and not na(rHi) and not na(rLo) and rHi > rLo
            float rng    = rHi - rLo
            float topLim = rHi - rng * dashH / 100.0
            float botLim = rLo + rng * dashH / 100.0
            int wN = math.max(1, int(math.round(nV * dashW / 100.0)))
            int cTL = 0
            int cTR = 0
            int cBL = 0
            int cBR = 0
            for i = 0 to nV - 1
                float hh = vH.get(i)
                float ll = vL.get(i)
                bool inL2 = i < wN
                bool inR2 = i >= nV - wN
                if hh >= topLim
                    if inL2
                        cTL += 1
                    if inR2
                        cTR += 1
                if ll <= botLim
                    if inL2
                        cBL += 1
                    if inR2
                        cBR += 1
            int pen = int(wN * 0.5)            // the live range and its ruler extend into the right margin
            cTR += pen
            cBR += pen
            int best = cBL
            if cTR < best
                best := cTR
                chosen := "Top right"
            if cBR < best
                best := cBR
                chosen := "Bottom right"
            if autoTL and cTL < best
                best := cTL
                chosen := "Top left"
    f_show(tTL, showDash and chosen == "Top left")
    f_show(tTR, showDash and chosen == "Top right")
    f_show(tBL, showDash and chosen == "Bottom left")
    f_show(tBR, showDash and chosen == "Bottom right")

← 返回列表