Spike Sonar [Deriv Boom/Crash]

Deriv · study · 498 行 · 点赞 28 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  SPIKE SONAR v3 — Deriv Boom & Crash indices (one script, auto-mirrors)
//
//   • N = average ticks between spikes. Each tick spikes with p = 1/N → the spike
//     clock is MEMORYLESS: "overdue" does not exist. We quantify risk, not timing.
//   • Between spikes: gradual drift opposite to the spike direction ("carry").
//   • Spikes are detected on a LOWER timeframe (default 1m) inside any chart
//     timeframe. All clocks are in real time / ticks. Tick interval is measured.
//   • No volume, no sessions, no gaps, no news (24/7) → none of that is used.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Spike Sonar [Deriv Boom/Crash]", shorttitle="SPIKE SONAR", overlay=true, max_lines_count=500, max_labels_count=500, max_polylines_count=100, max_boxes_count=50, max_bars_back=1000)
 
// ───────────────────────────── INPUTS ─────────────────────────────
gI = "① Instrument & detection"
dirMode  = input.string("Auto (from symbol name)", "Index type", options=["Auto (from symbol name)", "Boom", "Crash"], group=gI)
idxMode  = input.string("Auto (from symbol name)", "Average ticks between spikes (N)", options=["Auto (from symbol name)", "150", "300", "500", "600", "900", "1000", "Custom"], group=gI)
customN  = input.int(1000, "Custom / fallback N", minval=20, group=gI)
tickMode = input.string("Auto (measured)", "Seconds per tick", options=["Auto (measured)", "1", "2"], group=gI, tooltip="Auto = derived from how often spikes really occur (picks 1 s or 2 s). Set manually if you know your feed.")
ltfIn    = input.string("1", "Spike detection timeframe (minutes)", options=["1", "2", "5"], group=gI, tooltip="Spikes are detected on this lower timeframe inside the chart bars. If the chart is already ≤ 2× this value, chart bars are used directly.")
robLen   = input.int(300, "Robust noise window (detection bars)", minval=50, maxval=1000, group=gI)
spikeK   = input.float(3.5, "Spike threshold (robust σ of one detection bar)", minval=2.0, step=0.5, group=gI)
 
gS = "② Spike display & aftermath"
markMode    = input.string("Major only", "Spike markers in history", options=["All", "Major only", "Last only"], group=gS, tooltip="On coarse timeframes a large share of bars contain a spike. 'Major only' keeps the chart readable.")
majorMult   = input.float(1.3, "Major spike = × median spike size", minval=0.5, step=0.1, group=gS)
showSpikeBg = input.bool(false, "Highlight spike bars (column)", group=gS)
showGeom    = input.bool(true, "Last-spike geometry (base / top / carry line)", group=gS)
showRoll    = input.bool(true, "Carry-resumes marker (after major spikes)", group=gS)
rollMin     = input.float(10.0, "Carry-resumes window (minutes after spike)", minval=1.0, group=gS)
showBase    = input.bool(true, "Spike-immune baseline", group=gS)
eqLen       = input.int(60, "Baseline length (chart bars)", minval=10, group=gS)
 
gF = "③ Forward map & hold planner"
showMap    = input.bool(true, "Two-scenario map (carry vs spike)", group=gF)
mapN       = input.float(0.5, "Map horizon (× N ticks)", minval=0.05, maxval=3.0, step=0.05, group=gF, tooltip="0.5 = half an average spike cycle. Converted to bars automatically. Hidden when the chart timeframe is too coarse for it.")
holdMin    = input.float(5.0, "Planned holding time (minutes)", minval=0.5, step=0.5, group=gF)
riskBudget = input.float(20.0, "Spike-risk budget per trade (%)", minval=1.0, maxval=90.0, step=1.0, group=gF)
measMin    = input.float(15.0, "Measurement horizon (minutes)", minval=1.0, step=1.0, group=gF, tooltip="Tests theory vs history: how often did a spike really arrive within this time?")
showBiasLbl = input.bool(true, "Likeliest-path label next to last candle", group=gF)
 
