Liquidity Sweep & CHoCH Target Zones [PhenLabs]

PhenLabs · study · 1053 行 · 点赞 593 · TradingView 原页

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

Pine Script

//@version=6
indicator("Liquidity Sweep & CHoCH Target Zones [PhenLabs]", shorttitle = "LSCTZ [PhenLabs]", overlay = true, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 250)
 
// ══════════════════════════════════════════════════════════════════════════════
// Enums & Inputs (Progressive Disclosure, < 15 Rows, Zero CW10026 Warnings)
// ══════════════════════════════════════════════════════════════════════════════
enum ProfSel
    auto   = "Auto Best (by Avg R)"
    bal    = "Balanced (8-bar)"
    scalp  = "Scalp Fast (6-bar)"
    strict = "Swing Strict (10-bar)"
 
enum EntryStyle
    pullback  = "CHoCH + Pullback (Confirmed)"
    immediate = "CHoCH Close (Immediate)"
 
enum TrendGate
    aligned = "EMA 50 & 200 Aligned"
    ema200  = "EMA 200 Only"
    off     = "Off (All Reversals)"
 
enum SlType
    atrMult = "ATR Multiple"
    wickBuf = "Sweep Wick + ATR Buffer"
 
enum TblSz
    tiny   = "Tiny"
    small  = "Small"
    normal = "Normal"
 
const string G1 = "1 · Setup & Confirmation"
const string G2 = "2 · Stop Loss & Targets"
const string G3 = "3 · Display & Declutter"
 
ProfSel    profIn    = input.enum(ProfSel.auto, "Profile", group = G1, tooltip = "Auto Best evaluates Balanced, Scalp Fast, and Swing Strict in parallel and routes new setups using the profile with the highest closed-trade Avg R (minimum 4 closed trades; starts on Balanced).")
EntryStyle entryIn   = input.enum(EntryStyle.pullback, "Entry Mode", group = G1, tooltip = "CHoCH + Pullback waits for price to dip into the discount/premium zone of the CHoCH leg and close back in favor of the shift (+0.15R to +0.21R avg in multi-asset testing). Immediate enters directly on a non-extended CHoCH close.")
TrendGate  trendIn   = input.enum(TrendGate.aligned, "Trend Filter", group = G1, tooltip = "EMA 50 & 200 Aligned takes liquidity sweep + CHoCH setups aligned with the prevailing trend. Set Off to allow counter-trend major reversals.")
bool       effIn     = input.bool(true, "Volume / Range Displacement Filter", group = G1, tooltip = "Requires above-average volume (or candle range expansion on volume-free feeds) on the CHoCH structure break candle.")
 
SlType     slModeIn  = input.enum(SlType.atrMult, "Stop Loss Mode", group = G2, tooltip = "ATR Multiple sets stop distance at Stop Value × ATR(14) from entry. Sweep Wick + ATR Buffer places the stop beyond the liquidity sweep wick extreme plus Stop Value × ATR(14).")
float      slValIn   = input.float(1.50, "Stop Distance / Wick Buffer (ATR)", minval = 0.15, maxval = 4.0, step = 0.05, group = G2, tooltip = "In ATR Multiple mode, 1.50 = 1.5× ATR stop distance. In Sweep Wick mode, try 0.25–0.50 to add ATR breathing room past the sweep wick.")
bool       beIn      = input.bool(false, "Move Stop to Break-Even at TP1", group = G2, tooltip = "When enabled, ratchets the active stop loss to Entry once TP1 is reached. Scale-out weights: 50% at TP1, 30% at TP2, 20% at TP3.")
float      tp1RIn    = input.float(1.0, "Targets: TP1 / TP2 / TP3 (R)", minval = 0.4, maxval = 5.0, step = 0.1, inline = "tp", group = G2)
float      tp2RIn    = input.float(2.0, "", minval = 0.8, maxval = 8.0, step = 0.1, inline = "tp", group = G2)
float      tp3RIn    = input.float(3.0, "", minval = 1.2, maxval = 12.0, step = 0.1, inline = "tp", group = G2, tooltip = "R-multiple targets relative to initial stop risk (50% / 30% / 20% partial exits).")
bool       magIn     = input.bool(true, "Snap TP2 to Opposing Liquidity Pool", group = G2, tooltip = "If an unswept opposing BSL/SSL pool sits between TP1 and TP3, snaps TP2 just inside that liquidity draw.")
 
