Probability Staircase Trend Engine [PhenLabs]

PhenLabs · study · 539 行 · 点赞 600 · TradingView 原页

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

Pine Script

//@version=6
// Probability Staircase Trend Engine [PhenLabs]
// Every confirmed trend flip is tracked as a shadow trade. Its path-dependent maximum favorable
// excursion (in R, measured before the stop, the horizon, or the next flip) is written to an
// outcome ring buffer. The next flip reads the survival curve of similar past flips and places
// T1/T2/T3 at the furthest R-levels that were reached by at least 60/40/20% of them (Balanced
// ladder), each box ending at the median bar count it took to get there. A TAKE/SKIP verdict comes
// from the realized expectancy of the "exit at T1" plan on the same evidence pool.
// All-plan: closed-bar OHLC only. No lower-timeframe data, no lookahead, no repainting.
indicator("Probability Staircase Trend Engine [PhenLabs]", shorttitle = "PSTE [PhenLabs]", overlay = true, max_boxes_count = 40, max_labels_count = 40, max_lines_count = 20)
 
// ───────────────────────────── Enums ─────────────────────────────
enum Sensitivity
    fast     = "Fast"
    balanced = "Balanced"
    slow     = "Slow"
 
enum Ladder
    conservative = "Conservative (70 / 50 / 30%)"
    balanced     = "Balanced (60 / 40 / 20%)"
    aggressive   = "Aggressive (50 / 30 / 15%)"
 
enum TableSize
    tiny   = "Tiny"
    small  = "Small"
    normal = "Normal"
 
// ───────────────────────────── Inputs (13) ─────────────────────────────
const string G1 = "Trend Engine"
const string G2 = "Calibration"
const string G3 = "Visuals"
 