gV = "④ Look"
theme    = input.string("Auto", "Theme", options=["Auto", "Ember", "Ice"], group=gV, tooltip="Auto: Boom = Ember (warm), Crash = Ice (cold).")
showWater = input.bool(true, "Instrument watermark", group=gV)
colorCandles = input.bool(true, "Theme-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(36, "Auto: panel footprint, % of chart width", minval=15, maxval=60, group=gV)
dashH    = input.int(42, "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
 
// ───────────────────────────── INSTRUMENT & THEME ─────────────────────────────
string nameU = str.upper(syminfo.ticker + " " + syminfo.description)
bool isBoom  = dirMode == "Boom" ? true : dirMode == "Crash" ? false : not str.contains(nameU, "CRASH")
int  dir     = isBoom ? 1 : -1                       // +1 spikes up (Boom) · -1 spikes down (Crash)
 
float nDet = str.contains(nameU, "1000") ? 1000.0 : str.contains(nameU, "900") ? 900.0 : str.contains(nameU, "600") ? 600.0 : str.contains(nameU, "500") ? 500.0 : str.contains(nameU, "300") ? 300.0 : str.contains(nameU, "150") ? 150.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)
 
bool  ember  = theme == "Ember" or (theme == "Auto" and isBoom)
color cUpC   = ember ? #FFD166 : #8EE3FF
color cDnC   = ember ? #C8643B : #4F6BED
color cSp    = ember ? #FF6B1A : #00B4FF
color cAcc   = ember ? #FFB86B : #A0C4FF
color cTxt   = ember ? #FFF1DC : #E4F1FF
color cPanel = ember ? #1A0E08 : #07121F
color cOK    = #67E39B
color cBad   = #FF6B6B
color cCarry = isBoom ? cDnC : cUpC
 
string carryArrow = isBoom ? "▼" : "▲"
string spikeArrow = isBoom ? "▲" : "▼"
 
// ───────────────────────────── HELPERS ─────────────────────────────
f_dur(float 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_sg(float x) => (x >= 0 ? "+" : "") + str.tostring(x, "0.00")
f_pct(float p) => str.tostring(p * 100, "0") + "%"
 
f_meter(float p) =>
    int n = int(math.round(p * 10))
    string s = ""
    for i = 0 to 9
        s := s + (i < n ? "█" : "░")
    s
 
// ───────────────────────────── TIME MODEL ─────────────────────────────
tfSec   = timeframe.in_seconds()
barSec  = (na(tfSec) or tfSec <= 0) ? 60.0 : float(tfSec)
ltfSec  = str.tonumber(ltfIn) * 60.0
bool useLtf = barSec >= 2.0 * ltfSec
baseSec = useLtf ? ltfSec : barSec               // resolution at which spikes are detected
 
// ───────────────────────────── DETECTION DATA ─────────────────────────────
array<float> cA = array.new<float>()
array<float> hA = array.new<float>()
array<float> lA = array.new<float>()
array<int>   tA = array.new<int>()
if useLtf
    cA := request.security_lower_tf(syminfo.tickerid, ltfIn, close)
    hA := request.security_lower_tf(syminfo.tickerid, ltfIn, high)
    lA := request.security_lower_tf(syminfo.tickerid, ltfIn, low)
    tA := request.security_lower_tf(syminfo.tickerid, ltfIn, time)
else
    cA.push(close)
    hA.push(high)
    lA.push(low)
    tA.push(time)
 
// robust noise stats of recent detection-bar moves (in the spike direction)
var array<float> win = array.new<float>()
float winMed = na
float winMad = na
if win.size() >= 30
    winMed := win.median()
    array<float> dv = array.new<float>()
    for i = 0 to win.size() - 1
        dv.push(math.abs(win.get(i) - winMed))
    winMad := dv.median()
float sigW = na(winMad) ? na : math.max(1.4826 * winMad, 0.0000001)
 
// ───────────────────────────── SPIKE BOOKKEEPING ─────────────────────────────
var int   lastSpT   = na          // time (ms) of the last spike
var int   lastSpBar = na          // chart bar that contained it
var int   lastMajBar = na         // chart bar of the last MAJOR spike
var float spOrigin  = na
var float spTop     = na
var float spClose   = na
var float lastZ     = na
var float prevC     = na
var int   nSpikes   = 0
var int   nLtf      = 0
var float sumSpike  = 0.0
var array<float> spSizes = array.new<float>()
 
float medPrior = spSizes.size() > 0 ? spSizes.median() : 0.0
 
int   spCnt = 0
float pc    = prevC
array<float> newRd = array.new<float>()
array<float> szNew = array.new<float>()
if cA.size() > 0
    for i = 0 to cA.size() - 1
        float cc = cA.get(i)
        if not na(cc)
            if not na(pc) and pc > 0 and cc > 0
                float rdi = dir * math.log(cc / pc)
                newRd.push(rdi)
                if not na(sigW) and (rdi - winMed) / sigW >= spikeK
                    spCnt += 1
                    float tpx = isBoom ? hA.get(i) : lA.get(i)
                    lastSpT   := tA.get(i)
                    lastSpBar := bar_index
                    spOrigin  := pc
                    spTop     := tpx
                    spClose   := cc
                    lastZ     := (rdi - winMed) / sigW
                    szNew.push(dir * math.log(tpx / pc))
            pc := cc
 
if barstate.isconfirmed
    prevC := pc
    if newRd.size() > 0
        for j = 0 to newRd.size() - 1
            win.push(newRd.get(j))
        while win.size() > robLen
            win.shift()
    nLtf    += newRd.size()
    nSpikes += spCnt
    if szNew.size() > 0
        for j = 0 to szNew.size() - 1
            float v = szNew.get(j)
            spSizes.push(v)
            sumSpike += v
        while spSizes.size() > 100
            spSizes.shift()
 
bool  spike  = spCnt > 0
float maxSz  = szNew.size() > 0 ? szNew.max() : na
bool  major  = spike and (spSizes.size() < 5 or nz(maxSz) >= majorMult * medPrior)
if major
    lastMajBar := bar_index
 
// ───────────────────────────── TICK CALIBRATION (measured from spike frequency) ─────────────────────────────
float pHatL  = nLtf > 0 ? nSpikes / float(nLtf) : 0.0
float lamL   = pHatL < 0.95 ? -math.log(1.0 - pHatL) : 3.0
bool  calReady = nSpikes >= 8 and nLtf > 200
float secPerSpike = (calReady and lamL > 0) ? baseSec / lamL : na
float tickImpl    = na(secPerSpike) ? na : secPerSpike / nIn
float tickAuto    = na(tickImpl) ? 1.0 : (math.abs(math.log(tickImpl / 1.0)) <= math.abs(math.log(tickImpl / 2.0)) ? 1.0 : 2.0)
bool  tickAutoMode = tickMode == "Auto (measured)"
float tickSec     = tickAutoMode ? tickAuto : str.tonumber(tickMode)
 
tpb    = barSec / tickSec                        // ticks per chart bar
tpBase = baseSec / tickSec                       // ticks per detection bar
pTick  = 1.0 / nIn                               // spike probability per tick
 
f_pT(float sec) => 1.0 - math.pow(1.0 - pTick, sec / tickSec)
 
// chart-bar scaled carry & noise (log-return per chart bar, price terms)
float scaleB  = barSec / baseSec
float carryR  = dir * nz(winMed) * scaleB
float sigN    = math.max(nz(sigW, 0.0000001) * math.sqrt(scaleB), 0.0000001)
float medSz   = spSizes.size() > 0 ? spSizes.median() : 0.0
float meanSp  = nSpikes > 0 ? sumSpike / nSpikes : 0.0
 
// ───────────────────────────── CLOCKS (time-based) ─────────────────────────────
int   nowTs      = barstate.isrealtime ? timenow : time_close
float ticksSince = na(lastSpT) ? na : math.max(0.0, (nowTs - lastSpT) / 1000.0 / tickSec)
float pQuiet     = na(ticksSince) ? na : math.pow(1.0 - pTick, ticksSince)
bool  recentSp   = not na(ticksSince) and ticksSince <= 2.5 * nIn
int   rollBars   = math.max(1, int(math.round(rollMin * 60.0 / barSec)))
int   barsSinceSp  = na(lastSpBar) ? 9999 : bar_index - lastSpBar
int   barsSinceMaj = na(lastMajBar) ? 9999 : bar_index - lastMajBar
 
float uSince = na(ticksSince) ? 99.0 : ticksSince / nIn
int   bkt    = uSince < 0.1 ? 0 : uSince < 0.5 ? 1 : uSince < 1.0 ? 2 : uSince < 2.0 ? 3 : 4
 
// aftermath geometry
float spSz    = (not na(spTop) and not na(spOrigin)) ? spTop - spOrigin : na
float retr    = (not na(spSz) and spSz != 0) ? (spTop - close) / spSz : na
float remLog  = not na(spOrigin) ? dir * math.log(close / spOrigin) : na
float etaSec  = (not na(remLog) and remLog > 0 and nz(winMed) < 0) ? remLog / (-winMed) * baseSec : na
 
// carry resumes: first bar closing back in the carry direction after a MAJOR spike
var bool rollDone = false
if major
    rollDone := false
bool rollover = false
if not major and not na(lastMajBar) and not rollDone and barsSinceMaj >= 1 and barsSinceMaj <= rollBars and dir * (close - open) < 0
    rollover := true
    rollDone := true
 
// ───────────────────────────── MEASURED vs THEORY ─────────────────────────────
int   measBars = math.max(1, int(math.round(measMin * 60.0 / barSec)))
var array<float> bTot = array.new<float>(5, 0.0)
var array<float> bSp  = array.new<float>(5, 0.0)
var array<float> bUp  = array.new<float>(5, 0.0)
float spikeF = spike ? 1.0 : 0.0
float spWin  = math.sum(spikeF, measBars)
 
if barstate.isconfirmed and bar_index > measBars + 50
    int bk = bkt[measBars]
    bTot.set(bk, bTot.get(bk) + 1.0)
    if spWin > 0
        bSp.set(bk, bSp.get(bk) + 1.0)
    if close > close[measBars]
        bUp.set(bk, bUp.get(bk) + 1.0)
 
int   curB   = bkt
float nB     = bTot.get(curB)
float spMeas = nB > 0 ? bSp.get(curB) / nB : na
float upMeas = nB > 0 ? bUp.get(curB) / nB : 0.5
float spTheo = f_pT(measBars * barSec)
float nEff   = math.max(1.0, nB / measBars)
float ciSp   = 1.96 * math.sqrt(math.max(spTheo * (1.0 - spTheo), 0.0001) / nEff)
bool  spMatch = nEff >= 10 and not na(spMeas) and math.abs(spMeas - spTheo) <= ciSp
 
// net edge of the generator in loaded history (chart-bar returns)
var float sumRd = 0.0
var float sumSq = 0.0
var int   nBarsAll = 0
float rdc = dir * math.log(close / close[1])
if barstate.isconfirmed and not na(rdc)
    sumRd += rdc
    sumSq += rdc * rdc
    nBarsAll += 1
float meanRd = nBarsAll > 0 ? sumRd / nBarsAll : 0.0
float varRd  = nBarsAll > 1 ? math.max(sumSq / nBarsAll - meanRd * meanRd, 0.0) : 0.0
float seRd   = nBarsAll > 1 ? math.sqrt(varRd / nBarsAll) : 1.0
float tEV    = seRd > 0 ? meanRd / seRd : 0.0
float ev1000 = dir * meanRd * (1000.0 / tpb)
 
// ───────────────────────────── PROBABILITIES / PLANNER ─────────────────────────────
float pM5  = f_pT(300.0)
float pM15 = f_pT(900.0)
float pM60 = f_pT(3600.0)
 
float mapRaw   = mapN * nIn * tickSec / barSec
int   mapBars  = int(math.min(200.0, math.max(3.0, math.round(mapRaw))))
float mapSecEff = mapBars * barSec
bool  coarse   = mapRaw < 4.0
float pSpMap   = f_pT(mapSecEff)
float pNoMap   = 1.0 - pSpMap
float pBarChart = f_pT(barSec)
bool  dense    = pBarChart > 0.25
 
float holdTicks    = holdMin * 60.0 / tickSec
float pHold        = 1.0 - math.pow(1.0 - pTick, holdTicks)
float maxHoldMin   = math.log(1.0 - riskBudget / 100.0) / math.log(1.0 - pTick) * tickSec / 60.0
float carryPerTick = math.abs(nz(winMed)) / tpBase
float expT         = (1.0 - math.pow(1.0 - pTick, holdTicks)) / pTick
float evHold       = carryPerTick * expT - pHold * meanSp
 
// ───────────────────────────── 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 ELEMENTS ─────────────────────────────
plot(showBase ? ta.median(close, eqLen) : na, "Spike-immune baseline", color=color.new(cAcc, 25), linewidth=2, style=plot.style_stepline)
 
color baseC = close >= open ? cUpC : cDnC
barcolor(colorCandles ? color.new(baseC, barsSinceMaj <= rollBars ? 0 : 15) : na)
bgcolor(showSpikeBg and spike ? color.new(cSp, 88) : na)
 
bool mark = spike and (markMode == "All" or (markMode == "Major only" and major))
plotshape(mark and isBoom, "Spike up", shape.triangleup, location.abovebar, color=cSp, size=size.tiny)
plotshape(mark and not isBoom, "Spike down", shape.triangledown, location.belowbar, color=cSp, size=size.tiny)
plotshape(showRoll and rollover and isBoom, "Carry resumes (down)", shape.circle, location.abovebar, color=color.new(cAcc, 10), size=size.tiny)
plotshape(showRoll and rollover and not isBoom, "Carry resumes (up)", shape.circle, location.belowbar, color=color.new(cAcc, 10), size=size.tiny)
 
alertcondition(spike, "Spike Sonar: SPIKE detected", "Spike Sonar: a spike just printed")
alertcondition(major, "Spike Sonar: MAJOR spike detected", "Spike Sonar: a major spike just printed")
alertcondition(rollover, "Spike Sonar: carry resumes", "Spike Sonar: first bar back in the carry direction after a major spike")
 
// ───────────────────────────── FORWARD MAP + GEOMETRY (last bar only) ─────────────────────────────
var array<polyline> pls    = array.new<polyline>()
var array<line>     dLines = array.new<line>()
var array<label>    dLbls  = array.new<label>()
var array<linefill> dFills = array.new<linefill>()
 
if barstate.islast
    while pls.size() > 0
        polyline.delete(pls.pop())
    while dFills.size() > 0
        linefill.delete(dFills.pop())
    while dLines.size() > 0
        line.delete(dLines.pop())
    while dLbls.size() > 0
        label.delete(dLbls.pop())
 
    // The one and only spike label: the latest spike
    if not na(lastSpBar) and not na(spTop) and not na(spOrigin)
        string ago = na(ticksSince) ? "" : "  ·  " + f_dur(ticksSince * tickSec) + " ago"
        dLbls.push(label.new(lastSpBar, spTop, "SPIKE " + spikeArrow + " " + str.tostring(math.abs(spTop / spOrigin - 1) * 100, "0.00") + "%" + ago, style=isBoom ? label.style_label_down : label.style_label_up, color=cSp, textcolor=color.black, size=size.small))
 
    // Last-spike geometry — only while the spike is recent
    if showGeom and recentSp and not na(lastSpBar)
        line lnT = line.new(lastSpBar, spTop, bar_index + 1, spTop, color=color.new(cSp, 20), style=line.style_dotted, width=1)
        line lnO = line.new(lastSpBar, spOrigin, bar_index + 1, spOrigin, color=color.new(cAcc, 15), style=line.style_dashed, width=1)
        dLines.push(lnT)
        dLines.push(lnO)
        dFills.push(linefill.new(lnT, lnO, color.new(cSp, 91)))
        string rt = na(retr) ? "" : "  " + str.tostring(retr * 100, "0") + "% retraced"
        dLbls.push(label.new(bar_index + 1, spOrigin, "◂ BASE" + rt, style=label.style_label_left, color=color.new(cPanel, 20), textcolor=cAcc, size=size.tiny))
 
    // Two-scenario map: carry fan (no spike) vs spike jump — only when the timeframe can resolve it
    if showMap and not coarse
        pts2 = array.new<chart.point>()
        pts1 = array.new<chart.point>()
        for k = 0 to mapBars
            float s = sigN * math.sqrt(k)
            float c = carryR * k
            pts2.push(chart.point.from_index(bar_index + k, close * math.exp(c + 2.0 * s)))
            pts1.push(chart.point.from_index(bar_index + k, close * math.exp(c + 1.0 * s)))
        for k = mapBars to 0
            float s = sigN * math.sqrt(k)
            float c = carryR * k
            pts2.push(chart.point.from_index(bar_index + k, close * math.exp(c - 2.0 * s)))
            pts1.push(chart.point.from_index(bar_index + k, close * math.exp(c - 1.0 * s)))
        pls.push(polyline.new(pts2, closed=true, line_color=color.new(cAcc, 65), fill_color=color.new(cAcc, 93), line_width=1))
        pls.push(polyline.new(pts1, closed=true, line_color=color.new(cAcc, 40), fill_color=color.new(cAcc, 85), line_width=1))
        float endC = close * math.exp(carryR * mapBars)
        dLines.push(line.new(bar_index, close, bar_index + mapBars, endC, color=cCarry, width=2))
        dLbls.push(label.new(bar_index + mapBars, endC, carryArrow + " CARRY  " + f_pct(pNoMap) + " no spike", style=label.style_label_left, color=color.new(cPanel, 100), textcolor=cCarry, size=size.small))
        if spSizes.size() > 0
            float endS = endC * math.exp(dir * medSz)
            dLines.push(line.new(bar_index + mapBars, endC, bar_index + mapBars, endS, color=cSp, style=line.style_dashed, width=2))
            dLbls.push(label.new(bar_index + mapBars, endS, spikeArrow + " SPIKE " + (isBoom ? "+" : "−") + str.tostring(medSz * 100, "0.00") + "%  " + f_pct(pSpMap) + " by then", style=label.style_label_left, color=color.new(cPanel, 100), textcolor=cSp, size=size.small))
 
    // Likeliest-path label next to the last candle
    if showBiasLbl
        bool carryLead = pNoMap >= 0.5
        string bl = carryArrow + " " + f_pct(pNoMap) + "   " + spikeArrow + " " + f_pct(pSpMap) + "  (" + f_dur(mapSecEff) + ")"
        dLbls.push(label.new(bar_index + 1, close, bl, style=label.style_label_left, color=color.new(cPanel, 25), textcolor=carryLead ? cCarry : cSp, size=size.small))
 
// ───────────────────────────── WATERMARK ─────────────────────────────
var table wm = table.new(position.middle_center, 1, 1)
if barstate.islast
    if showWater
        table.cell(wm, 0, 0, (isBoom ? "BOOM " : "CRASH ") + str.tostring(nIn, "0"), text_color=color.new(cSp, 90), 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, 13, border_width=1, border_color=color.new(cSp, 80))
var table tTR = table.new(position.top_right, 2, 13, border_width=1, border_color=color.new(cSp, 80))
var table tBL = table.new(position.bottom_left, 2, 13, border_width=1, border_color=color.new(cSp, 80))
var table tBR = table.new(position.bottom_right, 2, 13, border_width=1, border_color=color.new(cSp, 80))
 
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, 8))
    table.cell(t, 1, r0, v, text_color=vCol, text_size=txtSz, text_halign=text.align_right, bgcolor=color.new(cPanel, 8))
 
