Eye Rejection Profile [EyeAlgo]

eyealgo · study · 748 行 · 点赞 328 · 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
// Eye Rejection Profile — by Eye Algo (original code)
//  1. Rejection profile: only WICK volume is placed by price (not total volume).
//     Lower wicks = buyers rejecting lower prices (left wing), upper wicks = sellers rejecting higher prices (right wing).
//  2. Rejection zones: the price bands with the heaviest rejection volume. Rebuilt once per session from the
//     bars BEFORE the session, then frozen — so zones and signals never repaint.
//  3. Naked POC tracker: every finished session's POC stays on the chart until price trades back to it.
//  ★ Magnet Map: every naked POC shows the probability that price reaches it within the next few sessions,
//     learned from this symbol's own history and its distance from price (in average session ranges).
//  ★ Rejection Candles: candles whose wick rejected price with unusual size AND volume get a glowing wick.
//  4. Rejection setup: price wicks into a zone and closes back out with a rejection candle. Stop beyond the zone,
//     target = nearest naked POC (the volume magnet), else the opposite zone, else 2R. Every setup is tracked
//     and the table shows its own hit rate.
 
//@version=6
indicator("Eye Rejection Profile [EyeAlgo]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ═══════════════════════════════════════════════════════════════════════════
//  SETTINGS
// ═══════════════════════════════════════════════════════════════════════════
GP = "📊 Rejection Profile"
lookN = input.int(300, "Bars used per session", minval = 50, maxval = 2000, group = GP, display = display.none,
     tooltip = "At the start of every session the profile and zones are rebuilt from this many bars before it. Session = day on intraday charts, week on daily, month on weekly.")
rows  = input.int(40, "Rows", minval = 10, maxval = 100, group = GP, display = display.none)
widB  = input.int(50, "Profile width (bars)", minval = 10, maxval = 200, group = GP, display = display.none)
offB  = input.int(10, "Gap from last candle (bars)", minval = 2, maxval = 100, group = GP, display = display.none)
showP = input.bool(true, "Show rejection profile", group = GP, display = display.none)
 
GZ = "🧱 Rejection Zones"
showZ  = input.bool(true, "Show rejection zones", group = GZ, display = display.none)
zoneTh = input.int(60, "Zone strength (% of strongest row)", minval = 30, maxval = 95, group = GZ, display = display.none,
     tooltip = "Rows with at least this share of the strongest row form a zone. Higher = fewer, stronger zones.")
zPer   = input.int(2, "Zones per side", minval = 1, maxval = 4, group = GZ, display = display.none)
 
GS = "🎯 Rejection Setups"
showSig = input.bool(true, "Show rejection setups", group = GS, display = display.none)
wickMin = input.float(40, "Rejection wick (% of candle)", minval = 10, maxval = 90, group = GS, display = display.none,
     tooltip = "The wick pointing into the zone must be at least this share of the candle's range.")
slBuf   = input.float(0.2, "Stop buffer (× ATR)", minval = 0.0, step = 0.05, group = GS, display = display.none)
minRR   = input.float(1.0, "Minimum reward : risk", minval = 0.5, step = 0.25, group = GS, display = display.none,
     tooltip = "A naked POC or zone is only used as target if it is at least this many R away; otherwise the target is 2R.")
maxRR   = input.float(3.0, "Maximum reward : risk", minval = 1.0, step = 0.5, group = GS, display = display.none,
     tooltip = "Targets further than this many R are ignored, so trades stay realistic.")
maxBars = input.int(48, "Time exit after (bars)", minval = 5, maxval = 500, group = GS, display = display.none,
     tooltip = "If neither target nor stop is hit within this many bars, the setup is closed at the bar's close.")
magMin  = input.int(60, "⭐ Magnet target needs (%)", minval = 30, maxval = 95, group = GS, display = display.none,
     tooltip = "A setup earns the magnet star when its target is a naked POC whose probability is at least this.")
showBox = input.bool(true, "Show TP / SL boxes", group = GS, display = display.none)
keepT   = input.int(100, "Setups kept on chart", minval = 1, maxval = 150, group = GS, display = display.none)
 
GN = "🧲 Magnet Map"
showN   = input.bool(true, "Show magnets (naked POCs)", group = GN, display = display.none)
maxN    = input.int(5, "Nearest magnets shown", minval = 1, maxval = 30, group = GN, display = display.none)
revWin  = input.int(5, "Probability window (sessions)", minval = 1, maxval = 20, group = GN, display = display.none,
     tooltip = "Each magnet shows the chance that price trades back to it within this many sessions, measured on this symbol.")
maxDist = input.float(3.0, "Hide magnets further than (session ranges)", minval = 0.5, step = 0.5, group = GN, display = display.none,
     tooltip = "Magnets further away than this many average session ranges are not drawn, so the price scale is not squeezed. They still count in the statistics.")
minSamp = input.int(15, "Min samples per distance bucket", minval = 5, maxval = 200, group = GN, display = display.none)
 
GR = "🕯️ Rejection Candles"
showRC = input.bool(true, "Glow strong rejection wicks", group = GR, display = display.none)
rcStr  = input.float(2.5, "Rejection strength needed", minval = 0.5, step = 0.25, group = GR, display = display.none,
     tooltip = "Strength = wick length in ATR × volume versus its 50-bar average. The wick must also be at least the 'Rejection wick %' of the candle.")
rcKeep = input.int(100, "Rejection candles kept", minval = 5, maxval = 150, group = GR, display = display.none)
 
GC = "🎨 Colours"
buyC = input.color(#26A69A, "Buyers", inline = "c1", group = GC)
selC = input.color(#EF5350, "Sellers", inline = "c1", group = GC)
pocC = input.color(#FFB300, "Naked POC", inline = "c2", group = GC)
hdrC = input.color(#2962FF, "Header", inline = "c2", group = GC)
 
GT = "📋 Table & Alerts"
showTb = input.bool(true, "Show summary table", group = GT, display = display.none)
tbPos  = input.string("Top right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = GT, display = display.none)
detailAlerts = input.bool(true, "Detailed alert() messages", group = GT, display = display.none,
     tooltip = "Create the alert with 'Any alert() function call' to get entry, stop and target in the message.")
 
// ═══════════════════════════════════════════════════════════════════════════
//  COMMON
// ═══════════════════════════════════════════════════════════════════════════
atr  = ta.atr(14)
atrL = ta.atr(50)
avgVol = ta.sma(nz(volume) > 0 ? volume : 1.0, 50)
sessTf = timeframe.isintraday ? "D" : timeframe.isdaily ? "W" : timeframe.isweekly ? "M" : "12M"
sessName = timeframe.isintraday ? "days" : timeframe.isdaily ? "weeks" : timeframe.isweekly ? "months" : "years"
sessUnit = timeframe.isintraday ? "day" : timeframe.isdaily ? "week" : timeframe.isweekly ? "month" : "year"
f_bk(float d) => d < 0.5 ? 0 : d < 1.0 ? 1 : d < 2.0 ? 2 : 3
newS = timeframe.change(sessTf)
px(float p) => str.tostring(p, format.mintick)
bgLum  = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
isDark = bgLum < 128
pocT   = isDark ? pocC : #B7791F          // darker gold for text on light charts
 
// rejection volume inside a price band
f_str(array<float> arr, float top, float bot, float loR, float step, int nRows) =>
    float sm = 0.0
    for k = 0 to nRows - 1
        float mid = loR + (k + 0.5) * step
        if mid <= top and mid >= bot
            sm += arr.get(k)
    sm
 
// spread an amount over the rows between lo and hi
f_spread(array<float> arr, float lo, float hi, float amt, float loR, float step, int nRows) =>
    if hi > lo and amt > 0
        int k1 = math.max(0, math.min(nRows - 1, int(math.floor((lo - loR) / step))))
        int k2 = math.max(0, math.min(nRows - 1, int(math.floor((hi - loR) / step))))
        for k = k1 to k2
            float rLo = loR + k * step
            float ov  = math.max(0.0, math.min(hi, rLo + step) - math.max(lo, rLo))
            arr.set(k, arr.get(k) + amt * ov / (hi - lo))
 
// strongest zones of one side → [tops, bottoms], strongest first
f_zones(array<float> arr, float loR, float step, int nRows, int keep) =>
    float mx = arr.max()
    array<float> zT = array.new<float>()
    array<float> zB = array.new<float>()
    array<float> zS = array.new<float>()
    if mx > 0
        int   s   = -1
        float acc = 0.0
        for k = 0 to nRows
            bool on = k < nRows and arr.get(k) >= mx * zoneTh / 100.0
            if on
                if s < 0
                    s := k
                    acc := 0.0
                acc += arr.get(k)
            else if s >= 0
                zB.push(loR + s * step)
                zT.push(loR + k * step)
                zS.push(acc)
                s := -1
    array<float> oT = array.new<float>()
    array<float> oB = array.new<float>()
    while oT.size() < keep and zS.size() > 0
        int j = zS.indexof(zS.max())
        oT.push(zT.get(j))
        oB.push(zB.get(j))
        zT.remove(j)
        zB.remove(j)
        zS.remove(j)
    [oT, oB]
 
// ═══════════════════════════════════════════════════════════════════════════
//  1. NAKED POC ENGINE
// ═══════════════════════════════════════════════════════════════════════════
var map<int, float> sVol   = map.new<int, float>()
var float           bSize  = na
var array<float>    nPrice = array.new<float>()
var array<int>      nBorn  = array.new<int>()
var array<int>      nBar   = array.new<int>()
var array<int>      nTm    = array.new<int>()     // time of the POC's session (for the label)
var int             sStartT = na
var array<label>    hitLb  = array.new<label>()
var array<bool>     nDone  = array.new<bool>()
var int   sessCount = 0
var int   revisited = 0
var int   expired   = 0
var float sumAge    = 0.0
var int          pocId  = 0
var array<int>   nId    = array.new<int>()
var array<int>   smB    = array.new<int>()       // pending probability samples: distance bucket
var array<int>   smS    = array.new<int>()       //   session the sample started
var array<int>   smId   = array.new<int>()       //   naked POC id
var array<bool>  smHit  = array.new<bool>()      //   reached inside its window?
var array<int>   bHit   = array.new<int>(4, 0)
var array<int>   bTot   = array.new<int>(4, 0)
var float sHi   = na
var float sLo   = na
var float avgSR = na
 
if newS
    if not na(sHi)
        float sr = sHi - sLo
        avgSR := na(avgSR) ? sr : avgSR * 0.9 + sr * 0.1
    sHi := high
    sLo := low
    if sVol.size() > 0 and not na(bSize)
        float bestV = -1.0
        int   bestK = 0
        for [k, v] in sVol
            if v > bestV
                bestV := v
                bestK := k
        nPrice.push((bestK + 0.5) * bSize)
        nBorn.push(sessCount)
        nBar.push(bar_index - 1)
        nTm.push(nz(sStartT, time))
        nDone.push(false)
        pocId += 1
        nId.push(pocId)
    sVol.clear()
    sStartT := time
    sessCount += 1
    bSize := na(atrL) ? na : math.max(syminfo.mintick, atrL * 0.25)
    // close samples whose window is over: count them only now, hit or miss (no early-hit bias)
    if smB.size() > 0
        for i = smB.size() - 1 to 0
            if sessCount - smS.get(i) >= revWin
                bTot.set(smB.get(i), bTot.get(smB.get(i)) + 1)
                if smHit.get(i)
                    bHit.set(smB.get(i), bHit.get(smB.get(i)) + 1)
                smB.remove(i)
                smS.remove(i)
                smId.remove(i)
                smHit.remove(i)
    // one new sample per open magnet: its distance now, in average session ranges
    if not na(avgSR) and avgSR > 0 and nPrice.size() > 0 and smB.size() < 4000
        for i = 0 to nPrice.size() - 1
            smB.push(f_bk(math.abs(open - nPrice.get(i)) / avgSR))
            smS.push(sessCount)
            smId.push(nId.get(i))
            smHit.push(false)
else
    sHi := math.max(nz(sHi, high), high)
    sLo := math.min(nz(sLo, low), low)
 
if not na(bSize)
    float vv = nz(volume) > 0 ? volume : 1.0
    int kLo = int(math.floor(low / bSize))
    int kHi = int(math.floor(high / bSize))
    if kHi - kLo <= 200
        float part = vv / (kHi - kLo + 1)
        for kk = kLo to kHi
            sVol.put(kk, nz(sVol.get(kk)) + part)
 
touchN = false
if nPrice.size() > 0
    for i = nPrice.size() - 1 to 0
        float pr  = nPrice.get(i)
        int   age = sessCount - nBorn.get(i)
        if bar_index > nBar.get(i) and high >= pr and low <= pr
            touchN := true
            if showN
                hitLb.push(label.new(bar_index, pr, "🧲 ✓", style = label.style_label_center, color = color(na), textcolor = pocT, size = size.small,
                     tooltip = "Magnet reached: " + px(pr) + " (" + str.tostring(age) + " " + sessName + " after it formed)"))
                if hitLb.size() > 80
                    hitLb.shift().delete()
            if not nDone.get(i)
                revisited += 1
                sumAge += age
            // resolve this magnet's samples as hits
            int id = nId.get(i)
            if smB.size() > 0
                for q = smB.size() - 1 to 0
                    if smId.get(q) == id
                        smHit.set(q, true)
            nPrice.remove(i)
            nBorn.remove(i)
            nBar.remove(i)
            nTm.remove(i)
            nDone.remove(i)
            nId.remove(i)
        else if age > revWin and not nDone.get(i)
            expired += 1
            nDone.set(i, true)
while nPrice.size() > 200
    if not nDone.get(0)
        expired += 1
    nPrice.shift()
    nBorn.shift()
    nBar.shift()
    nTm.shift()
    nDone.shift()
    nId.shift()
 
f_prob(int b) => bTot.get(b) >= minSamp ? 100.0 * bHit.get(b) / bTot.get(b) : na
 
// ═══════════════════════════════════════════════════════════════════════════
//  2. REJECTION PROFILE + ZONES (rebuilt once per session, then frozen)
// ═══════════════════════════════════════════════════════════════════════════
var float        zLo   = na
var float        zStep = na
var float        zHi   = na
var int          zN    = 0
var array<float> pRb   = array.new<float>()
var array<float> pRs   = array.new<float>()
var array<float> bzT   = array.new<float>()
var array<float> bzB   = array.new<float>()
var array<float> szT   = array.new<float>()
var array<float> szB   = array.new<float>()
var array<bool>  usedB = array.new<bool>()
var array<bool>  usedS = array.new<bool>()
var array<box>   zBox  = array.new<box>()
var array<box>   zLive = array.new<box>()
var array<int>   zCnt  = array.new<int>()
var array<bool>  zSide = array.new<bool>()    // true = buyer zone (for history colour)     // boxes drawn per session (for history clean-up)
 
if (newS or na(zStep)) and bar_index > 60
    // close the previous session's zone boxes
    // previous session's zones are removed: only the current session's zones are shown
    for b in zLive
        b.delete()
    zLive.clear()
    zSide.clear()
 
    int n = math.min(lookN, bar_index)
    float hiR = high[1]
    float loR = low[1]
    for i = 1 to n
        hiR := math.max(hiR, high[i])
        loR := math.min(loR, low[i])
    if hiR > loR
        float step = (hiR - loR) / rows
        rb = array.new<float>(rows, 0.0)
        rs = array.new<float>(rows, 0.0)
        for i = 1 to n
            float h = high[i]
            float l = low[i]
            float r = h - l
            if r > 0
                float v  = nz(volume[i]) > 0 ? volume[i] : 1.0
                float bt = math.max(open[i], close[i])
                float bb = math.min(open[i], close[i])
                f_spread(rs, bt, h, v * (h - bt) / r, loR, step, rows)
                f_spread(rb, l, bb, v * (bb - l) / r, loR, step, rows)
        zLo := loR
        zHi := hiR
        zStep := step
        zN := n
        pRb := rb
        pRs := rs
        [t1, b1] = f_zones(rb, loR, step, rows, zPer)
        [t2, b2] = f_zones(rs, loR, step, rows, zPer)
        bzT := t1
        bzB := b1
        szT := t2
        szB := b2
        // a band rejected from both sides is congestion: keep only the side that rejected more there
        int jb = bzT.size() - 1
        while jb >= 0
            bool dropB = false
            int js = szT.size() - 1
            while js >= 0 and not dropB
                if bzT.get(jb) > szB.get(js) and bzB.get(jb) < szT.get(js)
                    float sB = f_str(rb, bzT.get(jb), bzB.get(jb), loR, step, rows)
                    float sS = f_str(rs, szT.get(js), szB.get(js), loR, step, rows)
                    if sB >= sS
                        szT.remove(js)
                        szB.remove(js)
                    else
                        dropB := true
                js -= 1
            if dropB
                bzT.remove(jb)
                bzB.remove(jb)
            jb -= 1
        usedB := array.new<bool>(bzT.size(), false)
        usedS := array.new<bool>(szT.size(), false)
        if showZ
            if bzT.size() > 0
                for j = 0 to bzT.size() - 1
                    bx = box.new(bar_index, bzT.get(j), bar_index + 1, bzB.get(j), border_color = color.new(buyC, j == 0 ? 30 : 60), border_width = 1,
                         bgcolor = color.new(buyC, j == 0 ? 84 : 91), text = j == 0 ? "BUYERS DEFEND" : "", text_color = color.new(buyC, 10),
                         text_size = size.small, text_halign = text.align_right, text_valign = text.align_bottom)
                    zLive.push(bx)
                    zSide.push(true)
                    zBox.push(bx)
            if szT.size() > 0
                for j = 0 to szT.size() - 1
                    bx = box.new(bar_index, szT.get(j), bar_index + 1, szB.get(j), border_color = color.new(selC, j == 0 ? 30 : 60), border_width = 1,
                         bgcolor = color.new(selC, j == 0 ? 84 : 91), text = j == 0 ? "SELLERS DEFEND" : "", text_color = color.new(selC, 10),
                         text_size = size.small, text_halign = text.align_right, text_valign = text.align_top)
                    zLive.push(bx)
                    zSide.push(false)
                    zBox.push(bx)
 
 
// live zones follow the current bar
for b in zLive
    b.set_right(bar_index + offB - 2)
 
// ═══════════════════════════════════════════════════════════════════════════
//  3. REJECTION SETUPS + TRACKING
// ═══════════════════════════════════════════════════════════════════════════
var bool  tOn   = false
var int   tDir  = 0
var float tE    = na
var float tSL   = na
var float tTP   = na
var int   tBar  = 0
var box   tbTP  = na
var box   tbSL  = na
var int   wins  = 0
var int   losses = 0
var float sumR  = 0.0
var int   tExits = 0
var int   tStars = 1
var array<int>   gN = array.new<int>(3, 0)
var array<int>   gW = array.new<int>(3, 0)
var array<float> gR = array.new<float>(3, 0.0)
f_stars(int n) => n >= 3 ? "⭐⭐⭐" : n == 2 ? "⭐⭐" : "⭐"
var array<box>   tBoxes = array.new<box>()
var array<label> tLbls  = array.new<label>()
 
longSig  = false
shortSig = false
tpHit    = false
slHit    = false
string tpTag = ""
 
// manage the open setup
if tOn and bar_index > tBar
    if not na(tbTP)
        tbTP.set_right(bar_index)
        tbSL.set_right(bar_index)
    bool hs = tDir == 1 ? low <= tSL : high >= tSL
    bool ht = tDir == 1 ? high >= tTP : low <= tTP
    bool tx = bar_index - tBar >= maxBars
    if hs or ht or tx
        tOn := false
        float risk0 = math.abs(tE - tSL)
        if hs                      // stop first when both are touched on one bar (conservative)
            losses += 1
            sumR -= 1
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) - 1)
            slHit := true
            tLbls.push(label.new(bar_index, tSL, "✗ −1R", color = selC, textcolor = #FFFFFF, style = tDir == 1 ? label.style_label_up : label.style_label_down, size = size.small))
        else if ht
            float rr = math.abs(tTP - tE) / risk0
            wins += 1
            sumR += rr
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gW.set(tStars - 1, gW.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) + rr)
            tpHit := true
            tLbls.push(label.new(bar_index, tTP, "✓ +" + str.tostring(rr, "#.0") + "R", color = buyC, textcolor = #FFFFFF, style = tDir == 1 ? label.style_label_down : label.style_label_up, size = size.small))
        else
            float rr = tDir * (close - tE) / risk0
            tExits += 1
            sumR += rr
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) + rr)
            tLbls.push(label.new(bar_index, close, "⏱ " + (rr >= 0 ? "+" : "") + str.tostring(rr, "#.0") + "R", color = color.new(chart.fg_color, 40), textcolor = chart.bg_color,
                 style = tDir == 1 ? label.style_label_down : label.style_label_up, size = size.small))
 
// new setups (bar close only)
rngC = high - low
if showSig and barstate.isconfirmed and not tOn and rngC > 0 and not na(atr)
    float lw = math.min(open, close) - low
    float uw = high - math.max(open, close)
    // LONG: wick into a buyer zone, close back above it
    if bzT.size() > 0
        for j = 0 to bzT.size() - 1
            float zt = bzT.get(j)
            float zb = bzB.get(j)
            if not longSig and not usedB.get(j) and low <= zt and low >= zb - atr * 0.5 and close > zt and lw >= rngC * wickMin / 100
                float sl   = math.min(low, zb) - atr * slBuf
                float risk = close - sl
                float tp   = na
                tpTag := ""
                if nPrice.size() > 0
                    for i = 0 to nPrice.size() - 1
                        float p = nPrice.get(i)
                        if p >= close + risk * minRR and p <= close + risk * maxRR and (na(tp) or p < tp)
                            tp := p
                            tpTag := "nPOC"
                if na(tp) and szB.size() > 0
                    for i = 0 to szB.size() - 1
                        float p = szB.get(i)
                        if p >= close + risk * minRR and p <= close + risk * maxRR and (na(tp) or p < tp)
                            tp := p
                            tpTag := "zone"
                if na(tp)
                    tp := close + math.min(2.0, maxRR) * risk
                    tpTag := "2R"
                if risk > 0
                    usedB.set(j, true)
                    longSig := true
                    tOn := true
                    tDir := 1
                    tE := close
                    tSL := sl
                    tTP := tp
                    tBar := bar_index
    // SHORT: wick into a seller zone, close back below it
    if not longSig and szT.size() > 0
        for j = 0 to szT.size() - 1
            float zt = szT.get(j)
            float zb = szB.get(j)
            if not shortSig and not usedS.get(j) and high >= zb and high <= zt + atr * 0.5 and close < zb and uw >= rngC * wickMin / 100
                float sl   = math.max(high, zt) + atr * slBuf
                float risk = sl - close
                float tp   = na
                tpTag := ""
                if nPrice.size() > 0
                    for i = 0 to nPrice.size() - 1
                        float p = nPrice.get(i)
                        if p <= close - risk * minRR and p >= close - risk * maxRR and (na(tp) or p > tp)
                            tp := p
                            tpTag := "nPOC"
                if na(tp) and bzT.size() > 0
                    for i = 0 to bzT.size() - 1
                        float p = bzT.get(i)
                        if p <= close - risk * minRR and p >= close - risk * maxRR and (na(tp) or p > tp)
                            tp := p
                            tpTag := "zone"
                if na(tp)
                    tp := close - math.min(2.0, maxRR) * risk
                    tpTag := "2R"
                if risk > 0
                    usedS.set(j, true)
                    shortSig := true
                    tOn := true
                    tDir := -1
                    tE := close
                    tSL := sl
                    tTP := tp
                    tBar := bar_index
 
// grade the new setup: ⭐ zone rejection (always) + ⭐ strong rejection candle + ⭐ high-probability magnet target
bool  gStr = false
bool  gMag = false
float gStrV = na
float gPbT  = na
if longSig or shortSig
    float vRel0 = (nz(volume) > 0 ? volume : 1.0) / avgVol
    float wk    = longSig ? math.min(open, close) - low : high - math.max(open, close)
    gStrV := avgVol > 0 and atr > 0 ? wk / atr * vRel0 : na
    gStr  := not na(gStrV) and gStrV >= rcStr
    gPbT  := tpTag == "nPOC" and not na(avgSR) and avgSR > 0 ? f_prob(f_bk(math.abs(tTP - tE) / avgSR)) : na
    gMag  := not na(gPbT) and gPbT >= magMin
    tStars := 1 + (gStr ? 1 : 0) + (gMag ? 1 : 0)
 
// draw a new setup: position-tool style boxes + label
if longSig or shortSig
    tbTP := na
    tbSL := na
if showBox and (longSig or shortSig)
    tbTP := box.new(bar_index, tTP, bar_index + 1, tE, border_color = color.new(buyC, 55), border_width = 1, bgcolor = color.new(buyC, 88),
         text = "TP " + tpTag, text_color = color.new(buyC, 10), text_size = size.small, text_halign = text.align_right, text_valign = longSig ? text.align_top : text.align_bottom)
    tbSL := box.new(bar_index, tE, bar_index + 1, tSL, border_color = color.new(selC, 55), border_width = 1, bgcolor = color.new(selC, 88),
         text = "SL", text_color = color.new(selC, 10), text_size = size.small, text_halign = text.align_right, text_valign = longSig ? text.align_bottom : text.align_top)
    tBoxes.push(tbTP)
    tBoxes.push(tbSL)
if longSig or shortSig
    color c = longSig ? buyC : selC
    tLbls.push(label.new(bar_index, longSig ? low : high, (longSig ? "▲ REJECT " : "▼ REJECT ") + f_stars(tStars), yloc = longSig ? yloc.belowbar : yloc.abovebar,
         color = c, textcolor = #FFFFFF, style = longSig ? label.style_label_up : label.style_label_down, size = tStars >= 3 ? size.normal : size.small,
         tooltip = "⭐ Zone rejection ✓\n⭐ Strong rejection candle " + (gStr ? "✓" : "✗") + (na(gStrV) ? "" : " (×" + str.tostring(gStrV, "#.0") + ")") +
         "\n⭐ Magnet target ≥ " + str.tostring(magMin) + "% " + (gMag ? "✓" : "✗") + (na(gPbT) ? "" : " (" + str.tostring(gPbT, "#") + "%)") +
         "\n\nEntry " + px(tE) + "\nStop " + px(tSL) + "\nTarget " + px(tTP) + " (" + tpTag + ")"))
while tBoxes.size() > keepT * 2
    tBoxes.shift().delete()
while tLbls.size() > keepT * 2
    tLbls.shift().delete()
 
// ═══════════════════════════════════════════════════════════════════════════
//  ★ REJECTION CANDLES: glowing wick where size AND volume both stand out
// ═══════════════════════════════════════════════════════════════════════════
var array<line>  rcLn = array.new<line>()
var array<label> rcLb = array.new<label>()
rcBuy  = false
rcSell = false
if showRC and barstate.isconfirmed and not na(atr) and atr > 0 and high > low and avgVol > 0
    float vRel = (nz(volume) > 0 ? volume : 1.0) / avgVol
    float lwc  = math.min(open, close) - low
    float uwc  = high - math.max(open, close)
    float sL   = lwc / atr * vRel
    float sU   = uwc / atr * vRel
    float minW = (high - low) * wickMin / 100
    if lwc >= minW and lwc > uwc and sL >= rcStr
        rcBuy := true
        float bb = math.min(open, close)
        rcLn.push(line.new(bar_index, low, bar_index, bb, color = color.new(buyC, 70), width = 9))
        rcLn.push(line.new(bar_index, low, bar_index, bb, color = buyC, width = 3))
        if not longSig
            rcLb.push(label.new(bar_index, low, "×" + str.tostring(sL, "#.0"), style = label.style_label_up, color = color(na), textcolor = buyC, size = size.small,
             tooltip = "Buyer rejection: lower wick " + str.tostring(lwc / atr, "#.0") + " ATR on " + str.tostring(vRel, "#.0") + "× average volume"))
    if uwc >= minW and uwc > lwc and sU >= rcStr
        rcSell := true
        float bt = math.max(open, close)
        rcLn.push(line.new(bar_index, high, bar_index, bt, color = color.new(selC, 70), width = 9))
        rcLn.push(line.new(bar_index, high, bar_index, bt, color = selC, width = 3))
        if not shortSig
            rcLb.push(label.new(bar_index, high, "×" + str.tostring(sU, "#.0"), style = label.style_label_down, color = color(na), textcolor = selC, size = size.small,
             tooltip = "Seller rejection: upper wick " + str.tostring(uwc / atr, "#.0") + " ATR on " + str.tostring(vRel, "#.0") + "× average volume"))
while rcLn.size() > rcKeep * 2
    rcLn.shift().delete()
while rcLb.size() > rcKeep
    rcLb.shift().delete()
 
// ═══════════════════════════════════════════════════════════════════════════
//  4. LAST-BAR DRAWING: butterfly profile, naked POCs, table
// ═══════════════════════════════════════════════════════════════════════════
var array<box>   pBx = array.new<box>()
var array<line>  pLn = array.new<line>()
var array<label> pLb = array.new<label>()
var bool merged = false
var table bn = table.new(position.top_center, 1, 1, frame_color = color(na), frame_width = 0)
tpos = tbPos == "Top left" ? position.top_left : tbPos == "Bottom right" ? position.bottom_right : tbPos == "Bottom left" ? position.bottom_left : position.top_right
var table tb = table.new(tpos, 2, 13, bgcolor = color.new(chart.bg_color, 5), border_color = color.new(chart.fg_color, 90), border_width = 1, frame_color = color.new(chart.fg_color, 80), frame_width = 1)
 
f_cell(int r, string k, string v, color vc) =>
    table.cell(tb, 0, r, k, text_color = color.new(chart.fg_color, 35), text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if barstate.islast
    for b in pBx
        b.delete()
    for l in pLn
        l.delete()
    for x in pLb
        x.delete()
    pBx.clear()
    pLn.clear()
    pLb.clear()
 
    int x0   = bar_index + offB
    int half = int(widB / 2)
    int xc   = x0 + half
 
    // butterfly profile: buyers' wing to the left of the axis, sellers' wing to the right
    // live butterfly profile (display only): last N bars INCLUDING today, so new prices show up.
    // Zones and setups keep using the frozen session build, so they never repaint.
    if showP and bar_index > 60
        int   nL  = math.min(lookN, bar_index)
        float hiL = high
        float loL = low
        for i = 0 to nL - 1
            hiL := math.max(hiL, high[i])
            loL := math.min(loL, low[i])
        if hiL > loL
            float stL = (hiL - loL) / rows
            lb = array.new<float>(rows, 0.0)
            ls = array.new<float>(rows, 0.0)
            for i = 0 to nL - 1
                float h = high[i]
                float l = low[i]
                float r = h - l
                if r > 0
                    float v  = nz(volume[i]) > 0 ? volume[i] : 1.0
                    float bt = math.max(open[i], close[i])
                    float bb = math.min(open[i], close[i])
                    f_spread(ls, bt, h, v * (h - bt) / r, loL, stL, rows)
                    f_spread(lb, l, bb, v * (bb - l) / r, loL, stL, rows)
            float mxS = math.max(lb.max(), ls.max())
            float gap = stL * 0.14
            if mxS > 0
                for k = 0 to rows - 1
                    float top = loL + (k + 1) * stL - gap / 2
                    float bot = loL + k * stL + gap / 2
                    float vb  = lb.get(k)
                    float vs  = ls.get(k)
                    int   wb  = int(math.round(half * vb / mxS))
                    int   ws  = int(math.round(half * vs / mxS))
                    if wb > 0
                        pBx.push(box.new(xc - wb, top, xc, bot, border_color = color(na), border_width = 0, bgcolor = color.new(buyC, int(82 - 70 * vb / mxS))))
                    if ws > 0
                        pBx.push(box.new(xc, top, xc + ws, bot, border_color = color(na), border_width = 0, bgcolor = color.new(selC, int(82 - 70 * vs / mxS))))
            pLn.push(line.new(xc, hiL, xc, loL, color = color.new(chart.fg_color, 70), style = line.style_dotted))
            pLb.push(label.new(xc - int(half / 2), hiL, "BUYERS ◀", color = color(na), textcolor = buyC, style = label.style_label_down, size = size.small))
            pLb.push(label.new(xc + int(half / 2), hiL, "▶ SELLERS", color = color(na), textcolor = selC, style = label.style_label_down, size = size.small))
            pLn.push(line.new(x0, close, x0 + widB, close, color = color.new(chart.fg_color, 40), style = line.style_dotted))
 
    // MAGNET MAP: nearest naked POCs, each with its probability of being reached
    int   openN = nPrice.size()
    float mag   = na
    float magP  = na
    if openN > 0 and not na(avgSR) and avgSR > 0
        array<float> dd = array.new<float>()
        for i = 0 to openN - 1
            float dst = math.abs(nPrice.get(i) - close)
            dd.push(dst <= maxDist * avgSR ? dst : 1e100)      // far magnets are skipped
        int shown = 0
        while shown < math.min(maxN, openN) and dd.min() < 1e99
            int   i  = dd.indexof(dd.min())
            float pr = nPrice.get(i)
            dd.set(i, 1e100)
            shown += 1
            float pb = f_prob(f_bk(math.abs(pr - close) / avgSR))
            // best magnet = the nearest one with at least 50% probability (else simply the nearest)
            if na(mag) or (not na(pb) and pb >= 50 and (na(magP) or magP < 50))
                mag  := pr
                magP := pb
            if showN
                float q  = na(pb) ? 30.0 : pb
                int   w  = q >= 75 ? 3 : q >= 50 ? 2 : 1
                int   tr = int(math.max(0, 75 - 0.75 * q))
                int x1 = math.max(nBar.get(i), bar_index - 4900)
                pLn.push(line.new(x1, pr, x0 - 2, pr, color = color.new(pocC, tr), style = q >= 50 ? line.style_solid : line.style_dashed, width = w))
                // origin dot where the magnet was born
                pLb.push(label.new(x1, pr, "●", style = label.style_label_center, color = color(na), textcolor = color.new(pocC, tr), size = size.small))
                float dist = pr - close
                string born = str.format_time(nTm.get(i), "dd MMM", syminfo.timezone)
                pLb.push(label.new(x0 - 2, pr, "🧲 MAGNET  " + px(pr) + "   " + (na(pb) ? "–" : str.tostring(pb, "#") + "%") + "   " + (dist >= 0 ? "▲ +" : "▼ ") + px(dist),
                     color = color.new(pocC, q >= 75 ? 10 : q >= 50 ? 35 : 70), textcolor = q >= 50 ? #000000 : pocT, style = label.style_label_right, size = q >= 75 ? size.normal : size.small,
                     tooltip = "Untouched volume level (naked POC) from " + born + ".\nChance price trades back here within " + str.tostring(revWin) + " " + sessName + ": " + (na(pb) ? "not enough data yet" : str.tostring(pb, "#") + "%") + "\nDistance from price: " + px(dist)))
    // glow under the best magnet
    if showN and not na(mag) and not na(magP) and magP >= 50
        pLn.push(line.new(bar_index - 20, mag, x0 - 2, mag, color = color.new(pocC, 82), width = 5))
 
    if showTb
        int   res  = revisited + expired
        float rate = res > 0 ? 100.0 * revisited / res : na
        float avgA = revisited > 0 ? sumAge / revisited : na
        int   nT   = wins + losses + tExits
        float hitR = nT > 0 ? 100.0 * wins / nT : na
        float avgR = nT > 0 ? sumR / nT : na
        table.cell(tb, 0, 0, "EYE REJECTION PROFILE", text_color = #FFFFFF, bgcolor = color.new(hdrC, 10), text_size = size.small, text_halign = text.align_center)
        if not merged
            table.merge_cells(tb, 0, 0, 1, 0)
            merged := true
        f_cell(1, "Buyers defend", bzT.size() > 0 ? px(bzB.get(0)) + " – " + px(bzT.get(0)) : "none", buyC)
        f_cell(2, "Sellers defend", szT.size() > 0 ? px(szB.get(0)) + " – " + px(szT.get(0)) : "none", selC)
        f_cell(3, "Best magnet", na(mag) ? "–" : px(mag) + (na(magP) ? "" : "  ·  " + str.tostring(magP, "#") + "%"), pocT)
        array<string> bName = array.from("Magnet < ½ " + sessUnit + " range", "Magnet ½–1 " + sessUnit + " range", "Magnet 1–2 " + sessUnit + " ranges", "Magnet 2+ " + sessUnit + " ranges")
        for b = 0 to 3
            float pb = f_prob(b)
            f_cell(4 + b, bName.get(b), na(pb) ? "–" : str.tostring(pb, "#") + "%  (" + str.tostring(bTot.get(b)) + ")", pocT)
        f_cell(8, "Setups · hit rate · avg R", str.tostring(nT) + "  ·  " + (na(hitR) ? "–" : str.tostring(hitR, "#") + "%") + "  ·  " + (na(avgR) ? "–" : (avgR >= 0 ? "+" : "") + str.tostring(avgR, "#.00") + "R"),
             na(avgR) ? chart.fg_color : avgR >= 0 ? buyC : selC)
        f_cell(9, "Open magnets", str.tostring(openN), pocT)
        for g = 0 to 2
            int   gn = gN.get(g)
            float gh = gn > 0 ? 100.0 * gW.get(g) / gn : na
            float ga = gn > 0 ? gR.get(g) / gn : na
            f_cell(10 + g, f_stars(g + 1) + " setups", gn == 0 ? "–" : str.tostring(gh, "#") + "% hit  ·  " + (ga >= 0 ? "+" : "") + str.tostring(ga, "#.00") + "R  (" + str.tostring(gn) + ")",
                 na(ga) ? chart.fg_color : ga >= 0 ? buyC : selC)
 
    // status banner: what is happening now, in one line
    bool inB = bzT.size() > 0 and close <= bzT.get(0) and close >= bzB.get(0)
    bool inS = szT.size() > 0 and close <= szT.get(0) and close >= szB.get(0)
    string st = tOn ? (tDir == 1 ? "▲ LONG ACTIVE " : "▼ SHORT ACTIVE ") + f_stars(tStars) + "   TP " + px(tTP) + "   SL " + px(tSL) :
         inB ? "PRICE AT BUYER ZONE  ·  watch for ▲ REJECT" : inS ? "PRICE AT SELLER ZONE  ·  watch for ▼ REJECT" : "BETWEEN ZONES  ·  wait"
    if not na(mag)
        st += "      MAGNET " + (mag >= close ? "▲ " : "▼ ") + px(mag) + (na(magP) ? "" : "  ·  " + str.tostring(magP, "#") + "% in " + str.tostring(revWin) + " " + sessName)
    color sc = tOn ? (tDir == 1 ? buyC : selC) : inB ? buyC : inS ? selC : color.new(chart.fg_color, 30)
    table.cell(bn, 0, 0, st, text_color = #FFFFFF, bgcolor = sc, text_size = size.normal)
 
// ═══════════════════════════════════════════════════════════════════════════
//  ALERTS
// ═══════════════════════════════════════════════════════════════════════════
alertcondition(longSig, "Rejection setup ▲", "{{ticker}} buyer-zone rejection setup")
alertcondition(shortSig, "Rejection setup ▼", "{{ticker}} seller-zone rejection setup")
alertcondition((longSig or shortSig) and tStars >= 3, "⭐⭐⭐ setup", "{{ticker}} 3-star rejection setup (zone + strong candle + magnet target)")
alertcondition(barstate.isconfirmed and tpHit, "Setup target hit", "{{ticker}} rejection setup reached its target")
alertcondition(barstate.isconfirmed and slHit, "Setup stop hit", "{{ticker}} rejection setup hit its stop")
alertcondition(barstate.isconfirmed and touchN, "Magnet reached", "{{ticker}} traded back to a naked POC magnet")
alertcondition(rcBuy, "Buyer rejection candle", "{{ticker}} strong buyer rejection wick")
alertcondition(rcSell, "Seller rejection candle", "{{ticker}} strong seller rejection wick")
 
if detailAlerts and (longSig or shortSig)
    alert(syminfo.ticker + " — Eye Rejection Profile: " + (longSig ? "BUYER" : "SELLER") + " zone rejection " + f_stars(tStars) + ". Entry " + px(tE) + ", stop " + px(tSL) +
         ", target " + px(tTP) + " (" + tpTag + ")", alert.freq_once_per_bar_close)

← 返回列表