bool       shSwpIn   = input.bool(true, "Show: Sweep Traps / CHoCH / Pools", inline = "sh1", group = G3)
bool       shChochIn = input.bool(true, "", inline = "sh1", group = G3)
bool       shPoolIn  = input.bool(true, "", inline = "sh1", group = G3, tooltip = "Toggle Sweep Trap boxes, CHoCH structure lines, and active BSL/SSL pool rays.")
bool       shEnIn    = input.bool(true, "Plan: Entry / Stop Box / TP1–TP3", inline = "sh2", group = G3)
bool       shSlIn    = input.bool(true, "", inline = "sh2", group = G3)
bool       shTpIn    = input.bool(true, "", inline = "sh2", group = G3, tooltip = "Independently show or hide Entry line, Stop-Loss risk box/line, and TP1–TP3 target lines/boxes.")
int        histIn    = input.int(4, "Past Plans Shown", minval = 1, maxval = 12, group = G3)
bool       shTblIn   = input.bool(true, "Dashboard & Size", inline = "tb", group = G3)
TblSz      tblSzIn   = input.enum(TblSz.small, "", inline = "tb", group = G3)
color      bullC     = input.color(#00E5A8, "Colors: Bull / Bear / Sweep", inline = "cl", group = G3)
color      bearC     = input.color(#FF4D6D, "", inline = "cl", group = G3)
color      swpC      = input.color(#38BDF8, "", inline = "cl", group = G3, tooltip = "Bullish target/signal color, Bearish stop/signal color, and Liquidity Sweep setup color (kept distinct from red/green risk boxes).")
 
// ══════════════════════════════════════════════════════════════════════════════
// Buffer Reservations & Core Series
// ══════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 100)
max_bars_back(high, 100)
max_bars_back(low, 100)
max_bars_back(open, 100)
max_bars_back(close, 100)
 
float atr      = ta.atr(14)
float ema50    = ta.ema(close, 50)
float ema200   = ta.ema(close, 200)
float volAvg   = ta.sma(volume, 20)
bool  hasVol   = not na(volume) and not na(volAvg) and volAvg > 0
float barSpan  = math.max(high - low, syminfo.mintick)
float spanAvg  = ta.sma(barSpan, 20)
float effort   = hasVol ? volume / math.max(volAvg, 1e-9) : barSpan / math.max(nz(spanAvg, barSpan), 1e-9)
float lwRatio  = (math.min(open, close) - low) / barSpan
float uwRatio  = (high - math.max(open, close)) / barSpan
float bodyFrac = math.abs(close - open) / barSpan
int   tfSec    = timeframe.in_seconds()
int   barMs    = math.max(tfSec, 60) * 1000
color bslCol   = #F5C542
 
// Pre-compute confirmed pivots for all 3 profile lengths (6, 8, 10) + 3-bar internal structure
float ph6  = ta.pivothigh(high, 6, 6)
float pl6  = ta.pivotlow(low, 6, 6)
float ph8  = ta.pivothigh(high, 8, 8)
float pl8  = ta.pivotlow(low, 8, 8)
float ph10 = ta.pivothigh(high, 10, 10)
float pl10 = ta.pivotlow(low, 10, 10)
float hi3  = ta.highest(high[1], 3)
float lo3  = ta.lowest(low[1], 3)
 
// ══════════════════════════════════════════════════════════════════════════════
// User-Defined Types (UDTs) & Methods
// ══════════════════════════════════════════════════════════════════════════════
type Pool
    float price
    int   pivTime
 
type PlanDraw
    box   swpB
    line  chochLn
    label chochLb
    box   pbB
    box   riskB
    box   rewB
    line  eL
    line  sL
    line  t1L
    line  t2L
    line  t3L
    label eLb
    label sLb
    label t1Lb
    label t2Lb
    label t3Lb
    label sigLb
    label resLb
 
method cleanup(PlanDraw this) =>
    box.delete(this.swpB)
    line.delete(this.chochLn)
    label.delete(this.chochLb)
    box.delete(this.pbB)
    box.delete(this.riskB)
    box.delete(this.rewB)
    line.delete(this.eL)
    line.delete(this.sL)
    line.delete(this.t1L)
    line.delete(this.t2L)
    line.delete(this.t3L)
    label.delete(this.eLb)
    label.delete(this.sLb)
    label.delete(this.t1Lb)
    label.delete(this.t2Lb)
    label.delete(this.t3Lb)
    label.delete(this.sigLb)
    label.delete(this.resLb)
    true
 
type SimEngine
    int         extLen
    float       effMin
    array<Pool> bsl
    array<Pool> ssl
    int         st       = 0      // 0 idle, 1 sweep_armed, 2 choch_wait_pb, 3 in_trade
    int         dir      = 0
    int         age      = 0
    float       poolPx   = na
    float       swpExt   = na
    float       trigPx   = na
    float       legHi    = na
    float       legLo    = na
    float       tEn      = na
    float       tSl      = na
    float       tTp1     = na
    float       tTp2     = na
    float       tTp3     = na
    float       tRisk    = na
    int         tStage   = 0
    float       tR       = 0.0
    int         tBars    = 0
    int         nTrades  = 0
    int         nWins    = 0
    float       netR     = 0.0
 
f_clamp(float v, float lo, float hi) =>
    math.min(math.max(v, lo), hi)
 
f_trendOk(int d, TrendGate tg, float c, float e50, float e200) =>
    bool ok = true
    if tg == TrendGate.aligned
        ok := d == 1 ? (c > e200 and e50 >= e200) : (c < e200 and e50 <= e200)
    else if tg == TrendGate.ema200
        ok := d == 1 ? c > e200 : c < e200
    ok
 
f_score(float swpDepthAtr, float eff, float bFrac, float wRat, bool aligned) =>
    float sDepth = f_clamp(swpDepthAtr / 0.6, 0.15, 1.0) * 25.0
    float sEff   = f_clamp(eff / 1.8, 0.20, 1.0) * 30.0
    float sBody  = f_clamp((bFrac + wRat) / 1.1, 0.20, 1.0) * 25.0
    float sTr    = aligned ? 20.0 : 10.0
    math.round(f_clamp(sDepth + sEff + sBody + sTr, 50.0, 99.0))
 
// Step background tournament profile ledger on confirmed bars
method stepSim(SimEngine this, float phVal, float plVal, int pivTimeVal, float atrV, float hi3V, float lo3V, EntryStyle eStyle, TrendGate tGate, SlType sMode, float sVal, bool useBe, float r1, float r2, float r3, bool useEff, float e50, float e200) =>
    if not na(phVal)
        bool unbrokenH = true
        for k = 0 to this.extLen - 1
            if high[k] > phVal
                unbrokenH := false
        if unbrokenH
            array.push(this.bsl, Pool.new(phVal, pivTimeVal))
            if array.size(this.bsl) > 6
                array.shift(this.bsl)
    if not na(plVal)
        bool unbrokenL = true
        for k = 0 to this.extLen - 1
            if low[k] < plVal
                unbrokenL := false
        if unbrokenL
            array.push(this.ssl, Pool.new(plVal, pivTimeVal))
            if array.size(this.ssl) > 6
                array.shift(this.ssl)
 
    if this.st == 3
        this.tBars += 1
        bool isL   = this.dir == 1
        bool slHit = isL ? low <= this.tSl : high >= this.tSl
        bool done  = false
        if slHit
            float rem = this.tStage == 0 ? 1.0 : this.tStage == 1 ? 0.5 : 0.2
            this.tR  += rem * ((this.tSl - this.tEn) * this.dir) / this.tRisk
            done     := true
        else
            if this.tStage == 0 and (isL ? high >= this.tTp1 : low <= this.tTp1)
                this.tStage := 1
                this.tR     += 0.5 * (math.abs(this.tTp1 - this.tEn) / this.tRisk)
                if useBe
                    this.tSl := this.tEn
            if this.tStage == 1 and (isL ? high >= this.tTp2 : low <= this.tTp2)
                this.tStage := 2
                this.tR     += 0.3 * (math.abs(this.tTp2 - this.tEn) / this.tRisk)
            if this.tStage == 2 and (isL ? high >= this.tTp3 : low <= this.tTp3)
                this.tStage := 3
                this.tR     += 0.2 * (math.abs(this.tTp3 - this.tEn) / this.tRisk)
                done        := true
            if not done and this.tBars >= 80
                float rem = this.tStage == 0 ? 1.0 : this.tStage == 1 ? 0.5 : 0.2
                this.tR  += rem * ((close - this.tEn) * this.dir) / this.tRisk
                done     := true
        if done
            this.nTrades += 1
            if this.tStage >= 1
                this.nWins += 1
            this.netR += this.tR
            this.st   := 0
            this.dir  := 0
 
    float sweptSsl = na
    if array.size(this.ssl) > 0
        for i = array.size(this.ssl) - 1 to 0
            Pool p = array.get(this.ssl, i)
            if low < p.price
                sweptSsl := na(sweptSsl) ? p.price : math.min(sweptSsl, p.price)
                array.remove(this.ssl, i)
 
    float sweptBsl = na
    if array.size(this.bsl) > 0
        for i = array.size(this.bsl) - 1 to 0
            Pool p = array.get(this.bsl, i)
            if high > p.price
                sweptBsl := na(sweptBsl) ? p.price : math.max(sweptBsl, p.price)
                array.remove(this.bsl, i)
 
    bool effOk = not useEff or effort >= this.effMin
    bool fire  = false
    int  fDir  = 0
 
    if this.st == 2
        this.age += 1
        bool isL = this.dir == 1
        if (isL ? close < this.swpExt : close > this.swpExt) or this.age > 8
            this.st  := 0
            this.dir := 0
        else
            if isL
                this.legHi := math.max(this.legHi, high)
            else
                this.legLo := math.min(this.legLo, low)
            float pbEdge  = isL ? this.legLo + 0.60 * (this.legHi - this.legLo) : this.legHi - 0.60 * (this.legHi - this.legLo)
            bool  touched = isL ? low <= pbEdge : high >= pbEdge
            bool  held    = isL ? (close > open and close > this.poolPx) : (close < open and close < this.poolPx)
            if touched and held and f_trendOk(this.dir, tGate, close, e50, e200)
                fire := true
                fDir := this.dir
    else if this.st == 1
        this.age += 1
        bool isL = this.dir == 1
        if isL
            this.swpExt := math.min(this.swpExt, low)
            if close < this.poolPx - 1.0 * atrV or this.age > 6
                this.st  := 0
                this.dir := 0
            else if close > this.trigPx and close > open and effOk
                if eStyle == EntryStyle.immediate
                    if (close - this.swpExt) <= 1.8 * atrV and f_trendOk(1, tGate, close, e50, e200)
                        fire := true
                        fDir := 1
                    else
                        this.st := 0
                else
                    this.st    := 2
                    this.age   := 0
                    this.legLo := this.swpExt
                    this.legHi := high
        else
            this.swpExt := math.max(this.swpExt, high)
            if close > this.poolPx + 1.0 * atrV or this.age > 6
                this.st  := 0
                this.dir := 0
            else if close < this.trigPx and close < open and effOk
                if eStyle == EntryStyle.immediate
                    if (this.swpExt - close) <= 1.8 * atrV and f_trendOk(-1, tGate, close, e50, e200)
                        fire := true
                        fDir := -1
                    else
                        this.st := 0
                else
                    this.st    := 2
                    this.age   := 0
                    this.legHi := this.swpExt
                    this.legLo := low
 
    if this.st == 0 and not fire
        if not na(sweptSsl) and close >= sweptSsl - 1.0 * atrV and not na(hi3V)
            this.st     := 1
            this.dir    := 1
            this.age    := 0
            this.poolPx := sweptSsl
            this.swpExt := low
            this.trigPx := hi3V
            if close > hi3V and close > open and effOk
                if eStyle == EntryStyle.immediate
                    if (close - low) <= 1.8 * atrV and f_trendOk(1, tGate, close, e50, e200)
                        fire := true
                        fDir := 1
                    else
                        this.st := 0
                else
                    this.st    := 2
                    this.age   := 0
                    this.legLo := low
                    this.legHi := high
        else if not na(sweptBsl) and close <= sweptBsl + 1.0 * atrV and not na(lo3V)
            this.st     := 1
            this.dir    := -1
            this.age    := 0
            this.poolPx := sweptBsl
            this.swpExt := high
            this.trigPx := lo3V
            if close < lo3V and close < open and effOk
                if eStyle == EntryStyle.immediate
                    if (high - close) <= 1.8 * atrV and f_trendOk(-1, tGate, close, e50, e200)
                        fire := true
                        fDir := -1
                    else
                        this.st := 0
                else
                    this.st    := 2
                    this.age   := 0
                    this.legHi := high
                    this.legLo := low
 
    if fire and this.st != 3
        float en   = close
        float rawD = fDir == 1 ? (en - (this.swpExt - sVal * atrV)) : ((this.swpExt + sVal * atrV) - en)
        float dist = sMode == SlType.atrMult ? sVal * atrV : f_clamp(rawD, 0.6 * atrV, 3.0 * atrV)
        if dist > syminfo.mintick
            this.st     := 3
            this.dir    := fDir
            this.tEn    := en
            this.tRisk  := dist
            this.tSl    := en - fDir * dist
            this.tTp1   := en + fDir * r1 * dist
            this.tTp2   := en + fDir * r2 * dist
            this.tTp3   := en + fDir * r3 * dist
            this.tStage := 0
            this.tR     := 0.0
            this.tBars  := 0
    true
 
// ══════════════════════════════════════════════════════════════════════════════
// Persistent Tournament Engines & Live Visual Chart State
// ══════════════════════════════════════════════════════════════════════════════
var SimEngine simBal    = SimEngine.new(8,  1.00, array.new<Pool>(), array.new<Pool>())
var SimEngine simScalp  = SimEngine.new(6,  0.95, array.new<Pool>(), array.new<Pool>())
var SimEngine simStrict = SimEngine.new(10, 1.05, array.new<Pool>(), array.new<Pool>())
 
var array<Pool>     liveBsl    = array.new<Pool>()
var array<Pool>     liveSsl    = array.new<Pool>()
var array<PlanDraw> plans      = array.new<PlanDraw>()
var array<line>     poolRays   = array.new<line>()
var array<label>    poolTags   = array.new<label>()
 
var int      st         = 0
var int      dir        = 0
var int      age        = 0
var float    poolPx     = na
var float    swpExt     = na
var float    trigPx     = na
var int      trigT      = na
var float    legHi      = na
var float    legLo      = na
var float    curScore   = na
var box      curSwpBox  = na
var line     curTrigLn  = na
var line     curChochLn = na
var label    curChochLb = na
var box      curPbBox   = na
 
var float    tEn        = na
var float    tSl        = na
var float    tTp1       = na
var float    tTp2       = na
var float    tTp3       = na
var float    tRisk      = na
var bool     tp2Mag     = false
var int      tStage     = 0
var float    tR         = 0.0
var int      tBars      = 0
var int      tRight     = na
var PlanDraw curPlan    = na
 
var int      nTrades    = 0
var int      nWins      = 0
var float    netR       = 0.0
var float    grossW     = 0.0
var float    grossL     = 0.0
var int      nTp1       = 0
var int      nTp2       = 0
var int      nTp3       = 0
var string   lastSig    = "—"
var float    lastScore  = na
var int      activeIdx  = 0      // 0 Balanced, 1 Scalp Fast, 2 Swing Strict
 
// Per-bar alert & screener flags
bool evSweepBull = false
bool evSweepBear = false
bool evChochBull = false
bool evChochBear = false
bool evBuy       = false
bool evSell      = false
bool evTp1Hit    = false
bool evSlHit     = false
int  sigPlot     = 0
 
// ══════════════════════════════════════════════════════════════════════════════
// Confirmed-Bar Execution (100% Non-Repainting, Zero Orphan Clutter)
// ══════════════════════════════════════════════════════════════════════════════
if barstate.isconfirmed and not na(atr) and atr > 0
    simBal.stepSim(ph8, pl8, time[8], atr, hi3, lo3, entryIn, trendIn, slModeIn, slValIn, beIn, tp1RIn, tp2RIn, tp3RIn, effIn, ema50, ema200)
    simScalp.stepSim(ph6, pl6, time[6], atr, hi3, lo3, entryIn, trendIn, slModeIn, slValIn, beIn, tp1RIn, tp2RIn, tp3RIn, effIn, ema50, ema200)
    simStrict.stepSim(ph10, pl10, time[10], atr, hi3, lo3, entryIn, trendIn, slModeIn, slValIn, beIn, tp1RIn, tp2RIn, tp3RIn, effIn, ema50, ema200)
 
    if st == 0
        if profIn == ProfSel.bal
            activeIdx := 0
        else if profIn == ProfSel.scalp
            activeIdx := 1
        else if profIn == ProfSel.strict
            activeIdx := 2
        else
            float bestAvg = -1e9
            int   bestI   = 0
            if simBal.nTrades >= 4
                float a0 = simBal.netR / simBal.nTrades
                if a0 > bestAvg
                    bestAvg := a0
                    bestI   := 0
            if simScalp.nTrades >= 4
                float a1 = simScalp.netR / simScalp.nTrades
                if a1 > bestAvg
                    bestAvg := a1
                    bestI   := 1
            if simStrict.nTrades >= 4
                float a2 = simStrict.netR / simStrict.nTrades
                if a2 > bestAvg
                    bestAvg := a2
                    bestI   := 2
            activeIdx := bestI
 
    int   liveExtLen = activeIdx == 1 ? 6 : activeIdx == 2 ? 10 : 8
    float liveEffMin = activeIdx == 1 ? 0.95 : activeIdx == 2 ? 1.05 : 1.00
    float livePh     = activeIdx == 1 ? ph6 : activeIdx == 2 ? ph10 : ph8
    float livePl     = activeIdx == 1 ? pl6 : activeIdx == 2 ? pl10 : pl8
    int   livePivT   = activeIdx == 1 ? time[6] : activeIdx == 2 ? time[10] : time[8]
 
    // 1. Register confirmed BSL / SSL liquidity pools
    if not na(livePh)
        bool okH = true
        for k = 0 to liveExtLen - 1
            if high[k] > livePh
                okH := false
        if okH
            array.push(liveBsl, Pool.new(livePh, livePivT))
            if array.size(liveBsl) > 6
                array.shift(liveBsl)
    if not na(livePl)
        bool okL = true
        for k = 0 to liveExtLen - 1
            if low[k] < livePl
                okL := false
        if okL
            array.push(liveSsl, Pool.new(livePl, livePivT))
            if array.size(liveSsl) > 6
                array.shift(liveSsl)
 
    // 2. Manage Active Live Trade (State 3 — Stop-First Intrabar Accounting)
    if st == 3
        tBars += 1
        bool   isL     = dir == 1
        bool   slHit   = isL ? low <= tSl : high >= tSl
        bool   closed  = false
        string exitTag = "STOP"
        if slHit
            float rem = tStage == 0 ? 1.0 : tStage == 1 ? 0.5 : 0.2
            tR     += rem * ((tSl - tEn) * dir) / tRisk
            closed := true
            if tStage == 0
                evSlHit := true
            else
                exitTag := beIn and math.abs(tSl - tEn) <= syminfo.mintick ? "BE" : "TRAIL"
            if not na(curPlan)
                if not na(curPlan.sLb)
                    label.set_text(curPlan.sLb, tStage == 0 ? "SL ✕" : "SL (BE)")
                if not na(curPlan.riskB)
                    box.set_bgcolor(curPlan.riskB, color.new(bearC, 78))
        else
            if tStage == 0 and (isL ? high >= tTp1 : low <= tTp1)
                tStage   := 1
                tR       += 0.5 * (math.abs(tTp1 - tEn) / tRisk)
                nTp1     += 1
                evTp1Hit := true
                if beIn
                    tSl := tEn
                    if not na(curPlan) and not na(curPlan.sLb)
                        label.set_text(curPlan.sLb, "SL → BE")
                if not na(curPlan)
                    if not na(curPlan.t1L)
                        line.set_color(curPlan.t1L, bullC)
                        line.set_width(curPlan.t1L, 2)
                    if not na(curPlan.t1Lb)
                        label.set_text(curPlan.t1Lb, "TP1 ✓")
            if tStage == 1 and (isL ? high >= tTp2 : low <= tTp2)
                tStage := 2
                tR     += 0.3 * (math.abs(tTp2 - tEn) / tRisk)
                nTp2   += 1
                if not na(curPlan)
                    if not na(curPlan.t2L)
                        line.set_color(curPlan.t2L, bullC)
                        line.set_width(curPlan.t2L, 2)
                    if not na(curPlan.t2Lb)
                        label.set_text(curPlan.t2Lb, tp2Mag ? "TP2 · MAG ✓" : "TP2 ✓")
            if tStage == 2 and (isL ? high >= tTp3 : low <= tTp3)
                tStage  := 3
                tR      += 0.2 * (math.abs(tTp3 - tEn) / tRisk)
                nTp3    += 1
                exitTag := "TP3"
                closed  := true
                if not na(curPlan)
                    if not na(curPlan.t3L)
                        line.set_color(curPlan.t3L, bullC)
                        line.set_width(curPlan.t3L, 2)
                    if not na(curPlan.t3Lb)
                        label.set_text(curPlan.t3Lb, "TP3 ✓")
            if not closed and tBars >= 80
                float rem = tStage == 0 ? 1.0 : tStage == 1 ? 0.5 : 0.2
                tR      += rem * ((close - tEn) * dir) / tRisk
                exitTag := "TIME"
                closed  := true
 
        tRight := closed ? time : math.max(tRight, time + 4 * barMs)
        if not na(curPlan)
            if not na(curPlan.riskB)
                box.set_right(curPlan.riskB, tRight)
            if not na(curPlan.rewB)
                box.set_right(curPlan.rewB, tRight)
            if not na(curPlan.eL)
                line.set_x2(curPlan.eL, tRight)
            if not na(curPlan.sL)
                line.set_x2(curPlan.sL, tRight)
            if not na(curPlan.t1L)
                line.set_x2(curPlan.t1L, tRight)
            if not na(curPlan.t2L)
                line.set_x2(curPlan.t2L, tRight)
            if not na(curPlan.t3L)
                line.set_x2(curPlan.t3L, tRight)
            int lbX = closed ? tRight + barMs : tRight
            if not na(curPlan.eLb)
                label.set_x(curPlan.eLb, lbX)
            if not na(curPlan.sLb)
                label.set_x(curPlan.sLb, lbX)
            if not na(curPlan.t1Lb)
                label.set_x(curPlan.t1Lb, lbX)
            if not na(curPlan.t2Lb)
                label.set_x(curPlan.t2Lb, lbX)
            if not na(curPlan.t3Lb)
                label.set_x(curPlan.t3Lb, lbX)
 
        if closed
            if not na(curPlan)
                string rStr = (tR >= 0 ? "+" : "") + str.tostring(tR, "#.#") + "R · " + exitTag
                color  rCol = tR >= 0 ? bullC : bearC
                bool   placeAbove = (dir == 1) == (tR >= 0)
                curPlan.resLb := label.new(time, placeAbove ? high + 0.45 * atr : low - 0.45 * atr, rStr, xloc = xloc.bar_time, yloc = yloc.price, style = placeAbove ? label.style_label_down : label.style_label_up, color = color.new(rCol, 8), textcolor = #0B0E14, size = size.small, text_formatting = text.format_bold)
            nTrades += 1
            if tStage >= 1
                nWins += 1
            netR += tR
            if tR >= 0
                grossW += tR
            else
                grossL += math.abs(tR)
            curPlan := na
            st      := 0
            dir     := 0
 
    // 3. Detect Sweeps of Live SSL / BSL Pools
    float sweptSsl  = na
    int   sweptSslT = na
    if array.size(liveSsl) > 0
        for i = array.size(liveSsl) - 1 to 0
            Pool p = array.get(liveSsl, i)
            if low < p.price
                if na(sweptSsl) or p.price < sweptSsl
                    sweptSsl  := p.price
                    sweptSslT := p.pivTime
                array.remove(liveSsl, i)
 
    float sweptBsl  = na
    int   sweptBslT = na
    if array.size(liveBsl) > 0
        for i = array.size(liveBsl) - 1 to 0
            Pool p = array.get(liveBsl, i)
            if high > p.price
                if na(sweptBsl) or p.price > sweptBsl
                    sweptBsl  := p.price
                    sweptBslT := p.pivTime
                array.remove(liveBsl, i)
 
    bool effOk      = not effIn or effort >= liveEffMin
    bool fireSignal = false
    int  fireDir    = 0
 
    // 4. State 2 — CHoCH Confirmed, Monitoring Optimal Pullback Zone
    if st == 2
        age += 1
        bool isL = dir == 1
        bool inv = isL ? close < swpExt : close > swpExt
        if inv or age > 8
            box.delete(curSwpBox)
            line.delete(curChochLn)
            label.delete(curChochLb)
            box.delete(curPbBox)
            curSwpBox  := na
            curChochLn := na
            curChochLb := na
            curPbBox   := na
            st         := 0
            dir        := 0
        else
            if isL
                legHi := math.max(legHi, high)
            else
                legLo := math.min(legLo, low)
            float pbEdge = isL ? legLo + 0.60 * (legHi - legLo) : legHi - 0.60 * (legHi - legLo)
            if not na(curPbBox)
                box.set_right(curPbBox, time)
                box.set_top(curPbBox, math.max(pbEdge, poolPx))
                box.set_bottom(curPbBox, math.min(pbEdge, poolPx))
            bool touched = isL ? low <= pbEdge : high >= pbEdge
            bool held    = isL ? (close > open and close > poolPx) : (close < open and close < poolPx)
            if touched and held and f_trendOk(dir, trendIn, close, ema50, ema200)
                fireSignal := true
                fireDir    := dir
 
    // 5. State 1 — Liquidity Sweep Armed, Monitoring CHoCH Trigger Break
    else if st == 1
        age += 1
        bool isL = dir == 1
        if isL
            swpExt := math.min(swpExt, low)
            if not na(curSwpBox)
                box.set_right(curSwpBox, time)
                box.set_bottom(curSwpBox, math.min(swpExt, poolPx - 0.08 * atr))
            if not na(curTrigLn)
                line.set_x2(curTrigLn, time)
            if close < poolPx - 1.0 * atr or age > 6
                box.delete(curSwpBox)
                line.delete(curTrigLn)
                curSwpBox := na
                curTrigLn := na
                st        := 0
                dir       := 0
            else if close > trigPx and close > open and effOk
                evChochBull := true
                line.delete(curTrigLn)
                curTrigLn := na
                if shChochIn
                    curChochLn := line.new(trigT, trigPx, time, trigPx, xloc = xloc.bar_time, color = swpC, style = line.style_dashed, width = 2)
                    curChochLb := label.new(time, trigPx, "CHoCH ▲", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_down, color = color.new(swpC, 82), textcolor = swpC, size = size.tiny, text_formatting = text.format_bold)
                if entryIn == EntryStyle.immediate
                    if (close - swpExt) <= 1.8 * atr and f_trendOk(1, trendIn, close, ema50, ema200)
                        fireSignal := true
                        fireDir    := 1
                    else
                        box.delete(curSwpBox)
                        line.delete(curChochLn)
                        label.delete(curChochLb)
                        curSwpBox  := na
                        curChochLn := na
                        curChochLb := na
                        st         := 0
                        dir        := 0
                else
                    st    := 2
                    age   := 0
                    legLo := swpExt
                    legHi := high
                    if shSwpIn
                        float pbEdge = legLo + 0.60 * (legHi - legLo)
                        curPbBox := box.new(time, math.max(pbEdge, poolPx), time + 3 * barMs, math.min(pbEdge, poolPx), xloc = xloc.bar_time, border_color = color.new(swpC, 45), border_style = line.style_dotted, bgcolor = color.new(swpC, 91))
        else
            swpExt := math.max(swpExt, high)
            if not na(curSwpBox)
                box.set_right(curSwpBox, time)
                box.set_top(curSwpBox, math.max(swpExt, poolPx + 0.08 * atr))
            if not na(curTrigLn)
                line.set_x2(curTrigLn, time)
            if close > poolPx + 1.0 * atr or age > 6
                box.delete(curSwpBox)
                line.delete(curTrigLn)
                curSwpBox := na
                curTrigLn := na
                st        := 0
                dir       := 0
            else if close < trigPx and close < open and effOk
                evChochBear := true
                line.delete(curTrigLn)
                curTrigLn := na
                if shChochIn
                    curChochLn := line.new(trigT, trigPx, time, trigPx, xloc = xloc.bar_time, color = bslCol, style = line.style_dashed, width = 2)
                    curChochLb := label.new(time, trigPx, "CHoCH ▼", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_up, color = color.new(bslCol, 82), textcolor = bslCol, size = size.tiny, text_formatting = text.format_bold)
                if entryIn == EntryStyle.immediate
                    if (swpExt - close) <= 1.8 * atr and f_trendOk(-1, trendIn, close, ema50, ema200)
                        fireSignal := true
                        fireDir    := -1
                    else
                        box.delete(curSwpBox)
                        line.delete(curChochLn)
                        label.delete(curChochLb)
                        curSwpBox  := na
                        curChochLn := na
                        curChochLb := na
                        st         := 0
                        dir        := 0
                else
                    st    := 2
                    age   := 0
                    legHi := swpExt
                    legLo := low
                    if shSwpIn
                        float pbEdge = legHi - 0.60 * (legHi - legLo)
                        curPbBox := box.new(time, math.max(pbEdge, poolPx), time + 3 * barMs, math.min(pbEdge, poolPx), xloc = xloc.bar_time, border_color = color.new(bslCol, 45), border_style = line.style_dotted, bgcolor = color.new(bslCol, 91))
 
    // 6. State 0 — Detect Fresh SSL / BSL Liquidity Sweep
    if st == 0 and not fireSignal
        if not na(sweptSsl) and close >= sweptSsl - 1.0 * atr and not na(hi3)
            evSweepBull := true
            st          := 1
            dir         := 1
            age         := 0
            poolPx      := sweptSsl
            swpExt      := low
            trigPx      := hi3
            trigT       := time[3]
            bool al     = close > ema200 and ema50 >= ema200
            curScore    := f_score((sweptSsl - low) / atr, effort, bodyFrac, lwRatio, al)
            if shSwpIn
                int leftT = math.max(sweptSslT, time - 8 * barMs)
                curSwpBox := box.new(leftT, sweptSsl, time, math.min(low, sweptSsl - 0.08 * atr), xloc = xloc.bar_time, border_color = color.new(swpC, 30), bgcolor = color.new(swpC, 86), border_width = 1, text = "SSL SWEPT", text_size = size.tiny, text_color = swpC, text_halign = text.align_left, text_valign = text.align_bottom)
            if shChochIn
                curTrigLn := line.new(trigT, trigPx, time + 3 * barMs, trigPx, xloc = xloc.bar_time, color = color.new(swpC, 35), style = line.style_dotted, width = 1)
            if close > hi3 and close > open and effOk
                evChochBull := true
                line.delete(curTrigLn)
                curTrigLn := na
                if shChochIn
                    curChochLn := line.new(trigT, trigPx, time, trigPx, xloc = xloc.bar_time, color = swpC, style = line.style_dashed, width = 2)
                    curChochLb := label.new(time, trigPx, "CHoCH ▲", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_down, color = color.new(swpC, 82), textcolor = swpC, size = size.tiny, text_formatting = text.format_bold)
                if entryIn == EntryStyle.immediate
                    if (close - low) <= 1.8 * atr and f_trendOk(1, trendIn, close, ema50, ema200)
                        fireSignal := true
                        fireDir    := 1
                    else
                        box.delete(curSwpBox)
                        line.delete(curChochLn)
                        label.delete(curChochLb)
                        curSwpBox  := na
                        curChochLn := na
                        curChochLb := na
                        st         := 0
                        dir        := 0
                else
                    st    := 2
                    age   := 0
                    legLo := low
                    legHi := high
                    if shSwpIn
                        float pbEdge = legLo + 0.60 * (legHi - legLo)
                        curPbBox := box.new(time, math.max(pbEdge, poolPx), time + 3 * barMs, math.min(pbEdge, poolPx), xloc = xloc.bar_time, border_color = color.new(swpC, 45), border_style = line.style_dotted, bgcolor = color.new(swpC, 91))
 
        else if not na(sweptBsl) and close <= sweptBsl + 1.0 * atr and not na(lo3)
            evSweepBear := true
            st          := 1
            dir         := -1
            age         := 0
            poolPx      := sweptBsl
            swpExt      := high
            trigPx      := lo3
            trigT       := time[3]
            bool al     = close < ema200 and ema50 <= ema200
            curScore    := f_score((high - sweptBsl) / atr, effort, bodyFrac, uwRatio, al)
            if shSwpIn
                int leftT = math.max(sweptBslT, time - 8 * barMs)
                curSwpBox := box.new(leftT, math.max(high, sweptBsl + 0.08 * atr), time, sweptBsl, xloc = xloc.bar_time, border_color = color.new(bslCol, 30), bgcolor = color.new(bslCol, 86), border_width = 1, text = "BSL SWEPT", text_size = size.tiny, text_color = bslCol, text_halign = text.align_left, text_valign = text.align_top)
            if shChochIn
                curTrigLn := line.new(trigT, trigPx, time + 3 * barMs, trigPx, xloc = xloc.bar_time, color = color.new(bslCol, 35), style = line.style_dotted, width = 1)
            if close < lo3 and close < open and effOk
                evChochBear := true
                line.delete(curTrigLn)
                curTrigLn := na
                if shChochIn
                    curChochLn := line.new(trigT, trigPx, time, trigPx, xloc = xloc.bar_time, color = bslCol, style = line.style_dashed, width = 2)
                    curChochLb := label.new(time, trigPx, "CHoCH ▼", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_up, color = color.new(bslCol, 82), textcolor = bslCol, size = size.tiny, text_formatting = text.format_bold)
                if entryIn == EntryStyle.immediate
                    if (high - close) <= 1.8 * atr and f_trendOk(-1, trendIn, close, ema50, ema200)
                        fireSignal := true
                        fireDir    := -1
                    else
                        box.delete(curSwpBox)
                        line.delete(curChochLn)
                        label.delete(curChochLb)
                        curSwpBox  := na
                        curChochLn := na
                        curChochLb := na
                        st         := 0
                        dir        := 0
                else
                    st    := 2
                    age   := 0
                    legHi := high
                    legLo := low
                    if shSwpIn
                        float pbEdge = legHi - 0.60 * (legHi - legLo)
                        curPbBox := box.new(time, math.max(pbEdge, poolPx), time + 3 * barMs, math.min(pbEdge, poolPx), xloc = xloc.bar_time, border_color = color.new(bslCol, 45), border_style = line.style_dotted, bgcolor = color.new(bslCol, 91))
 
    // 7. Confirmed Entry Signal -> Transfer Setup Drawings to Position-Tool Trade Plan
    if fireSignal
        bool  isL  = fireDir == 1
        float en   = close
        float rawD = isL ? (en - (swpExt - slValIn * atr)) : ((swpExt + slValIn * atr) - en)
        float dist = slModeIn == SlType.atrMult ? slValIn * atr : f_clamp(rawD, 0.6 * atr, 3.0 * atr)
        if dist > syminfo.mintick
            tEn    := en
            tRisk  := dist
            tSl    := en - fireDir * dist
            tTp1   := en + fireDir * tp1RIn * dist
            tTp2   := en + fireDir * tp2RIn * dist
            tTp3   := en + fireDir * tp3RIn * dist
            tp2Mag := false
 
            if magIn
                float bestPool = na
                float bestGap  = 1e18
                if isL and array.size(liveBsl) > 0
                    for i = 0 to array.size(liveBsl) - 1
                        float px = array.get(liveBsl, i).price
                        if px > tTp1 + 0.2 * dist and px < tTp3 - 0.2 * dist and (px - en) < bestGap
                            bestGap  := px - en
                            bestPool := px
                if not isL and array.size(liveSsl) > 0
                    for i = 0 to array.size(liveSsl) - 1
                        float px = array.get(liveSsl, i).price
                        if px < tTp1 - 0.2 * dist and px > tTp3 + 0.2 * dist and (en - px) < bestGap
                            bestGap  := en - px
                            bestPool := px
                if not na(bestPool)
                    tTp2   := bestPool - fireDir * 0.04 * atr
                    tp2Mag := true
 
            tStage    := 0
            tR        := 0.0
            tBars     := 0
            tRight    := time + 18 * barMs
            st        := 3
            dir       := fireDir
            evBuy     := isL
            evSell    := not isL
            sigPlot   := fireDir
            lastSig   := isL ? "BUY" : "SELL"
            lastScore := curScore
 
            PlanDraw pd = PlanDraw.new()
            pd.swpB    := curSwpBox
            pd.chochLn := curChochLn
            pd.chochLb := curChochLb
            pd.pbB     := curPbBox
            if not na(curPbBox)
                box.set_right(curPbBox, time)
            curSwpBox  := na
            curChochLn := na
            curChochLb := na
            curPbBox   := na
 
            color  sigCol  = isL ? bullC : bearC
            string modeTag = entryIn == EntryStyle.pullback ? "CHoCH · PB" : "CHoCH"
            string sigTxt  = (isL ? "BUY" : "SELL") + "\n" + modeTag + (not na(curScore) ? " " + str.tostring(math.round(curScore)) + "%" : "")
            pd.sigLb := label.new(time, isL ? low - 0.22 * atr : high + 0.22 * atr, sigTxt, xloc = xloc.bar_time, yloc = yloc.price, style = isL ? label.style_label_up : label.style_label_down, color = sigCol, textcolor = #0B0E14, size = size.small, text_formatting = text.format_bold)
 
            if shSlIn
                pd.riskB := box.new(time, math.max(tEn, tSl), tRight, math.min(tEn, tSl), xloc = xloc.bar_time, bgcolor = color.new(bearC, 86), border_color = color.new(bearC, 100))
                pd.sL    := line.new(time, tSl, tRight, tSl, xloc = xloc.bar_time, color = bearC, width = 2)
                pd.sLb   := label.new(tRight, tSl, "SL " + str.tostring(tSl, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bearC, size = size.small)
            if shEnIn
                pd.eL    := line.new(time, tEn, tRight, tEn, xloc = xloc.bar_time, color = chart.fg_color, width = 2)
                pd.eLb   := label.new(tRight, tEn, "ENTRY " + str.tostring(tEn, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.small)
            if shTpIn
                pd.rewB  := box.new(time, math.max(tEn, tTp3), tRight, math.min(tEn, tTp3), xloc = xloc.bar_time, bgcolor = color.new(bullC, 90), border_color = color.new(bullC, 100))
                pd.t1L   := line.new(time, tTp1, tRight, tTp1, xloc = xloc.bar_time, color = color.new(bullC, 35), width = 1)
                pd.t2L   := line.new(time, tTp2, tRight, tTp2, xloc = xloc.bar_time, color = color.new(bullC, 35), width = 1, style = tp2Mag ? line.style_dashed : line.style_solid)
                pd.t3L   := line.new(time, tTp3, tRight, tTp3, xloc = xloc.bar_time, color = color.new(bullC, 35), width = 1)
                float rr1 = math.abs(tTp1 - tEn) / tRisk
                float rr2 = math.abs(tTp2 - tEn) / tRisk
                float rr3 = math.abs(tTp3 - tEn) / tRisk
                pd.t1Lb  := label.new(tRight, tTp1, "TP1 " + str.tostring(rr1, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
                pd.t2Lb  := label.new(tRight, tTp2, "TP2 " + str.tostring(rr2, "#.#") + "R" + (tp2Mag ? " · MAG" : ""), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
                pd.t3Lb  := label.new(tRight, tTp3, "TP3 " + str.tostring(rr3, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = bullC, size = size.small)
 
            curPlan := pd
            array.push(plans, pd)
            while array.size(plans) > histIn
                PlanDraw oldP = array.shift(plans)
                oldP.cleanup()
        else
            box.delete(curSwpBox)
            line.delete(curChochLn)
            label.delete(curChochLb)
            box.delete(curPbBox)
            curSwpBox  := na
            curChochLn := na
            curChochLb := na
            curPbBox   := na
            st         := 0
            dir        := 0
 
// ══════════════════════════════════════════════════════════════════════════════
// Active BSL / SSL Pool Rays on Last Bar (Delete-Then-Recreate, Zero Leak)
// ══════════════════════════════════════════════════════════════════════════════
if barstate.islast
    while array.size(poolRays) > 0
        line.delete(array.pop(poolRays))
    while array.size(poolTags) > 0
        label.delete(array.pop(poolTags))
 
    if shPoolIn
        int rEnd = time + 6 * barMs
        int bCnt = array.size(liveBsl)
        if bCnt > 0
            int startB = math.max(0, bCnt - 3)
            for i = startB to bCnt - 1
                Pool p = array.get(liveBsl, i)
                line ln = line.new(p.pivTime, p.price, rEnd, p.price, xloc = xloc.bar_time, color = color.new(bslCol, 45), style = line.style_dotted, width = 1)
                label lb = label.new(rEnd, p.price, "BSL " + str.tostring(p.price, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(bslCol, 20), size = size.tiny)
                array.push(poolRays, ln)
                array.push(poolTags, lb)
        int sCnt = array.size(liveSsl)
        if sCnt > 0
            int startS = math.max(0, sCnt - 3)
            for i = startS to sCnt - 1
                Pool p = array.get(liveSsl, i)
                line ln = line.new(p.pivTime, p.price, rEnd, p.price, xloc = xloc.bar_time, color = color.new(swpC, 45), style = line.style_dotted, width = 1)
                label lb = label.new(rEnd, p.price, "SSL " + str.tostring(p.price, format.mintick), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(swpC, 20), size = size.tiny)
                array.push(poolRays, ln)
                array.push(poolTags, lb)
 
// ══════════════════════════════════════════════════════════════════════════════
// Pine Screener & Data Window Plots (First 6 Plots for Screener Indexing)
// ══════════════════════════════════════════════════════════════════════════════
plot(sigPlot, "Confirmed Signal (+1 Buy / -1 Sell)", display = display.data_window + display.pine_screener)
plot(st, "State (0 Idle / 1 Sweep / 2 CHoCH / 3 Plan)", display = display.data_window + display.pine_screener)
plot(curScore, "Setup Quality Score (0-100)", display = display.data_window + display.pine_screener)
plot(evSweepBull ? 1 : evSweepBear ? -1 : 0, "Liquidity Sweep (+1 SSL / -1 BSL)", display = display.data_window + display.pine_screener)
plot(evChochBull ? 1 : evChochBear ? -1 : 0, "CHoCH Break (+1 Bull / -1 Bear)", display = display.data_window + display.pine_screener)
plot(netR, "Cumulative Net R", display = display.data_window + display.pine_screener)
 
// Subtle Trend Baseline & Mandatory Invisible Price Scale Anchors
plot(trendIn != TrendGate.off ? ema200 : na, "EMA 200 Baseline", color = color.new(chart.fg_color, 78), linewidth = 1)
plot(high, "Price Scale High Anchor", color = color.new(color.white, 100), display = display.pane, editable = false)
plot(low, "Price Scale Low Anchor", color = color.new(color.white, 100), display = display.pane, editable = false)
 
// ══════════════════════════════════════════════════════════════════════════════
// Built-In Alerts
// ══════════════════════════════════════════════════════════════════════════════
alertcondition(evBuy, "1. Bullish Sweep + CHoCH Entry (BUY)", "LSCTZ [PhenLabs]: Confirmed BUY Trade Plan on {{ticker}} ({{interval}}) @ {{close}}")
alertcondition(evSell, "2. Bearish Sweep + CHoCH Entry (SELL)", "LSCTZ [PhenLabs]: Confirmed SELL Trade Plan on {{ticker}} ({{interval}}) @ {{close}}")
alertcondition(evBuy or evSell, "3. Any Confirmed Trade Plan (BUY or SELL)", "LSCTZ [PhenLabs]: Confirmed Trade Plan triggered on {{ticker}} ({{interval}}) @ {{close}}")
alertcondition(evChochBull or evChochBear, "4. CHoCH Structure Break Armed", "LSCTZ [PhenLabs]: Liquidity Sweep + CHoCH break confirmed on {{ticker}} ({{interval}})")
alertcondition(evSweepBull or evSweepBear, "5. BSL / SSL Liquidity Pool Swept", "LSCTZ [PhenLabs]: External Liquidity Pool swept on {{ticker}} ({{interval}})")
alertcondition(evTp1Hit, "6. Target 1 (TP1) Reached", "LSCTZ [PhenLabs]: TP1 reached on {{ticker}} ({{interval}})")
alertcondition(evSlHit, "7. Stop Loss Hit", "LSCTZ [PhenLabs]: Stop Loss hit on {{ticker}} ({{interval}})")
 
// ══════════════════════════════════════════════════════════════════════════════
// Compact Top-Right Telemetry Dashboard
// ══════════════════════════════════════════════════════════════════════════════
string tblSz = tblSzIn == TblSz.tiny ? size.tiny : tblSzIn == TblSz.small ? size.small : size.normal
var table dash = table.new(position.top_right, 2, 10, bgcolor = color.new(chart.bg_color, 8), border_color = color.new(chart.fg_color, 82), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
 
f_row(table tb, int r, string k, string v, color vc, string sz) =>
    table.cell(tb, 0, r, k, text_color = color.new(chart.fg_color, 32), text_size = sz, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = vc, text_size = sz, text_halign = text.align_left)
    true
 
if barstate.islast
    table.clear(dash, 0, 0, 1, 9)
    if shTblIn
        color  fgC     = chart.fg_color
        string actName = activeIdx == 1 ? "Scalp Fast" : activeIdx == 2 ? "Swing Strict" : "Balanced"
        string profTxt = (profIn == ProfSel.auto ? "Auto → " + actName : actName) + " · " + (entryIn == EntryStyle.pullback ? "Pullback" : "Immediate")
 
        bool   bullReg = trendIn == TrendGate.aligned ? (close > ema200 and ema50 >= ema200) : close > ema200
        bool   bearReg = trendIn == TrendGate.aligned ? (close < ema200 and ema50 <= ema200) : close < ema200
        string trTxt   = trendIn == TrendGate.off ? "OFF · All Reversals" : bullReg ? "BULLISH · Longs Active" : bearReg ? "BEARISH · Shorts Active" : "TRANSITION · Neutral"
        color  trCol   = trendIn == TrendGate.off ? color.new(fgC, 30) : bullReg ? bullC : bearReg ? bearC : bslCol
 
        string stTxt = st == 3 ? (dir == 1 ? "LONG @ " : "SHORT @ ") + str.tostring(tEn, format.mintick) + (tStage >= 1 ? " · TP" + str.tostring(tStage) + " ✓" : "") : st == 2 ? (dir == 1 ? "BULL CHoCH · Pullback" : "BEAR CHoCH · Pullback") : st == 1 ? (dir == 1 ? "SSL SWEPT · Wait CHoCH" : "BSL SWEPT · Wait CHoCH") : "SCANNING POOLS"
        color  stCol = st == 3 ? (dir == 1 ? bullC : bearC) : st == 2 ? (dir == 1 ? swpC : bslCol) : st == 1 ? (dir == 1 ? swpC : bslCol) : color.new(fgC, 35)
 
        string sigTxt = lastSig == "—" ? "—" : lastSig + " · CHoCH" + (not na(lastScore) ? " (" + str.tostring(math.round(lastScore)) + "%)" : "")
        color  sigCol = lastSig == "BUY" ? bullC : lastSig == "SELL" ? bearC : color.new(fgC, 40)
 
        string wrTxt  = nTrades > 0 ? str.tostring(100.0 * nWins / nTrades, "#.#") + "% (" + str.tostring(nWins) + "W / " + str.tostring(nTrades - nWins) + "L)" : "—"
        float  pf     = grossL > 0 ? grossW / grossL : grossW > 0 ? 9.99 : 0.0
        string nrTxt  = nTrades > 0 ? (netR >= 0 ? "+" : "") + str.tostring(netR, "#.#") + "R" + (grossL > 0 ? " · PF " + str.tostring(pf, "#.##") : "") : "—"
 
        float nearBsl = array.size(liveBsl) > 0 ? array.get(liveBsl, array.size(liveBsl) - 1).price : na
        float nearSsl = array.size(liveSsl) > 0 ? array.get(liveSsl, array.size(liveSsl) - 1).price : na
        string plTxt  = "BSL " + (na(nearBsl) ? "—" : str.tostring(nearBsl, format.mintick)) + " · SSL " + (na(nearSsl) ? "—" : str.tostring(nearSsl, format.mintick))
 
        table.cell(dash, 0, 0, "LIQUIDITY SWEEP & CHoCH", text_color = swpC, text_size = tblSz, text_formatting = text.format_bold)
        table.merge_cells(dash, 0, 0, 1, 0)
        f_row(dash, 1, "Profile", profTxt, fgC, tblSz)
        f_row(dash, 2, "Trend Bias", trTxt, trCol, tblSz)
        f_row(dash, 3, "State", stTxt, stCol, tblSz)
        f_row(dash, 4, "Last Signal", sigTxt, sigCol, tblSz)
        f_row(dash, 5, "Win Rate (TP1+)", wrTxt, fgC, tblSz)
        f_row(dash, 6, "Net Return", nrTxt, netR >= 0 ? bullC : bearC, tblSz)
        f_row(dash, 7, "Target Hits", "TP1: " + str.tostring(nTp1) + " · TP2: " + str.tostring(nTp2) + " · TP3: " + str.tostring(nTp3), fgC, tblSz)
        f_row(dash, 8, "Nearest Pools", plTxt, color.new(fgC, 20), tblSz)
        f_row(dash, 9, "Stop / Data", (slModeIn == SlType.atrMult ? str.tostring(slValIn, "#.##") + "× ATR" : "Wick + " + str.tostring(slValIn, "#.##") + " ATR") + " · " + (hasVol ? "VOLUME" : "RANGE"), color.new(fgC, 35), tblSz)

← 返回列表