Eye Squeeze Breakout [EyeAlgo]

eyealgo · study · 657 行 · 点赞 31 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EyeAlgo
 
//@version=6
indicator("Eye Squeeze Breakout [EyeAlgo]", shorttitle = "Eye Squeeze Breakout", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ───────────────────────── Inputs
string G1 = "Squeeze"
int    sqLen   = input.int(20, "Length", minval = 5, group = G1)
int    baseLen = input.int(100, "Baseline length (bars)", minval = 20, group = G1, tooltip = "Compression = today's volatility divided by its own average over this many bars. 1.0 = normal, 0.5 = half of normal.")
float  thLow   = input.float(0.85, "Compression ≤  Low", minval = 0.1, maxval = 1.5, step = 0.05, group = G1, inline = "th")
float  thMid   = input.float(0.70, "Mid", minval = 0.1, maxval = 1.5, step = 0.05, group = G1, inline = "th")
float  thHigh  = input.float(0.55, "High", minval = 0.1, maxval = 1.5, step = 0.05, group = G1, inline = "th")
string fromLvl = input.string("Mid", "Squeeze counts from level", options = ["Low", "Mid", "High"], group = G1)
int    minSqz  = input.int(6, "Min squeeze bars", minval = 1, group = G1)
int    brkWin  = input.int(10, "Breakout window (bars after release)", minval = 1, group = G1)
 
string G1b = "Breakout filters"
bool   useMom  = input.bool(true, "Require drive agreement (breakout side)", group = G1b)
bool   useHtf  = input.bool(true, "Trade only with higher-TF trend", group = G1b, tooltip = "Breakouts against the higher-TF EMA trend are skipped (still measured in the Filter lab rows).")
string htfTf   = input.timeframe("240", "Higher-TF trend timeframe", group = G1b)
int    htfLen  = input.int(50, "Higher-TF EMA length", minval = 2, group = G1b)
bool   useSess = input.bool(false, "Signals only inside session", group = G1b)
string sess    = input.session("0000-2359", "Session (exchange time)", group = G1b)
 
string G1c = "Quality filters (tick to require)"
bool   reqDepth  = input.bool(false, "High squeeze depth only", group = G1c)
bool   reqBias   = input.bool(false, "Breakout with release bias", group = G1c)
bool   reqStrong = input.bool(false, "Strong breakout candle  ·  body ≥", group = G1c, inline = "st")
float  bodyMin   = input.float(0.5, "", minval = 0.1, maxval = 1.0, step = 0.05, group = G1c, inline = "st")
bool   reqVol    = input.bool(false, "Volume expansion  ·  × 20-bar avg", group = G1c, inline = "vo")
float  volMult   = input.float(1.2, "", minval = 0.5, step = 0.1, group = G1c, inline = "vo")
bool   reqTight  = input.bool(false, "Tight box  ·  height ≤ × ATR", group = G1c, inline = "ti")
float  tightAtr  = input.float(4.0, "", minval = 0.5, step = 0.5, group = G1c, inline = "ti")
 
string G2 = "Trade plan"
string entryMode  = input.string("Breakout close", "Entry", options = ["Breakout close", "Retest of box edge"], group = G2)
int    retestBars = input.int(5, "Retest window (bars)", minval = 1, group = G2)
string slMode     = input.string("Box middle", "Stop loss at", options = ["Box middle", "Box opposite side", "ATR"], group = G2)
float  slAtr      = input.float(1.5, "ATR stop multiplier (ATR mode)", minval = 0.1, step = 0.1, group = G2)
float  minSlAtr   = input.float(0.5, "Min stop distance (× ATR)", minval = 0.0, step = 0.1, group = G2)
float  tp1R       = input.float(1.0, "TP1 (R)", minval = 0.1, step = 0.1, group = G2)
float  tp2R       = input.float(2.0, "TP2 (R)", minval = 0.1, step = 0.1, group = G2)
float  tp3R       = input.float(3.0, "TP3 (R)", minval = 0.1, step = 0.1, group = G2)
bool   beTp1      = input.bool(false, "Move stop to entry after TP1", group = G2)
int    fakeBars   = input.int(3, "Fakeout check (bars)", minval = 1, group = G2)
int    maxBars    = input.int(60, "Max bars in trade", minval = 5, group = G2)
 
string G3 = "Visuals"
bool  showBox  = input.bool(true, "Show squeeze boxes", group = G3)
bool  showBias = input.bool(true, "Show release bias label", group = G3)
bool  showPlan = input.bool(true, "Show trade plan (Entry / SL / TP)", group = G3)
bool  showOut  = input.bool(true, "Show result labels", group = G3)
bool  showSkip = input.bool(true, "Mark filtered-out breakouts on the box", group = G3)
bool  showBg   = input.bool(true, "Tint background while squeeze is on", group = G3)
int   keepN    = input.int(30, "Setups kept on chart", minval = 1, maxval = 50, group = G3)
color lowCol   = input.color(#0EA5E9, "Low", group = G3, inline = "lv")
color midCol   = input.color(#D97706, "Mid", group = G3, inline = "lv")
color highCol  = input.color(#7C3AED, "High", group = G3, inline = "lv")
color upCol    = input.color(#16A34A, "Long", group = G3, inline = "c")
color dnCol    = input.color(#DC2626, "Short", group = G3, inline = "c")
color noCol    = input.color(#6B7280, "No breakout", group = G3, inline = "c")
 
string G4 = "Dashboard"
bool   showDash = input.bool(true, "Show dashboard", group = G4)
bool   compact  = input.bool(false, "Compact dashboard (key rows only)", group = G4)
string dPos     = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G4)
string dSize    = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = G4)
bool   showMtf  = input.bool(true, "Show multi-timeframe squeeze rows", group = G4)
string mtf1     = input.timeframe("60", "Timeframe 1", group = G4)
string mtf2     = input.timeframe("240", "Timeframe 2", group = G4)
string mtf3     = input.timeframe("D", "Timeframe 3", group = G4)
 
float  tp2v    = math.max(tp2R, tp1R)
float  tp3v    = math.max(tp3R, tp2v)
string ts      = dSize == "Tiny" ? size.tiny : dSize == "Normal" ? size.normal : size.small
int    minLvl  = fromLvl == "High" ? 3 : fromLvl == "Low" ? 1 : 2
bool   retest  = entryMode == "Retest of box edge"
 
// ───────────────────────── Types
type Setup
    box          bx
    label        brk
    array<line>  lns
    array<label> pl
    array<label> lbs
    bool         alive = true
 
type Trade
    int   dir
    float entry
    float sl
    float risk
    float tp1
    float tp2
    float tp3
    float top
    float bot
    int   sig
    int   start
    int   lvl    = 0
    int   bias   = 0
    int   fmask  = 0
    bool  taken  = true
    bool  live   = true
    bool  miss   = false
    bool  hit1   = false
    bool  hit2   = false
    bool  fake   = false
    float doneR  = 0.0
    float left   = 1.0
    Setup s
 
// ───────────────────────── Helpers
lvlName(int l) =>
    l == 3 ? "High" : l == 2 ? "Mid" : l == 1 ? "Low" : "None"
 
lvlCol(int l) =>
    l == 3 ? highCol : l == 2 ? midCol : l == 1 ? lowCol : noCol
 
boxTxt(int bars, int l) =>
    "Squeeze · " + str.tostring(bars) + " bars · " + lvlName(l)
 
tfLbl(string tf) =>
    int s = timeframe.in_seconds(tf)
    s < 60 ? str.tostring(s) + "s" : s < 86400 and s % 3600 != 0 ? str.tostring(s / 60, "0") + "m" : s < 86400 ? str.tostring(s / 3600, "0") + "H" : s == 86400 ? "D" : s == 604800 ? "W" : tf
 
killSetup(Setup s) =>
    if not na(s) and s.alive
        if not na(s.bx)
            s.bx.delete()
        if not na(s.brk)
            s.brk.delete()
        for l in s.lns
            l.delete()
        for b in s.pl
            b.delete()
        for b in s.lbs
            b.delete()
        s.alive := false
 
greyBox(Setup s, int bars, int l, int rightX) =>
    if not na(s) and s.alive and not na(s.bx)
        s.bx.set_right(rightX)
        s.bx.set_border_color(noCol)
        s.bx.set_bgcolor(color.new(noCol, 88))
        s.bx.set_text(boxTxt(bars, l) + " · no breakout")
 
fmtR(float r) =>
    (r >= 0 ? "+" : "") + str.tostring(r, "0.00") + "R"
 
pct(int a, int b) =>
    b > 0 ? str.tostring(100.0 * a / b, "0.0") + "%" : "–"
 
pctN(int a, int b) =>
    pct(a, b) + " (" + str.tostring(b) + ")"
 
avgRN(float s, int n) =>
    n > 0 ? fmtR(s / n) + " (" + str.tostring(n) + ")" : "–"
 
dirTxt(int d) =>
    d == 1 ? "LONG" : "SHORT"
 
// compression thresholds sorted so a wrong input order cannot break the depth logic (k1 = tightest = High)
float k1 = math.min(thHigh, thMid, thLow)
float k3 = math.max(thHigh, thMid, thLow)
float k2 = thHigh + thMid + thLow - k1 - k3
 
// Eye Compression: average of two ratios, each = current value / its own long-run average
//   1) candle range ratio  (how big the bars are now vs normal)
//   2) close dispersion ratio (how spread the closes are now vs normal)
f_comp() =>
    float rngNow = ta.sma(ta.tr(true), sqLen)
    float rngAvg = ta.sma(rngNow, baseLen)
    float sdNow  = ta.stdev(close, sqLen)
    float sdAvg  = ta.sma(sdNow, baseLen)
    rngAvg > 0 and sdAvg > 0 and rngNow > 0 and sdNow > 0 ? 0.5 * (rngNow / rngAvg + sdNow / sdAvg) : na
 
// Eye Drive: distance of price from its EMA in ATR units, lightly smoothed (+ = buyers in control, - = sellers)
f_drive() =>
    float a = ta.atr(sqLen)
    float e = ta.ema(close, sqLen)
    ta.ema(a > 0 ? (close - e) / a : 0.0, 5)
 
f_lvl(float c) =>
    na(c) ? 0 : c <= k1 ? 3 : c <= k2 ? 2 : c <= k3 ? 1 : 0
 
// squeeze level + drive of the last closed bar (used for the higher timeframes, no repaint)
f_sq() =>
    float c = f_comp()
    float m = f_drive()
    int   l = na(c) ? na : f_lvl(c)
    [l[1], m[1]]
 
// ───────────────────────── Core calculations
float atr     = ta.atr(14)
float comp    = f_comp()
int   lvl     = f_lvl(comp)
bool  sqzOn   = lvl >= minLvl
float mom     = f_drive()
float momPrev = mom[1]
float htfEma  = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead = barmerge.lookahead_on)
bool  htfOk   = timeframe.in_seconds(htfTf) >= timeframe.in_seconds(timeframe.period)
int   htfDir  = not htfOk or na(htfEma) ? 0 : close > htfEma ? 1 : -1
bool  inSess  = not useSess or timeframe.isdwm or not na(time(timeframe.period, sess))
float volAvg  = ta.sma(volume, 20)
bool  hasVol  = not na(volAvg) and volAvg > 0
bool  volExp  = hasVol and volume >= volMult * volAvg
float body    = math.abs(close - open)
float barRng  = high - low
 
string mtf1s = timeframe.in_seconds(mtf1) >= timeframe.in_seconds(timeframe.period) ? mtf1 : timeframe.period
string mtf2s = timeframe.in_seconds(mtf2) >= timeframe.in_seconds(timeframe.period) ? mtf2 : timeframe.period
string mtf3s = timeframe.in_seconds(mtf3) >= timeframe.in_seconds(timeframe.period) ? mtf3 : timeframe.period
[l1, m1] = request.security(syminfo.tickerid, mtf1s, f_sq(), lookahead = barmerge.lookahead_on)
[l2, m2] = request.security(syminfo.tickerid, mtf2s, f_sq(), lookahead = barmerge.lookahead_on)
[l3, m3] = request.security(syminfo.tickerid, mtf3s, f_sq(), lookahead = barmerge.lookahead_on)
 
// release bias: drive side + drive slope + close vs box middle + higher-TF trend
biasOf(float top, float bot) =>
    int sc = (mom > 0 ? 1 : mom < 0 ? -1 : 0) + (mom > momPrev ? 1 : mom < momPrev ? -1 : 0) + (close > (top + bot) / 2 ? 1 : -1) + htfDir
    sc > 0 ? 1 : sc < 0 ? -1 : 0
 
// ───────────────────────── State
var int   sqStart  = na
var float sqTop    = na
var float sqBot    = na
var int   sqMaxLvl = 0
var Setup curS     = na
var bool  armed    = false
var int   armBar   = na
var float aTop     = na
var float aBot     = na
var float aAtr     = na
var int   aBars    = 0
var int   aLvl     = 0
var int   aBias    = 0
var int   preBias  = 0
var int   rawDir   = 0
var Setup armS     = na
var array<Setup> setups = array.new<Setup>()
var array<Trade> trades = array.new<Trade>()
 
// stats: "taken" = trades that pass the filters; "all" = every breakout signal (no quality filter)
var int   nSqz    = 0
var int   nBrk    = 0
var int   nSkip   = 0
var int   nMiss   = 0
var int   nClosed = 0
var int   nT1     = 0
var int   nT2     = 0
var int   nT3     = 0
var int   nStop   = 0
var int   nFake   = 0
var int   nL      = 0
var int   nLT1    = 0
var int   nS      = 0
var int   nST1    = 0
var int   sqzSum  = 0
var float sumR    = 0.0
var int   nTime   = 0
var int   nExitN  = 0
var int   nExitOk = 0
var int   nW      = 0
var int   nWT1    = 0
var int   nA      = 0
var int   nAT1    = 0
var int   nAll    = 0
var float sumRAll = 0.0
var array<int>   lvN  = array.new<int>(4, 0)
var array<int>   lvT1 = array.new<int>(4, 0)
// filter lab: avg R of all breakouts (drive/session filters applied) with / without each quality factor
var array<int>   fNy  = array.new<int>(6, 0)
var array<int>   fNn  = array.new<int>(6, 0)
var array<float> fRy  = array.new<float>(6, 0.0)
var array<float> fRn  = array.new<float>(6, 0.0)
 
bool evStart = false
bool evReady = false
bool evRel   = false
bool evLong  = false
bool evShort = false
bool evTp1   = false
bool evStop  = false
bool evFake  = false
 
if barstate.isconfirmed
    // 1) Manage open trades (a new trade is first checked on the next bar)
    if trades.size() > 0
        for i = trades.size() - 1 to 0
            Trade t = trades.get(i)
            bool   closed = false
            string res    = ""
            float  px     = close
            float  fav    = t.dir == 1 ? high : low
            float  adv    = t.dir == 1 ? low : high
            float  fkBuf  = retest ? 0.1 * atr : 0.0 // retest entries sit on the box edge, so a fakeout needs a real close back inside
            if not t.live
                // retest mode: wait for price to come back to the box edge
                bool filled = t.dir * (adv - t.entry) <= 0
                if filled
                    t.live  := true
                    t.start := bar_index
                    if t.taken
                        alert("Eye Squeeze Breakout: retest entry FILLED (" + dirTxt(t.dir) + ") on " + syminfo.ticker + " " + timeframe.period + " at " + str.tostring(t.entry, format.mintick), alert.freq_once_per_bar_close)
                    if t.dir * (adv - t.sl) <= 0 // filled and stopped on the same bar (conservative); a gap through the stop fills at the open
                        px      := t.dir == 1 ? math.min(open, t.sl) : math.max(open, t.sl)
                        t.doneR := math.max(-1.0, t.dir * (px - t.entry) / t.risk)
                        t.left  := 0.0
                        closed  := true
                        res     := "Stop"
                        if t.taken
                            evStop := true
                            alert("Eye Squeeze Breakout: STOP hit (" + dirTxt(t.dir) + ") on " + syminfo.ticker + " " + timeframe.period + " at " + str.tostring(px, format.mintick), alert.freq_once_per_bar_close)
                else if t.dir * (fav - t.tp1) >= 0 or bar_index - t.sig >= retestBars
                    t.miss := true
                    closed := true
                    res    := "No retest"
            else
                // fakeout: close back inside the box within the check window (counted even if the stop is hit on the same bar)
                if not t.fake and not t.hit1 and bar_index - t.start <= fakeBars and (t.dir == 1 ? close < t.top - fkBuf : close > t.bot + fkBuf)
                    t.fake := true
                    if t.taken
                        evFake := true
                        alert("Eye Squeeze Breakout: FAKEOUT (" + dirTxt(t.dir) + ") on " + syminfo.ticker + " " + timeframe.period + " | close back inside the squeeze box", alert.freq_once_per_bar_close)
                        if showOut and not na(t.s) and t.s.alive
                            t.s.lbs.push(label.new(bar_index, t.dir == 1 ? high : low, "Fakeout", style = t.dir == 1 ? label.style_label_down : label.style_label_up, color = noCol, textcolor = color.white, size = size.tiny))
                // stop is checked first (conservative when one bar touches both); a gap through the stop fills at the open
                if t.dir * (adv - t.sl) <= 0
                    px      := t.dir == 1 ? math.min(open, t.sl) : math.max(open, t.sl)
                    t.doneR += t.left * t.dir * (px - t.entry) / t.risk
                    t.left  := 0.0
                    closed  := true
                    res     := t.hit1 ? (t.sl == t.entry ? "Stop at entry" : t.hit2 ? "Stop after TP2" : "Stop after TP1") : "Stop"
                    if not t.hit1 and t.taken
                        evStop := true
                        alert("Eye Squeeze Breakout: STOP hit (" + dirTxt(t.dir) + ") on " + syminfo.ticker + " " + timeframe.period + " at " + str.tostring(px, format.mintick), alert.freq_once_per_bar_close)
                else
                    if not t.hit1 and t.dir * (fav - t.tp1) >= 0
                        t.hit1  := true
                        t.doneR += tp1R / 3.0
                        t.left  -= 1.0 / 3.0
                        if t.taken
                            evTp1 := true
                            alert("Eye Squeeze Breakout: TP1 reached (" + dirTxt(t.dir) + ") on " + syminfo.ticker + " " + timeframe.period + " at " + str.tostring(t.tp1, format.mintick), alert.freq_once_per_bar_close)
                        if beTp1
                            t.sl := t.entry
                            // same bar also traded back to entry: TP1 is assumed first, the remaining size exits at entry (conservative)
                            if t.dir * (adv - t.sl) <= 0
                                t.left := 0.0
                                closed := true
                                res    := "Stop at entry"
                                px     := t.entry
                    if not closed and t.hit1 and not t.hit2 and t.dir * (fav - t.tp2) >= 0
                        t.hit2  := true
                        t.doneR += tp2v / 3.0
                        t.left  -= 1.0 / 3.0
                    if not closed and t.hit2 and t.dir * (fav - t.tp3) >= 0
                        t.doneR += t.left * tp3v
                        t.left  := 0.0
                        closed  := true
                        res     := "TP3 ✓"
                        px      := t.tp3
                    if not closed and bar_index - t.start >= maxBars
                        t.doneR += t.left * t.dir * (close - t.entry) / t.risk
                        t.left  := 0.0
                        closed  := true
                        res     := "Time exit"
                        px      := close
            if t.taken and not na(t.s) and t.s.alive
                for l in t.s.lns
                    l.set_x2(bar_index + 1)
                for b in t.s.pl
                    b.set_x(bar_index + 1)
            if closed
                if t.miss
                    if t.taken
                        nMiss += 1
                        if showOut and not na(t.s) and t.s.alive
                            t.s.lbs.push(label.new(bar_index, t.entry, "No retest", style = label.style_label_right, color = noCol, textcolor = color.white, size = size.tiny))
                else
                    // every signal (filters ignored)
                    nAll    += 1
                    sumRAll += t.doneR
                    int mk = t.fmask
                    for f = 0 to 5
                        if mk % 2 == 1
                            fNy.set(f, fNy.get(f) + 1)
                            fRy.set(f, fRy.get(f) + t.doneR)
                        else
                            fNn.set(f, fNn.get(f) + 1)
                            fRn.set(f, fRn.get(f) + t.doneR)
                        mk := int(mk / 2)
                    if t.taken
                        nClosed += 1
                        sumR    += t.doneR
                        nT1     += t.hit1 ? 1 : 0
                        nT2     += t.hit2 ? 1 : 0
                        nT3     += res == "TP3 ✓" ? 1 : 0
                        nStop   += res == "Stop" ? 1 : 0
                        nFake   += t.fake ? 1 : 0
                        nTime   += res == "Time exit" and not t.hit1 ? 1 : 0
                        if t.bias == t.dir
                            nW   += 1
                            nWT1 += t.hit1 ? 1 : 0
                        else if t.bias == -t.dir
                            nA   += 1
                            nAT1 += t.hit1 ? 1 : 0
                        lvN.set(t.lvl, lvN.get(t.lvl) + 1)
                        lvT1.set(t.lvl, lvT1.get(t.lvl) + (t.hit1 ? 1 : 0))
                        if t.dir == 1
                            nL   += 1
                            nLT1 += t.hit1 ? 1 : 0
                        else
                            nS   += 1
                            nST1 += t.hit1 ? 1 : 0
                        if showOut and not na(t.s) and t.s.alive
                            color oc = t.doneR > 0 ? upCol : t.doneR < 0 ? dnCol : noCol
                            t.s.lbs.push(label.new(bar_index, px, res + " " + fmtR(t.doneR), style = label.style_label_right, color = oc, textcolor = color.white, size = size.small))
                trades.remove(i)
 
    // 2) Squeeze tracking
    if sqzOn
        if na(sqStart)
            sqStart  := bar_index
            sqTop    := high
            sqBot    := low
            sqMaxLvl := lvl
            evStart  := true
            box b = showBox ? box.new(bar_index, high, bar_index, low, border_color = color.new(lvlCol(lvl), 30), bgcolor = color.new(lvlCol(lvl), 85), text = boxTxt(1, lvl), text_size = size.tiny, text_color = chart.fg_color, text_halign = text.align_left, text_valign = text.align_top) : na
            curS := Setup.new(b, na, array.new<line>(), array.new<label>(), array.new<label>())
            setups.push(curS)
            if setups.size() > keepN
                killSetup(setups.shift())
        else
            sqTop    := math.max(sqTop, high)
            sqBot    := math.min(sqBot, low)
            sqMaxLvl := math.max(sqMaxLvl, lvl)
        int cnt = bar_index - sqStart + 1
        if cnt == minSqz
            evReady := true
            if armed // a new qualifying squeeze replaces the old box that never broke out
                armed := false
                greyBox(armS, aBars, aLvl, sqStart - 1)
        if not na(curS) and curS.alive and not na(curS.bx)
            curS.bx.set_top(sqTop)
            curS.bx.set_bottom(sqBot)
            curS.bx.set_right(bar_index)
            curS.bx.set_border_color(color.new(lvlCol(sqMaxLvl), 30))
            curS.bx.set_bgcolor(color.new(lvlCol(sqMaxLvl), 85))
            curS.bx.set_text(boxTxt(cnt, sqMaxLvl))
        preBias := biasOf(sqTop, sqBot) // bias is fixed on the last squeeze bar, before release
    else
        if not na(sqStart)
            int bars = bar_index - sqStart
            if bars >= minSqz
                armed  := true
                armBar := bar_index
                aTop   := sqTop
                aBot   := sqBot
                aAtr   := atr
                aBars  := bars
                aLvl   := sqMaxLvl
                aBias  := preBias
                rawDir := 0
                armS   := curS
                nSqz   += 1
                sqzSum += bars
                evRel  := true
                if showBias and not na(curS) and curS.alive
                    color bc = aBias == 1 ? upCol : aBias == -1 ? dnCol : noCol
                    curS.lbs.push(label.new(bar_index, aBias == -1 ? sqBot : sqTop, aBias == 1 ? "Bias ▲" : aBias == -1 ? "Bias ▼" : "Bias –", style = aBias == -1 ? label.style_label_up : label.style_label_down, color = color.new(bc, 25), textcolor = color.white, size = size.tiny))
                alert("Eye Squeeze Breakout: squeeze released on " + syminfo.ticker + " " + timeframe.period + " | " + lvlName(aLvl) + " squeeze, " + str.tostring(bars) + " bars | Release bias " + (aBias == 1 ? "LONG" : aBias == -1 ? "SHORT" : "NEUTRAL"), alert.freq_once_per_bar_close)
            else if setups.size() > 0
                killSetup(setups.pop())
            sqStart  := na
            curS     := na
            sqMaxLvl := 0
 
    // 3) Breakout of the frozen squeeze box
    if armed
        // honest bias check: first unfiltered close outside the box vs the bias fixed before release
        if rawDir == 0
            rawDir := close > aTop ? 1 : close < aBot ? -1 : 0
            if rawDir != 0 and aBias != 0
                nExitN  += 1
                nExitOk += rawDir == aBias ? 1 : 0
        bool upB = close > aTop and (not useMom or mom > 0) and inSess
        bool dnB = close < aBot and (not useMom or mom < 0) and inSess
        if upB or dnB
            int   d    = upB ? 1 : -1
            float edge = d == 1 ? aTop : aBot
            float e    = retest ? edge : close
            float mid  = (aTop + aBot) / 2
            float raw  = slMode == "Box middle" ? d * (e - mid) : slMode == "Box opposite side" ? d * (e - (d == 1 ? aBot : aTop)) : slAtr * atr
            float rk   = math.max(raw, minSlAtr * atr, syminfo.mintick)
            // quality factors (each can be required; all are measured in the Filter lab)
            bool  fTrend  = htfOk and htfDir == d
            bool  fDepth  = aLvl == 3
            bool  fBias   = aBias == d
            bool  fStrong = barRng > 0 and body >= bodyMin * barRng and d * (close - edge) >= 0.1 * atr
            bool  fTight  = not na(aAtr) and aAtr > 0 and (aTop - aBot) <= tightAtr * aAtr
            int   fm      = (fTrend ? 1 : 0) + (fDepth ? 2 : 0) + (fBias ? 4 : 0) + (fStrong ? 8 : 0) + (volExp ? 16 : 0) + (fTight ? 32 : 0)
            int   qMax    = 4 + (htfOk ? 1 : 0) + (hasVol ? 1 : 0)
            int   q       = (fTrend ? 1 : 0) + (fDepth ? 1 : 0) + (fBias ? 1 : 0) + (fStrong ? 1 : 0) + (volExp ? 1 : 0) + (fTight ? 1 : 0)
            bool  take    = (not useHtf or not htfOk or fTrend) and (not reqDepth or fDepth) and (not reqBias or fBias) and (not reqStrong or fStrong) and (not reqVol or not hasVol or volExp) and (not reqTight or fTight)
            armed := false
            if not na(rk) and rk > 0
                nBrk += 1
                Trade t = Trade.new(dir = d, entry = e, sl = e - d * rk, risk = rk, tp1 = e + d * rk * tp1R, tp2 = e + d * rk * tp2v, tp3 = e + d * rk * tp3v, top = aTop, bot = aBot, sig = bar_index, start = bar_index, lvl = aLvl, bias = aBias, fmask = fm, taken = take, live = not retest, s = armS)
                trades.push(t)
                if take
                    if d == 1
                        evLong := true
                    else
                        evShort := true
                    alert("Eye Squeeze Breakout " + dirTxt(d) + " (quality " + str.tostring(q) + "/" + str.tostring(qMax) + ") on " + syminfo.ticker + " " + timeframe.period + " | " + (retest ? "Retest entry " : "Entry ") + str.tostring(e, format.mintick) + " | SL " + str.tostring(t.sl, format.mintick) + " | TP1 " + str.tostring(t.tp1, format.mintick) + " | TP2 " + str.tostring(t.tp2, format.mintick) + " | TP3 " + str.tostring(t.tp3, format.mintick) + " | " + lvlName(aLvl) + " squeeze, " + str.tostring(aBars) + " bars", alert.freq_once_per_bar_close)
                else
                    nSkip += 1
                if not na(armS) and armS.alive
                    color dc = d == 1 ? upCol : dnCol
                    if take
                        if not na(armS.bx)
                            armS.bx.set_right(bar_index)
                            armS.bx.set_border_color(dc)
                            armS.bx.set_bgcolor(color.new(dc, 88))
                            armS.bx.set_text(boxTxt(aBars, aLvl))
                        armS.brk := label.new(bar_index, d == 1 ? low : high, (d == 1 ? "Breakout ▲ " : "Breakout ▼ ") + "★" + str.tostring(q) + "/" + str.tostring(qMax), style = d == 1 ? label.style_label_up : label.style_label_down, color = dc, textcolor = color.white, size = size.small)
                        if showPlan
                            array<float>  lv = array.from(e, t.sl, t.tp1, t.tp2, t.tp3)
                            array<string> nm = array.from(retest ? "Retest entry" : "Entry", "SL", "TP1", "TP2", "TP3")
                            for k = 0 to 4
                                color lc = k == 0 ? chart.fg_color : k == 1 ? dnCol : upCol
                                armS.lns.push(line.new(bar_index, lv.get(k), bar_index + 1, lv.get(k), color = lc, style = k == 0 ? line.style_solid : line.style_dashed, width = 1))
                                armS.pl.push(label.new(bar_index + 1, lv.get(k), nm.get(k) + " " + str.tostring(lv.get(k), format.mintick), style = label.style_label_left, color = color.new(chart.bg_color, 100), textcolor = lc, size = size.tiny))
                    else if showSkip and not na(armS.bx)
                        armS.bx.set_right(bar_index)
                        armS.bx.set_border_color(color.new(dc, 40))
                        armS.bx.set_border_style(line.style_dotted)
                        armS.bx.set_bgcolor(color.new(noCol, 90))
                        armS.bx.set_text(boxTxt(aBars, aLvl) + " · " + (d == 1 ? "▲" : "▼") + " filtered out")
        else if bar_index - armBar >= brkWin
            armed := false
            greyBox(armS, aBars, aLvl, bar_index)
        else if not na(armS) and armS.alive and not na(armS.bx)
            armS.bx.set_right(bar_index)
 
bgcolor(showBg and sqzOn ? color.new(lvlCol(lvl), 94) : na, title = "Squeeze background")
 
// ───────────────────────── Dashboard
string tPos = dPos == "Top left" ? position.top_left : dPos == "Bottom right" ? position.bottom_right : dPos == "Bottom left" ? position.bottom_left : position.top_right
var table dash   = table.new(tPos, 2, 36, bgcolor = chart.bg_color, border_color = color.new(chart.fg_color, 85), border_width = 1, frame_color = color.new(chart.fg_color, 60), frame_width = 1)
 
mtfTxt(string tf, int l, float m) =>
    bool lower = timeframe.in_seconds(tf) < timeframe.in_seconds(timeframe.period)
    lower ? "lower than chart" : na(l) ? "–" : (l > 0 ? lvlName(l) + " squeeze" : "No squeeze") + (na(m) ? "" : m > 0 ? " ▲" : " ▼")
 
mtfCol(string tf, int l) =>
    bool lower = timeframe.in_seconds(tf) < timeframe.in_seconds(timeframe.period)
    lower or na(l) or l == 0 ? chart.fg_color : lvlCol(l)
 
if barstate.isfirst
    dash.merge_cells(0, 0, 1, 0)
 
if showDash and barstate.islast
    color fg = chart.fg_color
    dash.cell(0, 0, "Eye Squeeze Breakout", text_color = fg, text_size = ts, text_halign = text.align_center)
    array<string> ks = array.new<string>()
    array<string> vs = array.new<string>()
    array<color>  cs = array.new<color>()
    string st = sqzOn ? "Squeeze ON · " + lvlName(lvl) + (na(sqStart) ? "" : " · " + str.tostring(bar_index - sqStart + 1) + " bars") : armed ? "Released · waiting " + str.tostring(bar_index - armBar) + "/" + str.tostring(brkWin) : "No squeeze"
    ks.push("Status"), vs.push(st), cs.push(sqzOn ? lvlCol(lvl) : fg)
    ks.push("Compression"), vs.push(na(comp) ? "–" : str.tostring(comp, "0.00") + " × normal"), cs.push(lvl > 0 ? lvlCol(lvl) : fg)
    ks.push("Drive"), vs.push(na(mom) or mom == 0 ? "–" : mom > 0 ? (mom > momPrev ? "Bullish ▲ strengthening" : "Bullish ▼ fading") : (mom < momPrev ? "Bearish ▼ strengthening" : "Bearish ▲ fading")), cs.push(mom > 0 ? upCol : mom < 0 ? dnCol : fg)
    int lb = sqzOn and not na(sqStart) ? biasOf(sqTop, sqBot) : armed ? aBias : 2
    ks.push("Release bias"), vs.push(lb == 1 ? "Long ▲" : lb == -1 ? "Short ▼" : lb == 0 ? "Neutral" : "–"), cs.push(lb == 1 ? upCol : lb == -1 ? dnCol : fg)
    string ot = "None"
    color  oc = fg
    int    nOpen = 0
    for tt in trades
        nOpen += tt.taken and tt.live ? 1 : 0
    if trades.size() > 0
        for j = trades.size() - 1 to 0
            Trade t = trades.get(j)
            if t.taken
                if t.live
                    float lr = t.doneR + t.left * t.dir * (close - t.entry) / t.risk
                    ot := (t.dir == 1 ? "Long · " : "Short · ") + fmtR(lr)
                    oc := lr >= 0 ? upCol : dnCol
                else
                    ot := (t.dir == 1 ? "Long" : "Short") + " · waiting retest"
                break
    ks.push("Open trade"), vs.push(ot), cs.push(oc)
    string fl = (useHtf ? (htfOk ? "Trend · " : "Trend off (HTF < chart) · ") : "") + (reqDepth ? "High · " : "") + (reqBias ? "Bias · " : "") + (reqStrong ? "Candle · " : "") + (reqVol ? (hasVol ? "Volume · " : "Volume n/a · ") : "") + (reqTight ? "Tight · " : "")
    ks.push("Filters"), vs.push((fl == "" ? "none · " : fl) + (retest ? "retest entry" : "close entry")), cs.push(fg)
    if not compact
        ks.push("Squeezes found"), vs.push(str.tostring(nSqz) + (nSqz > 0 ? " · avg " + str.tostring(sqzSum * 1.0 / nSqz, "0.0") + " bars" : "")), cs.push(fg)
        ks.push("Breakout rate"), vs.push(pct(nBrk, nSqz - (armed ? 1 : 0))), cs.push(fg)
        ks.push("Trades taken"), vs.push(str.tostring(nClosed) + (nOpen > 0 ? " + " + str.tostring(nOpen) + " open" : "") + " · filtered out " + str.tostring(nSkip) + (retest ? " · no retest " + str.tostring(nMiss) : "")), cs.push(fg)
    ks.push("Reached TP1"), vs.push(pct(nT1, nClosed)), cs.push(upCol)
    if not compact
        ks.push("Reached TP2"), vs.push(pct(nT2, nClosed)), cs.push(upCol)
        ks.push("Reached TP3"), vs.push(pct(nT3, nClosed)), cs.push(upCol)
        ks.push("Full stop (before TP1)"), vs.push(pct(nStop, nClosed)), cs.push(dnCol)
        ks.push("Time exit (no TP1)"), vs.push(pct(nTime, nClosed)), cs.push(fg)
        ks.push("Fakeout rate"), vs.push(pct(nFake, nClosed)), cs.push(noCol)
    float avgR = nClosed > 0 ? sumR / nClosed : na
    ks.push("Avg result · taken trades"), vs.push(avgRN(sumR, nClosed)), cs.push(na(avgR) ? fg : avgR >= 0 ? upCol : dnCol)
    float avgAll = nAll > 0 ? sumRAll / nAll : na
    ks.push("Avg result · all signals (pre-quality)"), vs.push(avgRN(sumRAll, nAll)), cs.push(na(avgAll) ? fg : avgAll >= 0 ? upCol : dnCol)
    if not compact
        ks.push("Long / Short TP1"), vs.push(pctN(nLT1, nL) + " / " + pctN(nST1, nS)), cs.push(fg)
        string dp = ""
        for lv = minLvl to 3
            dp += (dp == "" ? "" : " / ") + str.substring(lvlName(lv), 0, 1) + " " + pctN(lvT1.get(lv), lvN.get(lv))
        ks.push("TP1 by max depth"), vs.push(dp), cs.push(fg)
        ks.push("Bias → first exit side"), vs.push(pctN(nExitOk, nExitN)), cs.push(fg)
        ks.push("TP1 with / against bias"), vs.push(pctN(nWT1, nW) + " / " + pctN(nAT1, nA)), cs.push(fg)
    if not compact
        array<string> fnm = array.from("With HTF trend", "High depth", "With release bias", "Strong candle", "Volume expansion", "Tight box")
        ks.push("Filter lab · all signals"), vs.push("with · without"), cs.push(color.new(fg, 40))
        for f = 0 to 5
            bool fNa = (f == 0 and not htfOk) or (f == 4 and not hasVol)
            ks.push("  " + fnm.get(f)), vs.push(fNa ? "n/a on this chart" : avgRN(fRy.get(f), fNy.get(f)) + " · " + avgRN(fRn.get(f), fNn.get(f))), cs.push(fNy.get(f) >= 20 and fNn.get(f) >= 20 and fRy.get(f) / fNy.get(f) > fRn.get(f) / fNn.get(f) ? upCol : fg)
    if showMtf
        ks.push("Squeeze " + tfLbl(mtf1)), vs.push(mtfTxt(mtf1, l1, m1)), cs.push(mtfCol(mtf1, l1))
        ks.push("Squeeze " + tfLbl(mtf2)), vs.push(mtfTxt(mtf2, l2, m2)), cs.push(mtfCol(mtf2, l2))
        ks.push("Squeeze " + tfLbl(mtf3)), vs.push(mtfTxt(mtf3, l3, m3)), cs.push(mtfCol(mtf3, l3))
    int n = ks.size()
    for r = 0 to n - 1
        dash.cell(0, r + 1, ks.get(r), text_color = fg, text_size = ts, text_halign = text.align_left)
        dash.cell(1, r + 1, vs.get(r), text_color = cs.get(r), text_size = ts, text_halign = text.align_right)
    dash.cell(0, n + 1, "In-sample · before spread & commission", text_color = color.new(fg, 40), text_size = size.tiny, text_halign = text.align_left)
    dash.cell(1, n + 1, "", text_size = size.tiny)
    if n + 2 <= 35
        dash.clear(0, n + 2, 1, 35)
 
// ───────────────────────── Alerts
bool evLow  = barstate.isconfirmed and lvl >= 1 and lvl[1] < 1
bool evMid  = barstate.isconfirmed and lvl >= 2 and lvl[1] < 2
bool evHigh = barstate.isconfirmed and lvl >= 3 and lvl[1] < 3
bool evFadeBull = barstate.isconfirmed and mom > 0 and mom < mom[1] and mom[1] >= mom[2]
bool evFadeBear = barstate.isconfirmed and mom < 0 and mom > mom[1] and mom[1] <= mom[2]
 
alertcondition(evStart, "Squeeze started (selected level)", "Eye Squeeze Breakout: squeeze started on {{ticker}} {{interval}}")
alertcondition(evLow, "Low level reached", "Eye Squeeze Breakout: squeeze reached LOW level on {{ticker}} {{interval}}")
alertcondition(evMid, "Mid level reached", "Eye Squeeze Breakout: squeeze reached MID level on {{ticker}} {{interval}}")
alertcondition(evHigh, "High level reached", "Eye Squeeze Breakout: squeeze reached HIGH level on {{ticker}} {{interval}}")
alertcondition(evReady, "Squeeze ready (min bars reached)", "Eye Squeeze Breakout: squeeze reached the minimum bars on {{ticker}} {{interval}}")
alertcondition(evRel, "Squeeze released", "Eye Squeeze Breakout: squeeze released on {{ticker}} {{interval}}, watching for breakout")
alertcondition(evLong, "Breakout Long (passes filters)", "Eye Squeeze Breakout: LONG breakout on {{ticker}} {{interval}} (for entry, SL and TP use the 'Any alert() function call' alert)")
alertcondition(evShort, "Breakout Short (passes filters)", "Eye Squeeze Breakout: SHORT breakout on {{ticker}} {{interval}} (for entry, SL and TP use the 'Any alert() function call' alert)")
alertcondition(evTp1, "TP1 reached", "Eye Squeeze Breakout: TP1 reached on {{ticker}} {{interval}}")
alertcondition(evStop, "Stop hit (before TP1)", "Eye Squeeze Breakout: stop hit on {{ticker}} {{interval}}")
alertcondition(evFake, "Fakeout", "Eye Squeeze Breakout: price closed back inside the squeeze box on {{ticker}} {{interval}}")
alertcondition(evFadeBull, "Bullish drive fading", "Eye Squeeze Breakout: bullish drive fading on {{ticker}} {{interval}}")
alertcondition(evFadeBear, "Bearish drive fading", "Eye Squeeze Breakout: bearish drive fading on {{ticker}} {{interval}}")

← 返回列表