f_fill(table t) =>
    table.cell(t, 0, 0, (isBoom ? "▲▲ BOOM " : "▼▼ CRASH ") + str.tostring(nIn, "0") + (autoOK ? " (auto)" : "") + "  ·  SPIKE SONAR", text_color=cTxt, text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cSp, 55))
    table.merge_cells(t, 0, 0, 1, 0)
 
    string clk = na(ticksSince) ? "waiting for spike data…" : "≈ " + str.tostring(ticksSince, "0") + " ticks  (" + f_dur(ticksSince * tickSec) + ")"
    f_row(t, 1, "Spike clock", clk, cTxt)
 
    string qTxt = na(pQuiet) ? "—" : str.tostring(pQuiet * 100, "0.0") + "% of gaps are this long" + (pQuiet < 0.05 ? "  ⚠ drought" : "")
    f_row(t, 2, "Quiet streak", qTxt, (not na(pQuiet) and pQuiet < 0.05) ? cBad : color.new(cTxt, 15))
 
    f_row(t, 3, "P(spike) next 5 / 15 / 60 min", f_pct(pM5) + " / " + f_pct(pM15) + " / " + f_pct(pM60), cTxt)
 
    string mTxt = (na(spMeas) or nEff < 3) ? "collecting history…" : "spike " + f_pct(spMeas) + " vs " + f_pct(spTheo) + " theory · ▲" + f_pct(upMeas) + (spMatch ? "  ✓ memoryless" : "  ≈")
    f_row(t, 4, "Measured · next " + f_dur(measBars * barSec), mTxt, spMatch ? cOK : color.new(cTxt, 30))
 
    string lsTxt = na(lastSpT) ? "none yet" : spikeArrow + " " + str.tostring(math.abs(spTop / spOrigin - 1) * 100, "0.00") + "% · " + str.tostring(lastZ, "0.0") + "σ · " + (recentSp ? (na(retr) ? "—" : str.tostring(retr * 100, "0") + "% retraced") : f_dur(ticksSince * tickSec) + " ago")
    f_row(t, 5, "Last spike", lsTxt, cSp)
 
    string eta = na(etaSec) ? "" : "  · base in ≈ " + f_dur(etaSec)
    f_row(t, 6, "Carry (no spike)", carryArrow + " " + str.tostring(math.abs(carryR) / tpb * 1000.0 * 100, "0.00") + "% per 1000 ticks" + eta, cCarry)
 
    bool carryLeads = pNoMap >= 0.5
    f_row(t, 7, "Likeliest path · " + f_dur(mapSecEff), carryArrow + " carry " + f_pct(pNoMap) + " " + f_meter(pNoMap) + " " + f_pct(pSpMap) + " " + spikeArrow + " spike", carryLeads ? cCarry : cSp)
 
    f_row(t, 8, "Net edge in history", f_sg(ev1000 * 100) + "% / 1000t · t=" + f_sg(tEV) + (math.abs(tEV) < 2.0 ? "  ≈ fair game" : "  ⚠ drift?"), math.abs(tEV) < 2.0 ? color.new(cTxt, 15) : cBad)
    f_row(t, 9, "Hold " + str.tostring(holdMin, "0.0") + " min", "spike risk " + f_pct(pHold) + " · max " + f_dur(maxHoldMin * 60.0) + " @" + str.tostring(riskBudget, "0") + "%", pHold <= riskBudget / 100.0 ? cOK : cBad)
    f_row(t, 10, "Carry-side EV (model)", f_sg(evHold * 100) + "% per hold  (vs spike " + str.tostring(meanSp * 100, "0.00") + "%)", evHold > 0 ? cOK : cBad)
 
    bool calOk = calReady and (tickAutoMode or (not na(tickImpl) and math.abs(tickImpl / tickSec - 1.0) < 0.3))
    string cal = not calReady ? "collecting… (" + str.tostring(nSpikes) + " spikes)" : tickAutoMode ? "✓ 1 spike / " + f_dur(secPerSpike) + " → tick ≈ " + str.tostring(tickSec, "0") + " s (auto)" : calOk ? "✓ 1 spike / " + f_dur(secPerSpike) : "⚠ 1 spike / " + f_dur(secPerSpike) + " → set tick ≈ " + str.tostring(tickImpl, "0.0") + " s"
    f_row(t, 11, "Calibration", cal, (not calReady) ? color.new(cTxt, 40) : calOk ? cOK : cBad)
 
    if dense
        f_row(t, 12, "Timeframe", "⚠ " + f_pct(pBarChart) + " of bars hold a spike · map needs ≤ 5m", cBad)
    else if coarse
        f_row(t, 12, "Timeframe", "⚠ too coarse for the map → use ≤ 5m", cBad)
    else
        f_row(t, 12, "Detection", (useLtf ? ltfIn + "m inside " + timeframe.period : "chart bars") + "  ·  'overdue' is a myth", color.new(cTxt, 50))
 
f_show(table t, bool on) =>
    if on
        f_fill(t)
    else
        table.clear(t, 0, 0, 1, 12)
 
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 inL = i < wN
                bool inR = i >= nV - wN
                if hh >= topLim
                    if inL
                        cTL += 1
                    if inR
                        cTR += 1
                if ll <= botLim
                    if inL
                        cBL += 1
                    if inR
                        cBR += 1
            int pen = (showMap and not coarse) ? int(wN * 0.5) : 0     // the forward map lives on the right
            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")

← 返回列表