Wedge Hunter [Neblok]

NeBlok · study · 596 行 · 点赞 349 · 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/
// © NeBlok
 
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Neblok
//
// ═══════════════════════════════════════════════════════════════════════════════
//  WEDGE HUNTER [Neblok]
//  Rising & falling wedge detector with least-squares line fitting, quality
//  scoring, breakout confirmation, measured-move targets, 3D neon rendering,
//  live hit-rate tracking and alerts.
// ═══════════════════════════════════════════════════════════════════════════════
 
//@version=6
indicator("Wedge Hunter [Neblok]", "Wedge Hunter [Neblok]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 1000)
 
// ═══════════════════════════════ INPUTS ═══════════════════════════════════════
grpD = "Detection"
pivLeft     = input.int(5, "Pivot Left Bars", minval = 2, maxval = 30, group = grpD)
pivRight    = input.int(5, "Pivot Right Bars", minval = 1, maxval = 30, group = grpD, tooltip = "Swing points confirm this many bars after they print. Wedges are drawn once enough swings confirm. Breakout signals fire on bar close and do not repaint.")
pivN        = input.int(3, "Swings Per Line", minval = 2, maxval = 5, group = grpD, tooltip = "How many of the latest swing highs / swing lows are fitted (least-squares regression) into each wedge line. 3 = classic textbook wedge.")
minLen      = input.int(20, "Min Pattern Length (bars)", minval = 8, maxval = 300, group = grpD)
maxLen      = input.int(200, "Max Pattern Length (bars)", minval = 20, maxval = 600, group = grpD)
fitTol      = input.float(0.6, "Touch Tolerance (× ATR)", minval = 0.1, maxval = 3.0, step = 0.05, group = grpD, tooltip = "How far a swing may sit from its fitted line and still count as a touch.")
maxConv     = input.float(0.75, "Max Width Ratio (end ÷ start)", minval = 0.2, maxval = 0.95, step = 0.05, group = grpD, tooltip = "How much the wedge must narrow. 0.75 = at least 25% narrower at the last swing than at its mouth.")
minSlope    = input.float(0.01, "Min Line Slope (× ATR per bar)", minval = 0.0, maxval = 0.5, step = 0.005, group = grpD, tooltip = "Both lines must slope the same way by at least this much. Filters out flat-sided triangles.")
minScore    = input.int(55, "Min Quality Score (0-100)", minval = 0, maxval = 100, group = grpD)
showFalling = input.bool(true, "Detect Falling Wedges (Bullish)", group = grpD)
showRising  = input.bool(true, "Detect Rising Wedges (Bearish)", group = grpD)
 
grpB = "Breakout & Targets"
breakBuf     = input.float(0.10, "Breakout Buffer (× ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = grpB, tooltip = "A bar must CLOSE this far beyond the wedge line to count as a breakout.")
useVol       = input.bool(false, "Require Volume Surge", group = grpB)
volMult      = input.float(1.3, "Volume Surge (× 20-bar avg)", minval = 1.0, maxval = 5.0, step = 0.1, group = grpB)
tp1Mult      = input.float(0.618, "TP1 (× wedge height)", minval = 0.1, maxval = 5.0, step = 0.05, group = grpB)
tp2Mult      = input.float(1.0, "TP2 (× wedge height)", minval = 0.1, maxval = 5.0, step = 0.05, group = grpB, tooltip = "Classic measured move = full height of the wedge mouth projected from the breakout.")
maxTradeBars = input.int(120, "Max Bars in Trade", minval = 5, maxval = 1000, group = grpB, tooltip = "Trades still open after this many bars are closed as TIME EXIT.")
 
grpS = "Stop Loss"
useStop  = input.bool(false, "Use Stop Loss", group = grpS, tooltip = "OFF by default. When off, no stop box is drawn and trades only close at TP2 or the max-bars time exit.")
stopMode = input.string("Last Swing", "Stop Placement", options = ["Last Swing", "Opposite Line"], group = grpS)
stopBuf  = input.float(0.25, "Stop Buffer (× ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = grpS)
moveBE   = input.bool(true, "Move Stop to Breakeven after TP1", group = grpS)
 
grpV = "Visuals"
colBull   = input.color(#39FF14, "Falling Wedge (Bullish)", group = grpV)
colBear   = input.color(#FF2079, "Rising Wedge (Bearish)", group = grpV)
colApex   = input.color(#FFF01F, "Apex / Info", group = grpV)
colTP     = input.color(#00F0FF, "Targets", group = grpV)
colSL     = input.color(#FF3131, "Stop", group = grpV)
use3D     = input.bool(true, "3D Rendering", group = grpV)
depthBars = input.int(6, "3D Depth (bars)", minval = 1, maxval = 20, group = grpV)
depthATR  = input.float(0.5, "3D Lift (× ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = grpV)
useGlow   = input.bool(true, "Neon Glow", group = grpV)
showApex  = input.bool(true, "Project Lines to Apex", group = grpV)
showTouch = input.bool(true, "Mark Touch Points", group = grpV)
showBoxes = input.bool(true, "Target / Stop Boxes", group = grpV)
projBars  = input.int(30, "Target Box Width (bars)", minval = 5, maxval = 200, group = grpV)
keepFail  = input.bool(true, "Keep Failed / Expired Wedges (dimmed)", group = grpV)
flashBg   = input.bool(true, "Flash Background on Breakout", group = grpV)
maxKeep   = input.int(8, "Max Patterns & Trades Kept", minval = 1, maxval = 25, group = grpV)
lblSizeIn = input.string("Large", "Label & Box Text Size", options = ["Normal", "Large", "Huge"], group = grpV)
 
grpT = "Dashboard"
showDash  = input.bool(true, "Show Dashboard", group = grpT)
dashPosIn = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Middle Right", "Bottom Right", "Bottom Left"], group = grpT)
dashSzIn  = input.string("Large", "Text Size", options = ["Small", "Normal", "Large"], group = grpT)
 
// ═══════════════════════════════ HELPERS ══════════════════════════════════════
f_size(string s) =>
    switch s
        "Huge"  => size.huge
        "Large" => size.large
        "Small" => size.small
        => size.normal
 
lblSize  = f_size(lblSizeIn)
subSize  = lblSizeIn == "Huge" ? size.large : lblSizeIn == "Large" ? size.normal : size.small
dashSize = f_size(dashSzIn)
dashPos  = switch dashPosIn
    "Top Left"     => position.top_left
    "Middle Right" => position.middle_right
    "Bottom Right" => position.bottom_right
    "Bottom Left"  => position.bottom_left
    => position.top_right
 
f_grade(float s) =>
    s >= 85 ? "A+" : s >= 72 ? "A" : s >= 60 ? "B" : "C"
 
f_gradeCol(string g) =>
    switch g
        "A+" => colTP
        "A"  => colBull
        "B"  => colApex
        => colSL
 
f_rate(int w, int n) =>
    n > 0 ? str.tostring(w) + "/" + str.tostring(n) + "  ·  " + str.tostring(100.0 * w / n, "#") + "%" : "—"
 
// ═══════════════════════════════ CORE SERIES ══════════════════════════════════
atr    = ta.atr(14)
volAvg = ta.sma(nz(volume), 20)
ph     = ta.pivothigh(high, pivLeft, pivRight)
pl     = ta.pivotlow(low, pivLeft, pivRight)
 
var phX = array.new<int>()
var phY = array.new<float>()
var plX = array.new<int>()
var plY = array.new<float>()
var int lastDone = -1
 
// ═══════════════════════════════ TYPES ════════════════════════════════════════
type Wedge
    int    dir      // 1 = falling wedge (bullish), -1 = rising wedge (bearish)
    int    x0
    float  uI
    float  us
    float  lI
    float  ls
    int    apexX
    float  apexY
    float  height
    float  score
    string grade
    int    tU
    int    tL
    float  conv
    float  depth
    int    state    // 0 forming, 1 broke out, 2 failed, 3 expired
    array<int>      tX
    array<float>    tY
    array<line>     lns
    array<linefill> fls
    array<label>    lbs
 
type Trade
    int    dir
    int    x
    float  entry
    float  stop
    float  tp1
    float  tp2
    bool   hit1
    bool   open
    array<box>   bxs
    array<line>  lns
    array<label> lbs
 
// ═══════════════════════════════ WEDGE METHODS ════════════════════════════════
method uAt(Wedge w, int x) =>
    w.uI + w.us * (x - w.x0)
 
method lAt(Wedge w, int x) =>
    w.lI + w.ls * (x - w.x0)
 
method wipe(Wedge w) =>
    for f in w.fls
        f.delete()
    for l in w.lns
        l.delete()
    for b in w.lbs
        b.delete()
    w.fls.clear()
    w.lns.clear()
    w.lbs.clear()
 
method stateText(Wedge w) =>
    switch w.state
        1 => w.dir == 1 ? "BROKE OUT ▲" : "BROKE DOWN ▼"
        2 => "FAILED ✖"
        3 => "EXPIRED ⌛"
        => "FORMING…"
 
method draw(Wedge w, int xEnd) =>
    w.wipe()
    color c     = w.dir == 1 ? colBull : colBear
    bool  faded = w.state >= 2
    int   x0    = w.x0
    float u0    = w.uAt(x0)
    float l0    = w.lAt(x0)
    float u1    = w.uAt(xEnd)
    float l1    = w.lAt(xEnd)
    int   dx    = use3D ? depthBars : 0
    float dy    = use3D ? w.depth : 0.0
    int   tCore = faded ? 45 : 0     // front face lines
    int   tEdge = faded ? 60 : 20    // visible 3D edges
    int   tHide = faded ? 82 : 60    // hidden 3D edges (dashed)
    line  bU    = na
    line  bR    = na
    // ── 3D box: hidden edges first (dashed), then the visible back / depth edges
    if use3D
        w.lns.push(line.new(x0 + dx, l0 + dy, xEnd + dx, l1 + dy, color = color.new(c, tHide), width = 1, style = line.style_dashed))
        w.lns.push(line.new(x0 + dx, u0 + dy, x0 + dx, l0 + dy, color = color.new(c, tHide), width = 1, style = line.style_dashed))
        w.lns.push(line.new(x0, l0, x0 + dx, l0 + dy, color = color.new(c, tHide), width = 1, style = line.style_dashed))
        bU := line.new(x0 + dx, u0 + dy, xEnd + dx, u1 + dy, color = color.new(c, tEdge), width = 2)
        bR := line.new(xEnd + dx, u1 + dy, xEnd + dx, l1 + dy, color = color.new(c, tEdge), width = 2)
        w.lns.push(bU)
        w.lns.push(bR)
        w.lns.push(line.new(x0, u0, x0 + dx, u0 + dy, color = color.new(c, tEdge), width = 2))
        w.lns.push(line.new(xEnd, u1, xEnd + dx, u1 + dy, color = color.new(c, tEdge), width = 2))
        w.lns.push(line.new(xEnd, l1, xEnd + dx, l1 + dy, color = color.new(c, tEdge), width = 2))
    // ── neon glow halo
    if useGlow and not faded
        w.lns.push(line.new(x0, u0, xEnd, u1, color = color.new(c, 80), width = 8))
        w.lns.push(line.new(x0, l0, xEnd, l1, color = color.new(c, 80), width = 8))
    // ── front face
    line fU = line.new(x0, u0, xEnd, u1, color = color.new(c, tCore), width = faded ? 2 : 3)
    line fL = line.new(x0, l0, xEnd, l1, color = color.new(c, tCore), width = faded ? 2 : 3)
    line fR = line.new(xEnd, u1, xEnd, l1, color = color.new(c, tCore), width = use3D ? 2 : 1, style = use3D ? line.style_solid : line.style_dashed)
    w.lns.push(fU)
    w.lns.push(fL)
    w.lns.push(fR)
    w.lns.push(line.new(x0, u0, x0, l0, color = color.new(c, tCore), width = 2))
    // ── face shading: front lightest, top brightest, right side in between
    if not faded or use3D
        w.fls.push(linefill.new(fU, fL, color.new(c, faded ? 94 : 85)))
    if use3D
        w.fls.push(linefill.new(fU, bU, color.new(c, faded ? 85 : 60)))
        w.fls.push(linefill.new(fR, bR, color.new(c, faded ? 88 : 70)))
    // ── projection to apex (live wedges only)
    if showApex and w.state == 0
        int xa = math.min(w.apexX, bar_index + 480)
        w.lns.push(line.new(xEnd, u1, xa, w.uAt(xa), color = color.new(c, 30), width = 2, style = line.style_dotted))
        w.lns.push(line.new(xEnd, l1, xa, w.lAt(xa), color = color.new(c, 30), width = 2, style = line.style_dotted))
        if w.apexX <= bar_index + 480
            w.lbs.push(label.new(w.apexX, w.apexY, "◆ APEX", style = label.style_label_left, color = colApex, textcolor = color.black, size = subSize))
    // ── touch points
    if showTouch
        for [i, tx] in w.tX
            w.lbs.push(label.new(tx, w.tY.get(i), "", style = label.style_circle, color = faded ? color.new(c, 60) : c, size = size.small))
    // ── main tag
    string nm  = w.dir == 1 ? "FALLING WEDGE" : "RISING WEDGE"
    string bia = w.dir == 1 ? "Bullish bias ▲" : "Bearish bias ▼"
    string txt = nm + "  [" + w.grade + "]\n" + bia + "  ·  Score " + str.tostring(w.score, "#") + "\n" + w.stateText()
    w.lbs.push(label.new(x0, u0 + dy, txt, style = label.style_label_down, color = faded ? color.new(c, 50) : c, textcolor = color.black, size = lblSize))
 
// ═══════════════════════════════ TRADE DRAWING ════════════════════════════════
f_cube(Trade t, int l, int r, float a, float b, color c, string txt) =>
    float top = math.max(a, b)
    float bot = math.min(a, b)
    if use3D
        int   dx = depthBars
        float dy = depthATR * atr * 0.6
        t.bxs.push(box.new(l + dx, top + dy, r + dx, bot + dy, border_color = color.new(c, 55), border_width = 1, bgcolor = color.new(c, 93)))
        t.lns.push(line.new(l, top, l + dx, top + dy, color = color.new(c, 35), width = 1))
        t.lns.push(line.new(r, top, r + dx, top + dy, color = color.new(c, 35), width = 1))
        t.lns.push(line.new(r, bot, r + dx, bot + dy, color = color.new(c, 35), width = 1))
    t.bxs.push(box.new(l, top, r, bot, border_color = c, border_width = 2, bgcolor = color.new(c, 80), text = txt, text_size = lblSize, text_color = chart.fg_color, text_halign = text.align_center, text_valign = text.align_center))
 
f_killTrade(Trade t) =>
    for b in t.bxs
        b.delete()
    for l in t.lns
        l.delete()
    for lb in t.lbs
        lb.delete()
 
// ═══════════════════════════════ DETECTION ════════════════════════════════════
// least-squares fit of the last n swings → [slope, intercept] with x measured from x0
f_fit(array<int> xs, array<float> ys, int n, int x0) =>
    int   sz  = xs.size()
    float sx  = 0.0
    float sy  = 0.0
    float sxx = 0.0
    float sxy = 0.0
    for i = sz - n to sz - 1
        float x = float(xs.get(i) - x0)
        float y = ys.get(i)
        sx  += x
        sy  += y
        sxx += x * x
        sxy += x * y
    float d = n * sxx - sx * sx
    float m = d != 0 ? (n * sxy - sx * sy) / d : 0.0
    float b = (sy - m * sx) / n
    [m, b]
 
// worst and summed residual of the fitted swings
f_maxRes(array<int> xs, array<float> ys, int n, int x0, float b, float m) =>
    int   sz = xs.size()
    float mr = 0.0
    float sr = 0.0
    for i = sz - n to sz - 1
        float r = math.abs(ys.get(i) - (b + m * (xs.get(i) - x0)))
        mr := math.max(mr, r)
        sr += r
    [mr, sr]
 
// every stored swing inside the pattern that sits on the line counts as a touch
f_touch(array<int> xs, array<float> ys, int x0, float b, float m, float tol, array<int> ox, array<float> oy) =>
    int cnt = 0
    for [i, x] in xs
        if x >= x0
            float y = ys.get(i)
            if math.abs(y - (b + m * (x - x0))) <= tol
                cnt += 1
                ox.push(x)
                oy.push(y)
    cnt
 
f_scan() =>
    Wedge res = na
    if phX.size() >= pivN and plX.size() >= pivN and atr > 0
        int x0    = math.min(phX.get(phX.size() - pivN), plX.get(plX.size() - pivN))
        int xLast = math.max(phX.last(), plX.last())
        int len   = bar_index - x0
        if x0 > lastDone and xLast - x0 >= minLen and len <= maxLen
            [us, uI] = f_fit(phX, phY, pivN, x0)
            [ls, lI] = f_fit(plX, plY, pivN, x0)
            float usN = us / atr
            float lsN = ls / atr
            int   dir = usN < -minSlope and lsN < -minSlope and us < ls ? 1 : usN > minSlope and lsN > minSlope and ls > us ? -1 : 0
            bool  dirOk = (dir == 1 and showFalling) or (dir == -1 and showRising)
            float w0 = uI - lI
            float wL = (uI + us * (xLast - x0)) - (lI + ls * (xLast - x0))
            float wN = (uI + us * len) - (lI + ls * len)
            if dirOk and w0 > 0 and wL > 0 and wN > 0
                float conv = wL / w0
                float tol  = fitTol * atr
                [mrU, srU] = f_maxRes(phX, phY, pivN, x0, uI, us)
                [mrL, srL] = f_maxRes(plX, plY, pivN, x0, lI, ls)
                if conv <= maxConv and mrU <= tol and mrL <= tol
                    // price must have respected the wedge the whole way
                    bool  inside = true
                    float cTol   = breakBuf * atr
                    float vNew   = 0.0
                    float vOld   = 0.0
                    for k = 0 to len
                        int   x = bar_index - k
                        float u = uI + us * (x - x0)
                        float l = lI + ls * (x - x0)
                        if close[k] > u + cTol or close[k] < l - cTol or high[k] > u + tol or low[k] < l - tol
                            inside := false
                            break
                        if k < len / 2
                            vNew += nz(volume[k])
                        else
                            vOld += nz(volume[k])
                    if inside
                        array<int>   tx = array.new<int>()
                        array<float> ty = array.new<float>()
                        int   tU     = f_touch(phX, phY, x0, uI, us, tol, tx, ty)
                        int   tL     = f_touch(plX, plY, x0, lI, ls, tol, tx, ty)
                        float sTouch = math.min(tU + tL, 8) / 8.0 * 30.0
                        float sConv  = math.min(math.max((1.0 - conv) / 0.6, 0.0), 1.0) * 25.0
                        float avgRes = (srU + srL) / (2 * pivN) / atr
                        float sFit   = math.max(1.0 - avgRes / fitTol, 0.0) * 20.0
                        float vr     = vOld > 0 ? vNew / vOld : 1.0
                        float sVol   = math.min(math.max((1.1 - vr) / 0.5, 0.0), 1.0) * 15.0
                        float sLen   = math.min((xLast - x0) / (minLen * 2.5), 1.0) * 10.0
                        float score  = sTouch + sConv + sFit + sVol + sLen
                        if score >= minScore
                            float xa = w0 / (ls - us)
                            res := Wedge.new(dir = dir, x0 = x0, uI = uI, us = us, lI = lI, ls = ls, apexX = x0 + math.round(xa), apexY = uI + us * xa, height = w0, score = score, grade = f_grade(score), tU = tU, tL = tL, conv = conv, depth = depthATR * atr, state = 0, tX = tx, tY = ty, lns = array.new<line>(), fls = array.new<linefill>(), lbs = array.new<label>())
    res
 
// ═══════════════════════════════ STATE ════════════════════════════════════════
var Wedge         active = na
var array<Wedge>  hist   = array.new<Wedge>()
var array<Trade>  trades = array.new<Trade>()
var int    nBull = 0
var int    wBull = 0
var int    nBear = 0
var int    wBear = 0
var string lastSig    = "—"
var color  lastSigCol = color.gray
var float  sigEntry   = na
var float  sigStop    = na
var float  sigTP1     = na
var float  sigTP2     = na
 
bool evNew  = false
bool evBull = false
bool evBear = false
bool evFail = false
bool evTP   = false
bool evSL   = false
 
// ── collect swings
if not na(ph)
    phX.push(bar_index - pivRight)
    phY.push(ph)
    if phX.size() > 20
        phX.shift()
        phY.shift()
if not na(pl)
    plX.push(bar_index - pivRight)
    plY.push(pl)
    if plX.size() > 20
        plX.shift()
        plY.shift()
 
// ── scan on every newly confirmed swing
if not na(ph) or not na(pl)
    Wedge cand = f_scan()
    if not na(cand)
        bool isNew = na(active) or cand.dir != active.dir or cand.x0 != active.x0
        if not na(active)
            active.wipe()
        active := cand
        active.draw(bar_index)
        evNew := isNew
 
// ── manage the live wedge
float aU = na
float aL = na
if not na(active)
    float uNow   = active.uAt(bar_index)
    float lNow   = active.lAt(bar_index)
    aU := uNow
    aL := lNow
    float buf    = breakBuf * atr
    bool  volOk  = not useVol or nz(volume) > volAvg * volMult
    int   result = 0
    if bar_index >= active.apexX
        result := 3
    else if active.dir == 1
        if close > uNow + buf and volOk
            result := 1
        else if close < lNow - buf
            result := 2
    else
        if close < lNow - buf and volOk
            result := 1
        else if close > uNow + buf
            result := 2
 
    if result == 1
        int   d     = active.dir
        float entry = close
        float sw    = d == 1 ? plY.last() - stopBuf * atr : phY.last() + stopBuf * atr
        float ol    = d == 1 ? lNow - stopBuf * atr : uNow + stopBuf * atr
        float stop  = na
        if useStop
            stop := stopMode == "Last Swing" ? sw : ol
            if (d == 1 and stop >= entry) or (d == -1 and stop <= entry)
                stop := ol
        float tp1   = entry + d * active.height * tp1Mult
        float tp2   = entry + d * active.height * tp2Mult
        Trade t     = Trade.new(d, bar_index, entry, stop, tp1, tp2, false, true, array.new<box>(), array.new<line>(), array.new<label>())
        color c     = d == 1 ? colBull : colBear
        string nm   = d == 1 ? "Falling Wedge" : "Rising Wedge"
        string head = d == 1 ? "▲ BREAKOUT" : "▼ BREAKDOWN"
        t.lbs.push(label.new(bar_index, d == 1 ? low - atr * 0.3 : high + atr * 0.3, head + "\n" + nm + " [" + active.grade + "]\nEntry " + str.tostring(entry, format.mintick), style = d == 1 ? label.style_label_up : label.style_label_down, color = c, textcolor = color.black, size = lblSize))
        if showBoxes
            int r = bar_index + projBars
            f_cube(t, bar_index, r, entry, tp1, colTP, "TP1  " + str.tostring(tp1, format.mintick))
            f_cube(t, bar_index, r, tp1, tp2, colTP, "TP2  " + str.tostring(tp2, format.mintick))
            if useStop
                f_cube(t, bar_index, r, entry, stop, colSL, "STOP  " + str.tostring(stop, format.mintick))
        trades.push(t)
        evBull     := d == 1
        evBear     := d == -1
        lastSig    := (d == 1 ? "▲ LONG  " : "▼ SHORT  ") + str.tostring(entry, format.mintick)
        lastSigCol := c
        sigEntry   := entry
        sigStop    := stop
        sigTP1     := tp1
        sigTP2     := tp2
 
    if result > 0
        active.state := result
        active.draw(math.min(bar_index, active.apexX))
        if result == 1 or keepFail
            hist.push(active)
        else
            active.wipe()
        if result == 2
            evFail := true
        active   := na
        lastDone := bar_index
        if hist.size() > maxKeep
            Wedge old = hist.shift()
            old.wipe()
 
// ── manage open trades
for t in trades
    if t.open and bar_index > t.x
        int    d       = t.dir
        bool   stopHit = useStop and not na(t.stop) and (d == 1 ? low <= t.stop : high >= t.stop)
        bool   tp1Hit  = d == 1 ? high >= t.tp1 : low <= t.tp1
        bool   tp2Hit  = d == 1 ? high >= t.tp2 : low <= t.tp2
        string res     = ""
        if stopHit
            res := t.hit1 and moveBE ? "■ BREAKEVEN" : "✖ STOPPED"
            if not t.hit1
                if d == 1
                    nBull += 1
                else
                    nBear += 1
            evSL := true
        else
            if tp1Hit and not t.hit1
                t.hit1 := true
                if d == 1
                    nBull += 1
                    wBull += 1
                else
                    nBear += 1
                    wBear += 1
                if useStop and moveBE
                    t.stop := t.entry
                evTP := true
                t.lbs.push(label.new(bar_index, d == 1 ? high + atr * 0.3 : low - atr * 0.3, "✔ TP1", style = d == 1 ? label.style_label_down : label.style_label_up, color = colTP, textcolor = color.black, size = subSize))
            if tp2Hit
                res  := "✔ TP2"
                evTP := true
            else if bar_index - t.x >= maxTradeBars
                res := "⏱ TIME EXIT"
                if not t.hit1
                    if d == 1
                        nBull += 1
                    else
                        nBear += 1
        if res != ""
            t.open := false
            bool  good  = str.startswith(res, "✔")
            bool  above = (d == 1) == good
            color rc    = good ? colTP : str.startswith(res, "✖") ? colSL : colApex
            t.lbs.push(label.new(bar_index, above ? high + atr * 0.3 : low - atr * 0.3, res, style = above ? label.style_label_down : label.style_label_up, color = rc, textcolor = color.black, size = subSize))
 
while trades.size() > maxKeep and not trades.first().open
    f_killTrade(trades.shift())
 
// ── keep the live wedge stretched to the current bar
if barstate.islast and not na(active)
    active.draw(bar_index)
 
// ═══════════════════════════════ OUTPUTS ══════════════════════════════════════
plot(aU, "Wedge Upper", color = colBull, display = display.data_window)
plot(aL, "Wedge Lower", color = colBear, display = display.data_window)
bgcolor(flashBg and evBull ? color.new(colBull, 85) : flashBg and evBear ? color.new(colBear, 85) : na, title = "Breakout Flash")
 
// ═══════════════════════════════ DASHBOARD ════════════════════════════════════
var table dash = table.new(dashPos, 2, 11, bgcolor = color.new(#05070A, 8), frame_color = colTP, frame_width = 2, border_color = color.new(colTP, 70), border_width = 1)
 
f_row(int r, string k, string v, color vc) =>
    table.cell(dash, 0, r, k, text_color = color.new(#E6EDF3, 0), text_size = dashSize, text_halign = text.align_left)
    table.cell(dash, 1, r, v, text_color = vc, text_size = dashSize, text_halign = text.align_right)
 
if barstate.islast and showDash
    table.cell(dash, 0, 0, "WEDGE HUNTER", bgcolor = colTP, text_color = color.black, text_size = dashSize, text_halign = text.align_left)
    table.cell(dash, 1, 0, "[Neblok]", bgcolor = colTP, text_color = color.black, text_size = dashSize, text_halign = text.align_right)
    string pat  = "Scanning…"
    string bias = "—"
    string qual = "—"
    string tch  = "—"
    string cmp  = "—"
    string apx  = "—"
    string trg  = "—"
    color  ac   = color.gray
    color  qc   = color.gray
    if not na(active)
        ac   := active.dir == 1 ? colBull : colBear
        qc   := f_gradeCol(active.grade)
        pat  := active.dir == 1 ? "FALLING WEDGE" : "RISING WEDGE"
        bias := active.dir == 1 ? "BULLISH ▲" : "BEARISH ▼"
        qual := str.tostring(active.score, "#") + " / 100  ·  " + active.grade
        tch  := "Upper " + str.tostring(active.tU) + "  ·  Lower " + str.tostring(active.tL)
        cmp  := str.tostring((1.0 - active.conv) * 100.0, "#") + "%"
        apx  := str.tostring(active.apexX - bar_index)
        trg  := str.tostring(active.dir == 1 ? aU : aL, format.mintick)
    f_row(1, "Pattern", pat, ac)
    f_row(2, "Bias", bias, ac)
    f_row(3, "Quality", qual, qc)
    f_row(4, "Touches", tch, color.white)
    f_row(5, "Compression", cmp, colApex)
    f_row(6, "Bars to Apex", apx, colApex)
    f_row(7, "Trigger Level", trg, ac)
    f_row(8, "Falling W. TP1 Rate", f_rate(wBull, nBull), colBull)
    f_row(9, "Rising W. TP1 Rate", f_rate(wBear, nBear), colBear)
    f_row(10, "Last Signal", lastSig, lastSigCol)
 
// ═══════════════════════════════ ALERTS ═══════════════════════════════════════
alertcondition(evNew, "Wedge Forming", "Wedge Hunter [Neblok]: new wedge forming on {{ticker}} ({{interval}})")
alertcondition(evBull, "Falling Wedge Breakout (Long)", "Wedge Hunter [Neblok]: FALLING WEDGE BREAKOUT on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(evBear, "Rising Wedge Breakdown (Short)", "Wedge Hunter [Neblok]: RISING WEDGE BREAKDOWN on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(evFail, "Wedge Failed", "Wedge Hunter [Neblok]: wedge failed on {{ticker}} ({{interval}})")
alertcondition(evTP, "Target Hit", "Wedge Hunter [Neblok]: target hit on {{ticker}} ({{interval}})")
alertcondition(evSL, "Stop Hit", "Wedge Hunter [Neblok]: stop hit on {{ticker}} ({{interval}})")
 
f_levels() =>
    " | Entry " + str.tostring(sigEntry, format.mintick) + (useStop ? " | Stop " + str.tostring(sigStop, format.mintick) : "") + " | TP1 " + str.tostring(sigTP1, format.mintick) + " | TP2 " + str.tostring(sigTP2, format.mintick)
 
if evBull
    alert("Wedge Hunter [Neblok] ▲ FALLING WEDGE BREAKOUT | " + syminfo.ticker + " " + timeframe.period + f_levels(), alert.freq_once_per_bar_close)
if evBear
    alert("Wedge Hunter [Neblok] ▼ RISING WEDGE BREAKDOWN | " + syminfo.ticker + " " + timeframe.period + f_levels(), alert.freq_once_per_bar_close)
if evNew
    alert("Wedge Hunter [Neblok] — new wedge forming | " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if evFail
    alert("Wedge Hunter [Neblok] ✖ wedge failed | " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if evTP
    alert("Wedge Hunter [Neblok] ✔ target hit | " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if evSL
    alert("Wedge Hunter [Neblok] stop hit | " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)

← 返回列表