Sensitivity sensIn = input.enum(Sensitivity.balanced, "Trend Sensitivity", group = G1, tooltip = "Preset for the efficiency-adaptive baseline and its ATR trailing band. Fast = more flips, Slow = fewer, longer trends.")
int stopLen        = input.int(10, "Stop Swing Lookback", minval = 3, maxval = 50, group = G1, tooltip = "Bars used to find the structural swing extreme for the stop. Risk (1R) is clamped between 0.5 and 3 ATR.")
int horizon        = input.int(60, "Plan Horizon (bars)", minval = 10, maxval = 300, group = G1, tooltip = "A shadow trade that has not been stopped or reversed after this many bars is closed and recorded.")
int minN           = input.int(20, "Minimum Sample", minval = 8, maxval = 150, group = G2, tooltip = "Resolved flips required before a pool is trusted. Pools fall back: same direction + context, then same direction, then all flips.")
Ladder ladderIn    = input.enum(Ladder.balanced, "Target Ladder", group = G2, tooltip = "Reach probabilities used to place T1 / T2 / T3 on the survival curve.")
bool useCtx        = input.bool(true, "Split by Trend Efficiency", group = G2, tooltip = "Separate evidence for flips that happen in clean (efficient) vs choppy conditions.")
bool showPlan      = input.bool(true, "Show Probability Staircase", group = G3)
int keepPlans      = input.int(2, "Past Plans Kept", minval = 0, maxval = 5, group = G3, active = showPlan, tooltip = "Resolved plans stay on the chart, frozen at their exit bar, with a check mark on every target that was reached.")
bool showSkip      = input.bool(true, "Show SKIP Flips", group = G3, tooltip = "Grey markers for flips whose evidence says the T1 plan had negative expectancy.")
color bullCol      = input.color(#00A8C6, "Bull", inline = "col", group = G3)
color bearCol      = input.color(#F0457A, "Bear", inline = "col", group = G3)
bool showDash      = input.bool(true, "Show Dashboard", group = G3)
TableSize tblIn    = input.enum(TableSize.small, "Table Size", group = G3, active = showDash)
 
// ───────────────────────────── Constants ─────────────────────────────
const int   MAX_STORE = 300
const color NEUTRAL   = #8A93A6
const color CLEAR     = #00000000
const color DASH_BG   = #0F131C
const color DASH_TXT  = #D6DAE3
 
int   erLen   = sensIn == Sensitivity.fast ? 8 : sensIn == Sensitivity.slow ? 14 : 10
int   slowLen = sensIn == Sensitivity.fast ? 20 : sensIn == Sensitivity.slow ? 40 : 30
float bandK   = sensIn == Sensitivity.fast ? 1.0 : sensIn == Sensitivity.slow ? 2.0 : 1.5
 
float p1 = ladderIn == Ladder.conservative ? 0.70 : ladderIn == Ladder.aggressive ? 0.50 : 0.60
float p2 = ladderIn == Ladder.conservative ? 0.50 : ladderIn == Ladder.aggressive ? 0.30 : 0.40
float p3 = ladderIn == Ladder.conservative ? 0.30 : ladderIn == Ladder.aggressive ? 0.15 : 0.20
 
string tSz = tblIn == TableSize.tiny ? size.tiny : tblIn == TableSize.normal ? size.normal : size.small
 
// ───────────────────────────── Types ─────────────────────────────
// One resolved shadow trade. rN = bars from entry until grid level N was first reached (-1 = never).
type Outcome
    int   bucket
    int   dir
    float mfeR
    float exitR
    int   r0 = -1
    int   r1 = -1
    int   r2 = -1
    int   r3 = -1
    int   r4 = -1
    int   r5 = -1
    int   r6 = -1
    int   r7 = -1
 
// Drawing handles for one plan, so it can be frozen, faded, and pruned as a unit.
type Plan
    box   zStop
    box   z1
    box   z2
    box   z3
    label l1
    label l2
    label l3
    label lS
    line  ent
    int   g1 = -1
    int   g2 = -1
    int   g3 = -1
    color col
    bool  live = true
 
method reachAt(Outcome this, int g) =>
    int v = switch g
        0 => this.r0
        1 => this.r1
        2 => this.r2
        3 => this.r3
        4 => this.r4
        5 => this.r5
        6 => this.r6
        => this.r7
    v
 
// ───────────────────────────── Pure helpers ─────────────────────────────
f_inPool(Outcome o, int lvl, int bucket, int dirIdx) =>
    lvl == 0 ? o.bucket == bucket : lvl == 1 ? o.dir == dirIdx : true
 
// Survival curve, ladder targets and T1-plan expectancy from resolved outcomes only.
f_stats(array<Outcome> store, array<float> grid, int bucket, int dirIdx, int minCount, float q1, float q2, float q3) =>
    int nB = 0
    int nD = 0
    int nA = store.size()
    for o in store
        if o.bucket == bucket
            nB += 1
        if o.dir == dirIdx
            nD += 1
    int lvl = nB >= minCount ? 0 : nD >= minCount ? 1 : nA >= minCount ? 2 : 3
    int n   = lvl == 0 ? nB : lvl == 1 ? nD : nA
    int g1 = -1
    int g2 = -1
    int g3 = -1
    float s1 = na
    float s2 = na
    float s3 = na
    float edge = na
    if lvl < 3 and n > 0
        array<float> surv = array.new<float>(8, 0.0)
        for o in store
            if f_inPool(o, lvl, bucket, dirIdx)
                for g = 0 to 7
                    if o.mfeR >= grid.get(g)
                        surv.set(g, surv.get(g) + 1.0)
        for g = 0 to 7
            surv.set(g, surv.get(g) / n)
        for g = 0 to 7
            float sv = surv.get(g)
            if sv >= q1
                g1 := g
            if sv >= q2
                g2 := g
            if sv >= q3
                g3 := g
        if g2 == g1
            g2 := -1
        int prevG = g2 >= 0 ? g2 : g1
        if g3 == prevG
            g3 := -1
        s1 := g1 >= 0 ? surv.get(math.max(g1, 0)) : na
        s2 := g2 >= 0 ? surv.get(math.max(g2, 0)) : na
        s3 := g3 >= 0 ? surv.get(math.max(g3, 0)) : na
        // Realized expectancy of "take profit at T1 (or 0.5R if no T1), otherwise whatever the trade did".
        float tgt = grid.get(math.max(g1, 0))
        float acc = 0.0
        for o in store
            if f_inPool(o, lvl, bucket, dirIdx)
                acc += o.mfeR >= tgt ? tgt : o.exitR
        edge := acc / n
    [lvl, n, g1, g2, g3, s1, s2, s3, edge]
 
// Median bars-to-reach for grid level g inside the chosen pool.
f_medBars(array<Outcome> store, int lvl, int bucket, int dirIdx, int g) =>
    float med = na
    if g >= 0 and lvl < 3
        array<int> tmp = array.new<int>()
        for o in store
            int rb = o.reachAt(g)
            if f_inPool(o, lvl, bucket, dirIdx) and rb >= 0
                tmp.push(rb)
        if tmp.size() > 0
            med := tmp.median()
    med
 
f_rTxt(float r) =>
    str.tostring(r, "#.#") + "R"
 
f_pctTxt(float s) =>
    na(s) ? "n/a" : str.tostring(math.round(s * 100)) + "%"
 
f_freezeBox(box b, int atBar) =>
    if not na(b)
        box.set_right(b, math.min(box.get_right(b), atBar))
 
f_freezeLabel(label l, int atBar, bool mark, string suffix) =>
    if not na(l)
        label.set_x(l, math.min(label.get_x(l), atBar))
        if mark
            label.set_text(l, label.get_text(l) + suffix)
 
f_fadeBox(box b, color c, int bgT, int bdT) =>
    if not na(b)
        box.set_bgcolor(b, color.new(c, bgT))
        box.set_border_color(b, color.new(c, bdT))
 
f_fadeLabel(label l, color c) =>
    if not na(l)
        label.set_textcolor(l, color.new(c, 45))
 
f_eraseBox(box b) =>
    if not na(b)
        box.delete(b)
 
f_eraseLabel(label l) =>
    if not na(l)
        label.delete(l)
 
f_drawTarget(int x0, int x1, float yFrom, float yTo, color c, float prob, string txt, string tip) =>
    int bgT = na(prob) ? 88 : math.round(88 - prob * 20)
    box b = box.new(x0, math.max(yFrom, yTo), x1, math.min(yFrom, yTo), border_color = color.new(c, 55), border_width = 1, bgcolor = color.new(c, bgT), xloc = xloc.bar_index)
    label l = label.new(x1, yTo, txt, xloc = xloc.bar_index, yloc = yloc.price, color = CLEAR, style = label.style_label_left, textcolor = c, size = size.small, tooltip = tip)
    [b, l]
 
// ───────────────────────────── Trend engine (efficiency-adaptive trail) ─────────────────────────────
float atr     = ta.atr(14)
float netMove = math.abs(close - close[erLen])
float pathLen = math.sum(math.abs(ta.change(close)), erLen)
float er      = na(netMove) or na(pathLen) or pathLen <= 0 ? 0.0 : netMove / pathLen
float erMed   = ta.percentile_linear_interpolation(er, 200, 50)
bool cleanCtx = na(erMed) ? er >= 0.30 : er >= erMed
 
float fastSC = 2.0 / 3.0
float slowSC = 2.0 / (slowLen + 1)
float sc     = math.pow(er * (fastSC - slowSC) + slowSC, 2)
var float kama = na
kama := na(kama) ? close : kama + sc * (close - kama)
 
float swingLo = ta.lowest(low, stopLen)
float swingHi = ta.highest(high, stopLen)
 
var float trail = na
var int   trend = 0
bool flipUp = false
bool flipDn = false
if not na(atr)
    float upTrail = kama - bandK * atr
    float dnTrail = kama + bandK * atr
    if trend == 0
        trend := close >= kama ? 1 : -1
        trail := trend == 1 ? upTrail : dnTrail
    else if trend == 1
        trail := math.max(trail, upTrail)
        if close < trail
            trend  := -1
            trail  := dnTrail
            flipDn := true
    else
        trail := math.min(trail, dnTrail)
        if close > trail
            trend  := 1
            trail  := upTrail
            flipUp := true
 
// Signals exist only on closed bars.
bool sigUp = flipUp and barstate.isconfirmed
bool sigDn = flipDn and barstate.isconfirmed
 
// ───────────────────────────── Shadow-trade state ─────────────────────────────
var array<float>   grid  = array.from(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0)
var array<Outcome> store = array.new<Outcome>()
var array<Plan>    plans = array.new<Plan>()
var array<int>     tReach = array.new<int>(8, -1)
 
var bool  tOpen     = false
var int   tDir      = 0
var int   tBucket   = 0
var int   tStartBar = na
var float tEntry    = na
var float tRisk     = na
var float tStop     = na
var float tMfe      = 0.0
var int   ties      = 0
var int   resolved  = 0
var string lastExit = "—"
 
// Last plan snapshot for the dashboard and screener columns.
var int   lastDir     = 0
var int   lastVerdict = -1   // 1 TAKE · 0 SKIP · 2 CALIBRATING
var int   lastSigBar  = na
var int   pLvl  = 3
var int   pN    = 0
var int   pG1   = -1
var int   pG2   = -1
var int   pG3   = -1
var float pS1   = na
var float pS2   = na
var float pS3   = na
var float pM1   = na
var float pM2   = na
var float pM3   = na
var float pEdge = na
var bool  pCtxClean = true
 
// 1) Advance the open shadow trade on the closed bar (stop-first on ambiguous bars).
bool   resolveNow = false
bool   stopped    = false
if barstate.isconfirmed and tOpen and bar_index > tStartBar and tRisk > 0
    bool  stopHit = tDir == 1 ? low <= tStop : high >= tStop
    float barMfe  = tDir == 1 ? (high - tEntry) / tRisk : (tEntry - low) / tRisk
    if stopHit
        bool wouldReach = false
        for g = 0 to 7
            if tReach.get(g) < 0 and barMfe >= grid.get(g)
                wouldReach := true
        if wouldReach
            ties += 1
        resolveNow := true
        stopped    := true
    else
        if barMfe > tMfe
            tMfe := barMfe
            for g = 0 to 7
                if tReach.get(g) < 0 and tMfe >= grid.get(g)
                    tReach.set(g, bar_index - tStartBar)
        if bar_index - tStartBar >= horizon
            resolveNow := true
    if sigUp or sigDn
        resolveNow := true
 
if resolveNow
    float exitR = stopped ? -1.0 : tDir * (close - tEntry) / tRisk
    Outcome o = Outcome.new(bucket = tBucket, dir = tDir == 1 ? 0 : 1, mfeR = math.max(tMfe, 0.0), exitR = exitR, r0 = tReach.get(0), r1 = tReach.get(1), r2 = tReach.get(2), r3 = tReach.get(3), r4 = tReach.get(4), r5 = tReach.get(5), r6 = tReach.get(6), r7 = tReach.get(7))
    store.push(o)
    if store.size() > MAX_STORE
        store.shift()
    resolved += 1
    lastExit := stopped ? "stopped" : (sigUp or sigDn) ? "reversed" : "horizon"
    tOpen := false
    if plans.size() > 0
        Plan lp = plans.last()
        if lp.live
            f_freezeBox(lp.zStop, bar_index)
            f_freezeBox(lp.z1, bar_index)
            f_freezeBox(lp.z2, bar_index)
            f_freezeBox(lp.z3, bar_index)
            f_freezeLabel(lp.l1, bar_index, lp.g1 >= 0 and tReach.get(math.max(lp.g1, 0)) >= 0, " ✓")
            f_freezeLabel(lp.l2, bar_index, lp.g2 >= 0 and tReach.get(math.max(lp.g2, 0)) >= 0, " ✓")
            f_freezeLabel(lp.l3, bar_index, lp.g3 >= 0 and tReach.get(math.max(lp.g3, 0)) >= 0, " ✓")
            f_freezeLabel(lp.lS, bar_index, stopped, " ✕")
            if not na(lp.ent)
                line.set_x2(lp.ent, math.min(line.get_x2(lp.ent), bar_index))
            lp.live := false
 
// 2) A new flip: read the evidence, issue the verdict, open the next shadow trade, draw the staircase.
if (sigUp or sigDn) and not na(atr) and atr > 0
    int   dirSign = sigUp ? 1 : -1
    int   dirIdx  = sigUp ? 0 : 1
    float entry   = close
    float swing   = sigUp ? swingLo : swingHi
    float riskRaw = na(swing) ? atr : dirSign == 1 ? entry - swing : swing - entry
    float risk    = math.max(0.5 * atr, math.min(3.0 * atr, riskRaw))
    int   ctxIdx  = useCtx ? (cleanCtx ? 0 : 1) : 0
    int   bucket  = dirIdx * 2 + ctxIdx
 
    [sLvl, sN, sG1, sG2, sG3, sS1, sS2, sS3, sEdge] = f_stats(store, grid, bucket, dirIdx, minN, p1, p2, p3)
    float m1 = f_medBars(store, sLvl, bucket, dirIdx, sG1)
    float m2 = f_medBars(store, sLvl, bucket, dirIdx, sG2)
    float m3 = f_medBars(store, sLvl, bucket, dirIdx, sG3)
    int verdict = sLvl == 3 ? 2 : (sG1 >= 0 and sEdge > 0 ? 1 : 0)
 
    tOpen     := true
    tDir      := dirSign
    tBucket   := bucket
    tStartBar := bar_index
    tEntry    := entry
    tRisk     := risk
    tStop     := entry - dirSign * risk
    tMfe      := 0.0
    tReach.fill(-1)
 
    lastDir     := dirSign
    lastVerdict := verdict
    lastSigBar  := bar_index
    pLvl  := sLvl
    pN    := sN
    pG1   := sG1
    pG2   := sG2
    pG3   := sG3
    pS1   := sS1
    pS2   := sS2
    pS3   := sS3
    pM1   := m1
    pM2   := m2
    pM3   := m3
    pEdge := sEdge
    pCtxClean := cleanCtx
 
    if showPlan
        if plans.size() > 0
            Plan prev = plans.last()
            f_fadeBox(prev.z1, prev.col, 93, 82)
            f_fadeBox(prev.z2, prev.col, 94, 84)
            f_fadeBox(prev.z3, prev.col, 95, 86)
            f_fadeBox(prev.zStop, NEUTRAL, 94, 86)
            f_fadeLabel(prev.l1, prev.col)
            f_fadeLabel(prev.l2, prev.col)
            f_fadeLabel(prev.l3, prev.col)
            f_fadeLabel(prev.lS, NEUTRAL)
        bool  calib = verdict == 2
        color c     = verdict == 0 ? NEUTRAL : dirSign == 1 ? bullCol : bearCol
        color opp   = dirSign == 1 ? bearCol : bullCol
        // Calibrating plans show plain 1R / 2R / 3R references until the sample is large enough.
        int dg1 = calib ? 1 : sG1
        int dg2 = calib ? 3 : sG2
        int dg3 = calib ? 5 : sG3
        int w1 = calib ? math.round(horizon * 0.25) : na(m1) ? math.round(horizon * 0.5) : math.round(m1)
        int w2 = calib ? math.round(horizon * 0.50) : na(m2) ? math.round(horizon * 0.5) : math.round(m2)
        int w3 = calib ? math.round(horizon * 0.75) : na(m3) ? math.round(horizon * 0.5) : math.round(m3)
        w1 := math.max(2, math.min(w1, 480))
        w2 := math.max(2, math.min(w2, 480))
        w3 := math.max(2, math.min(w3, 480))
        string poolTxt = sLvl == 0 ? "same direction + context" : sLvl == 1 ? "same direction" : sLvl == 2 ? "all flips" : "calibrating"
        string tipBase = "Evidence: " + poolTxt + " (n=" + str.tostring(sN) + ")"
        Plan pl = Plan.new(col = c, g1 = dg1, g2 = dg2, g3 = dg3)
        float lastLvl = entry
        int   xMax    = bar_index + 2
        if dg1 >= 0
            float y1 = entry + dirSign * grid.get(dg1) * risk
            string t1 = "T1 +" + f_rTxt(grid.get(dg1)) + (calib ? "" : "  " + f_pctTxt(sS1) + "  ~" + str.tostring(w1) + " bars")
            [b1, lb1] = f_drawTarget(bar_index, bar_index + w1, lastLvl, y1, c, calib ? na : sS1, t1, tipBase)
            pl.z1 := b1
            pl.l1 := lb1
            lastLvl := y1
            xMax := math.max(xMax, bar_index + w1)
        if dg2 >= 0
            float y2 = entry + dirSign * grid.get(dg2) * risk
            string t2 = "T2 +" + f_rTxt(grid.get(dg2)) + (calib ? "" : "  " + f_pctTxt(sS2) + "  ~" + str.tostring(w2) + " bars")
            [b2, lb2] = f_drawTarget(bar_index, bar_index + w2, lastLvl, y2, c, calib ? na : sS2, t2, tipBase)
            pl.z2 := b2
            pl.l2 := lb2
            lastLvl := y2
            xMax := math.max(xMax, bar_index + w2)
        if dg3 >= 0
            float y3 = entry + dirSign * grid.get(dg3) * risk
            string t3 = "T3 +" + f_rTxt(grid.get(dg3)) + (calib ? "" : "  " + f_pctTxt(sS3) + "  ~" + str.tostring(w3) + " bars")
            [b3, lb3] = f_drawTarget(bar_index, bar_index + w3, lastLvl, y3, c, calib ? na : sS3, t3, tipBase)
            pl.z3 := b3
            pl.l3 := lb3
            xMax := math.max(xMax, bar_index + w3)
        float yS = tStop
        pl.zStop := box.new(bar_index, math.max(entry, yS), xMax, math.min(entry, yS), border_color = color.new(opp, 60), border_width = 1, border_style = line.style_dashed, bgcolor = color.new(NEUTRAL, 88), xloc = xloc.bar_index)
        string stopTxt = "Stop −1R · " + (verdict == 0 ? "SKIP" : verdict == 2 ? "calibrating" : "TAKE")
        pl.lS  := label.new(xMax, yS, stopTxt, xloc = xloc.bar_index, yloc = yloc.price, color = CLEAR, style = label.style_label_left, textcolor = NEUTRAL, size = size.small, tooltip = tipBase)
        pl.ent := line.new(bar_index, entry, xMax, entry, xloc = xloc.bar_index, color = color.new(NEUTRAL, 35), style = line.style_dotted, width = 1)
        plans.push(pl)
        while plans.size() > keepPlans + 1
            Plan old = plans.shift()
            f_eraseBox(old.z1)
            f_eraseBox(old.z2)
            f_eraseBox(old.z3)
            f_eraseBox(old.zStop)
            f_eraseLabel(old.l1)
            f_eraseLabel(old.l2)
            f_eraseLabel(old.l3)
            f_eraseLabel(old.lS)
            if not na(old.ent)
                line.delete(old.ent)
 
// ───────────────────────────── Plots ─────────────────────────────
color trendCol = trend == 1 ? bullCol : trend == -1 ? bearCol : NEUTRAL
pTrail = plot(trend != trend[1] ? na : trail, "Trend Trail", trendCol, 2, plot.style_linebr)
pMid   = plot(hl2, "Mid", display = display.none, editable = false)
fill(pTrail, pMid, color.new(trendCol, 90), "Trend Fill")
 
bool takeUp = sigUp and lastVerdict == 1
bool takeDn = sigDn and lastVerdict == 1
bool skipUp = sigUp and lastVerdict == 0
bool skipDn = sigDn and lastVerdict == 0
bool calUp  = sigUp and lastVerdict == 2
bool calDn  = sigDn and lastVerdict == 2
 
float offs = na(atr) ? 0.0 : 0.35 * atr
float yTakeUp = takeUp ? low - offs : na
float yTakeDn = takeDn ? high + offs : na
float ySkipUp = skipUp and showSkip ? low - offs : na
float ySkipDn = skipDn and showSkip ? high + offs : na
float yCalUp  = calUp ? low - offs : na
float yCalDn  = calDn ? high + offs : na
plotshape(yTakeUp, "Long TAKE",  shape.triangleup,   location.absolute, bullCol, size = size.small)
plotshape(yTakeDn, "Short TAKE", shape.triangledown, location.absolute, bearCol, size = size.small)
plotshape(ySkipUp, "Long SKIP",  shape.xcross, location.absolute, color.new(NEUTRAL, 20), size = size.tiny)
plotshape(ySkipDn, "Short SKIP", shape.xcross, location.absolute, color.new(NEUTRAL, 20), size = size.tiny)
plotshape(yCalUp,  "Long flip (calibrating)",  shape.triangleup,   location.absolute, color.new(bullCol, 55), size = size.tiny)
plotshape(yCalDn,  "Short flip (calibrating)", shape.triangledown, location.absolute, color.new(bearCol, 55), size = size.tiny)
 
// Defensive price-scale anchors (invisible, pane only).
plot(high, "Scale Anchor High", CLEAR, display = display.pane, editable = false)
plot(low,  "Scale Anchor Low",  CLEAR, display = display.pane, editable = false)
 
// Pine Screener columns.
float sigCode = sigUp ? (lastVerdict == 1 ? 1.0 : 0.5) : sigDn ? (lastVerdict == 1 ? -1.0 : -0.5) : 0.0
plot(sigCode, "Signal (+1 long TAKE, -1 short TAKE, ±0.5 other flip)", display = display.data_window)
plot(trend, "Trend State (+1 / -1)", display = display.data_window)
plot(pEdge, "Edge at T1 (R per trade)", display = display.data_window)
plot(na(pS1) ? na : pS1 * 100, "T1 Reach Probability (%)", display = display.data_window)
plot(na(lastSigBar) ? na : bar_index - lastSigBar, "Bars Since Flip", display = display.data_window)
 
// ───────────────────────────── Alerts ─────────────────────────────
alertcondition(takeUp, "PSTE Long TAKE", "PSTE: long flip with positive T1 evidence on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(takeDn, "PSTE Short TAKE", "PSTE: short flip with positive T1 evidence on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sigUp, "PSTE Long Flip (any verdict)", "PSTE: bullish trend flip on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sigDn, "PSTE Short Flip (any verdict)", "PSTE: bearish trend flip on {{ticker}} ({{interval}}) at {{close}}")
 
// ───────────────────────────── Dashboard ─────────────────────────────
var table dash = table.new(position.top_right, 2, 10, bgcolor = color.new(DASH_BG, 8), frame_color = color.new(NEUTRAL, 60), frame_width = 1, border_color = color.new(NEUTRAL, 85), border_width = 1)
 
f_row(table t, int r, string k, string v, color vc, string sz) =>
    table.cell(t, 0, r, k, text_color = color.new(DASH_TXT, 30), text_halign = text.align_left, text_size = sz)
    table.cell(t, 1, r, v, text_color = vc, text_halign = text.align_right, text_size = sz)
 
if barstate.islast and showDash
    color dirC = lastDir == 1 ? bullCol : lastDir == -1 ? bearCol : NEUTRAL
    string trendTxt = (trend == 1 ? "▲ BULL" : trend == -1 ? "▼ BEAR" : "—") + (cleanCtx ? " · clean" : " · choppy")
    string verdTxt = lastVerdict == 1 ? "TAKE" : lastVerdict == 0 ? "SKIP" : lastVerdict == 2 ? "CALIBRATING" : "—"
    color verdC = lastVerdict == 1 ? dirC : NEUTRAL
    string flipTxt = na(lastSigBar) ? "—" : (lastDir == 1 ? "LONG · " : "SHORT · ") + verdTxt + " · " + str.tostring(bar_index - lastSigBar) + " bars ago"
    string poolTxt = pLvl == 0 ? "Direction + context" : pLvl == 1 ? "Direction pool" : pLvl == 2 ? "All flips" : "Calibrating"
    string evTxt = pLvl == 3 ? poolTxt + " " + str.tostring(store.size()) + "/" + str.tostring(minN) : poolTxt + " · n=" + str.tostring(pN)
    string t1Txt = pLvl == 3 or pG1 < 0 ? "none ≥ " + str.tostring(math.round(p1 * 100)) + "%" : "+" + f_rTxt(grid.get(pG1)) + " · " + f_pctTxt(pS1) + " · ~" + str.tostring(pM1, "#") + " bars"
    string t2Txt = pLvl == 3 or pG2 < 0 ? "—" : "+" + f_rTxt(grid.get(pG2)) + " · " + f_pctTxt(pS2) + " · ~" + str.tostring(pM2, "#") + " bars"
    string t3Txt = pLvl == 3 or pG3 < 0 ? "—" : "+" + f_rTxt(grid.get(pG3)) + " · " + f_pctTxt(pS3) + " · ~" + str.tostring(pM3, "#") + " bars"
    string edgeTxt = na(pEdge) ? "—" : (pEdge >= 0 ? "+" : "") + str.tostring(pEdge, "#.00") + "R / trade"
    color edgeC = na(pEdge) ? NEUTRAL : pEdge > 0 ? bullCol : bearCol
    string liveTxt = tOpen ? "Open · MFE +" + str.tostring(tMfe, "#.0") + "R · " + str.tostring(bar_index - tStartBar) + "/" + str.tostring(horizon) : na(lastSigBar) ? "—" : "Closed · " + lastExit
    table.cell(dash, 0, 0, "PSTE", text_color = DASH_TXT, text_halign = text.align_left, text_size = tSz, text_formatting = text.format_bold)
    table.cell(dash, 1, 0, trendTxt, text_color = trendCol, text_halign = text.align_right, text_size = tSz, text_formatting = text.format_bold)
    f_row(dash, 1, "Last flip", flipTxt, verdC, tSz)
    f_row(dash, 2, "Evidence", evTxt, DASH_TXT, tSz)
    f_row(dash, 3, "T1", t1Txt, dirC, tSz)
    f_row(dash, 4, "T2", t2Txt, dirC, tSz)
    f_row(dash, 5, "T3", t3Txt, dirC, tSz)
    f_row(dash, 6, "Edge at T1", edgeTxt, edgeC, tSz)
    f_row(dash, 7, "Live plan", liveTxt, DASH_TXT, tSz)
    f_row(dash, 8, "Record", str.tostring(resolved) + " resolved · " + str.tostring(ties) + " stop-first ties", color.new(DASH_TXT, 25), tSz)
    f_row(dash, 9, "Data mode", "ALL PLANS · closed-bar OHLC", color.new(DASH_TXT, 25), tSz)

← 返回列表