Breaker & Mitigation Blocks

NeuraAlgo · study · 330 行 · 点赞 158 · TradingView 原页

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

Pine Script

//@version=6
indicator("Breaker & Mitigation Blocks", overlay = true, max_bars_back = 500, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═════════════════════════════ INPUTS ═════════════════════════════
grpS = "Structure"
swingLen = input.int(7, "Swing length", minval = 2, maxval = 50, group = grpS)
showMss  = input.bool(true, "Show market structure shifts (MSS)", group = grpS)
showSw   = input.bool(false, "Show swing highs / lows", group = grpS)
 
grpB = "Blocks"
showBrk   = input.bool(true, "Show breaker blocks", group = grpB)
showMit   = input.bool(true, "Show mitigation blocks", group = grpB)
useBody   = input.bool(false, "Use candle body instead of wicks", group = grpB)
searchLen = input.int(20, "Search back for the block candle (bars)", minval = 1, maxval = 100, group = grpB)
maxBlocks = input.int(8, "Max active blocks", minval = 1, maxval = 50, group = grpB)
zoneExt   = input.int(15, "Extend blocks right (bars)", minval = 0, maxval = 200, group = grpB)
 
grpG = "Signals"
sigMode  = input.string("Breakers + Mitigation", "Signal on retest of", options = ["Breakers + Mitigation", "Breakers only", "Mitigation only", "Off"], group = grpG)
maxSig   = input.int(2, "Max signals per block", minval = 1, maxval = 10, group = grpG)
withBias = input.bool(true, "Only signal with the current structure bias", group = grpG)
showRisk = input.bool(true, "Show SL / TP for the latest signal", group = grpG)
slBuf    = input.float(0.25, "SL buffer beyond block (x ATR)", minval = 0, step = 0.05, group = grpG)
rr       = input.float(2.0, "Take profit (reward : risk)", minval = 0.5, step = 0.25, group = grpG)
 
grpV = "Style"
bullBrkCol = input.color(#00c896, "Bullish breaker", group = grpV)
bearBrkCol = input.color(#ff4d5e, "Bearish breaker", group = grpV)
bullMitCol = input.color(#4fc3f7, "Bullish mitigation", group = grpV)
bearMitCol = input.color(#ffb74d, "Bearish mitigation", group = grpV)
showDash   = input.bool(true, "Show dashboard", group = grpV)
dashPosIn  = input.string("Top Right", "Dashboard position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpV)
 
// ═════════════════════════════ TYPES & STATE ═════════════════════════════
type Block
    box   bx
    float top
    float btm
    int   dir           // 1 bullish (support), -1 bearish (resistance)
    bool  breaker       // true breaker, false mitigation
    int   created
    int   signals = 0
    int   lastSig = -100
 
var array<Block> blocks = array.new<Block>()
 
var float h0 = na
var int   h0Bar = na
var float h1 = na
var int   h1Bar = na
var float l0 = na
var int   l0Bar = na
var float l1 = na
var int   l1Bar = na
var bool  highBroken = true
var bool  lowBroken  = true
var int   bias       = 0
var string lastEvent  = "—"
var string lastSignal = "—"
 
var line  enL  = na
var line  slL  = na
var line  tpL  = na
var label slLb = na
var label tpLb = na
 
// The latest signal's trade, followed until SL or TP is hit
var bool  tradeOpen = false
var int   tradeDir  = 0
var int   tradeBar  = na
var float tradeSL   = na
var float tradeTP   = na
int riskPad = 5    // how far past the latest candle the SL / TP labels sit
 
color clear = color.new(color.black, 100)
 
// ═════════════════════════════ CALCULATIONS ═════════════════════════════
float atr  = ta.atr(14)
bool  conf = barstate.isconfirmed
float ph   = ta.pivothigh(high, swingLen, swingLen)
float pl   = ta.pivotlow(low, swingLen, swingLen)
 
// ═════════════════════════════ HELPERS ═════════════════════════════
f_col(int dir, bool breaker) =>
    breaker ? (dir == 1 ? bullBrkCol : bearBrkCol) : (dir == 1 ? bullMitCol : bearMitCol)
 
// Offset of the last up-candle (wantBull) or down-candle at or before `fromOff`
f_findCandle(int fromOff, bool wantBull) =>
    int found = fromOff
    for i = fromOff to fromOff + searchLen
        if wantBull ? close[i] > open[i] : close[i] < open[i]
            found := i
            break
    found
 
f_newBlock(int off, float top, float btm, int dir, bool breaker) =>
    color  c   = f_col(dir, breaker)
    string txt = (dir == 1 ? "Bull " : "Bear ") + (breaker ? "Breaker" : "Mitigation")
    box b = box.new(bar_index - off, top, bar_index + zoneExt, btm, border_color = color.new(c, 30), border_style = breaker ? line.style_solid : line.style_dashed, bgcolor = color.new(c, breaker ? 78 : 86), text = txt, text_color = c, text_size = size.tiny, text_halign = text.align_right)
    blocks.push(Block.new(b, top, btm, dir, breaker, bar_index))
    if blocks.size() > maxBlocks
        Block old = blocks.shift()
        old.bx.delete()
 
f_mss(int fromBar, float y, bool bull) =>
    color c = bull ? bullBrkCol : bearBrkCol
    line.new(fromBar, y, bar_index, y, color = color.new(c, 20), style = line.style_dashed)
    label.new(int(math.avg(fromBar, bar_index)), y, "MSS", style = bull ? label.style_label_down : label.style_label_up, color = clear, textcolor = c, size = size.tiny)
 
// ═════════════════════════════ ENGINE (closed bars only) ═════════════════════════════
bool buyBrk   = false
bool buyMit   = false
bool sellBrk  = false
bool sellMit  = false
bool newBull  = false
bool newBear  = false
 
if conf
    // 1) Existing blocks: invalidation and retests
    bool  gotBuy  = false
    bool  gotSell = false
    bool  sigBrk  = false
    float sigTop  = na
    float sigBtm  = na
    int n = blocks.size()
    if n > 0
        for i = n - 1 to 0
            Block b = blocks.get(i)
            bool invalid = b.dir == -1 ? close > b.top : close < b.btm
            if invalid
                b.bx.delete()
                blocks.remove(i)
            else
                b.bx.set_right(bar_index + zoneExt)
                bool allowed = sigMode == "Breakers + Mitigation" or (sigMode == "Breakers only" and b.breaker) or (sigMode == "Mitigation only" and not b.breaker)
                bool biasOk  = not withBias or bias == b.dir
                bool touch   = b.dir == -1 ? (high >= b.btm and close < b.top and close < open) : (low <= b.top and close > b.btm and close > open)
                bool fresh   = b.signals < maxSig and bar_index - b.lastSig > 3 and bar_index > b.created
                if allowed and biasOk and touch and fresh and not gotBuy and not gotSell
                    b.signals := b.signals + 1
                    b.lastSig := bar_index
                    gotBuy    := b.dir == 1
                    gotSell   := b.dir == -1
                    sigBrk    := b.breaker
                    sigTop    := b.top
                    sigBtm    := b.btm
 
    buyBrk  := gotBuy and sigBrk
    buyMit  := gotBuy and not sigBrk
    sellBrk := gotSell and sigBrk
    sellMit := gotSell and not sigBrk
 
    if gotBuy or gotSell
        float entry = close
        float sl    = gotBuy ? sigBtm - atr * slBuf : sigTop + atr * slBuf
        float tp    = entry + (entry - sl) * rr
        string kind = sigBrk ? "breaker" : "mitigation block"
        lastSignal := (gotBuy ? "BUY " : "SELL ") + kind
        if showRisk
            enL.delete()
            slL.delete()
            tpL.delete()
            slLb.delete()
            tpLb.delete()
            int x2 = bar_index + riskPad
            enL  := line.new(bar_index, entry, x2, entry, color = color.gray, style = line.style_dotted)
            slL  := line.new(bar_index, sl, x2, sl, color = bearBrkCol, style = line.style_dashed)
            tpL  := line.new(bar_index, tp, x2, tp, color = bullBrkCol, style = line.style_dashed)
            slLb := label.new(x2, sl, "SL " + str.tostring(sl, format.mintick), style = label.style_label_left, color = color.new(bearBrkCol, 15), textcolor = color.white, size = size.tiny)
            tpLb := label.new(x2, tp, "TP " + str.tostring(tp, format.mintick), style = label.style_label_left, color = color.new(bullBrkCol, 15), textcolor = color.white, size = size.tiny)
        tradeOpen := true
        tradeDir  := gotBuy ? 1 : -1
        tradeBar  := bar_index
        tradeSL   := sl
        tradeTP   := tp
        alert("BMB " + lastSignal + " " + syminfo.ticker + " (" + timeframe.period + ") | Entry " + str.tostring(entry, format.mintick) + " | SL " + str.tostring(sl, format.mintick) + " | TP " + str.tostring(tp, format.mintick), alert.freq_once_per_bar_close)
 
    // 2) New swings
    if not na(ph)
        h0         := h1
        h0Bar      := h1Bar
        h1         := ph
        h1Bar      := bar_index - swingLen
        highBroken := false
        if showSw
            label.new(h1Bar, ph, "▼", style = label.style_label_down, color = clear, textcolor = color.new(color.gray, 20), size = size.tiny)
 
    if not na(pl)
        l0        := l1
        l0Bar     := l1Bar
        l1        := pl
        l1Bar     := bar_index - swingLen
        lowBroken := false
        if showSw
            label.new(l1Bar, pl, "▲", style = label.style_label_up, color = clear, textcolor = color.new(color.gray, 20), size = size.tiny)
 
    // 3) Bearish shift: close below the last swing low
    if not lowBroken and not na(l1) and close < l1
        lowBroken := true
        bias      := -1
        if showMss
            f_mss(l1Bar, l1, false)
        if not na(h1) and not na(h0) and h1Bar > l1Bar
            bool isBrk = h1 > h0
            int  offH  = bar_index - h1Bar
            if offH + searchLen < 450 and (isBrk ? showBrk : showMit)
                int   k   = f_findCandle(offH, true)
                float top = useBody ? math.max(open[k], close[k]) : high[k]
                float btm = useBody ? math.min(open[k], close[k]) : low[k]
                f_newBlock(k, top, btm, -1, isBrk)
                newBear   := true
                lastEvent := isBrk ? "Bearish breaker formed" : "Bearish mitigation formed"
                alert("BMB " + syminfo.ticker + " (" + timeframe.period + "): " + lastEvent + " " + str.tostring(btm, format.mintick) + " – " + str.tostring(top, format.mintick), alert.freq_once_per_bar_close)
 
    // 4) Bullish shift: close above the last swing high
    if not highBroken and not na(h1) and close > h1
        highBroken := true
        bias       := 1
        if showMss
            f_mss(h1Bar, h1, true)
        if not na(l1) and not na(l0) and l1Bar > h1Bar
            bool isBrk = l1 < l0
            int  offL  = bar_index - l1Bar
            if offL + searchLen < 450 and (isBrk ? showBrk : showMit)
                int   k   = f_findCandle(offL, false)
                float top = useBody ? math.max(open[k], close[k]) : high[k]
                float btm = useBody ? math.min(open[k], close[k]) : low[k]
                f_newBlock(k, top, btm, 1, isBrk)
                newBull   := true
                lastEvent := isBrk ? "Bullish breaker formed" : "Bullish mitigation formed"
                alert("BMB " + syminfo.ticker + " (" + timeframe.period + "): " + lastEvent + " " + str.tostring(btm, format.mintick) + " – " + str.tostring(top, format.mintick), alert.freq_once_per_bar_close)
 
// ═════════════════════════════ TRADE TRACKING ═════════════════════════════
// Move SL / TP forward with each candle until price reaches one of them
if tradeOpen and bar_index > tradeBar
    bool hitSL = tradeDir == 1 ? low <= tradeSL : high >= tradeSL
    bool hitTP = tradeDir == 1 ? high >= tradeTP : low <= tradeTP
 
    if hitSL or hitTP
        tradeOpen := false
        // Both hit inside one candle: the order is unknown, so count the stop
        bool won = hitTP and not hitSL
        lastSignal := lastSignal + (won ? " · TP hit" : " · SL hit")
 
        if showRisk
            enL.set_x2(bar_index)
            slL.set_x2(bar_index)
            tpL.set_x2(bar_index)
            slLb.set_x(bar_index)
            tpLb.set_x(bar_index)
 
            if won
                tpLb.set_text("TP hit " + str.tostring(tradeTP, format.mintick))
                slLb.set_color(color.new(bearBrkCol, 70))
            else
                slLb.set_text("SL hit " + str.tostring(tradeSL, format.mintick))
                tpLb.set_color(color.new(bullBrkCol, 70))
 
    else if showRisk
        int x2 = bar_index + riskPad
        enL.set_x2(x2)
        slL.set_x2(x2)
        tpL.set_x2(x2)
        slLb.set_x(x2)
        tpLb.set_x(x2)
 
// Keep blocks reaching the live bar
if barstate.islast
    for b in blocks
        b.bx.set_right(bar_index + zoneExt)
 
// ═════════════════════════════ SIGNALS & ALERT CONDITIONS ═════════════════════════════
plotshape(buyBrk,  "Buy (breaker)",     shape.triangleup,   location.belowbar, bullBrkCol, text = "", textcolor = color.white, size = size.tiny)
plotshape(buyMit,  "Buy (mitigation)",  shape.triangleup,   location.belowbar, bullMitCol, text = "",  textcolor = color.white, size = size.tiny)
plotshape(sellBrk, "Sell (breaker)",    shape.triangledown, location.abovebar, bearBrkCol, text = "", textcolor = color.white, size = size.tiny)
plotshape(sellMit, "Sell (mitigation)", shape.triangledown, location.abovebar, bearMitCol, text = "",  textcolor = color.white, size = size.tiny)
 
alertcondition(buyBrk or buyMit,   "Buy: block retest",       "BMB BUY {{ticker}} at {{close}}")
alertcondition(sellBrk or sellMit, "Sell: block retest",      "BMB SELL {{ticker}} at {{close}}")
alertcondition(newBull,            "New bullish block",       "BMB new bullish breaker/mitigation block on {{ticker}}")
alertcondition(newBear,            "New bearish block",       "BMB new bearish breaker/mitigation block on {{ticker}}")
 
// ═════════════════════════════ DASHBOARD ═════════════════════════════
string dashPos = switch dashPosIn
    "Top Left"     => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left"  => position.bottom_left
    => position.top_right
 
var table dash = table.new(dashPos, 2, 8, bgcolor = color.new(#0e1117, 8), frame_color = color.new(color.gray, 60), frame_width = 1, border_color = color.new(color.gray, 80), border_width = 1)
 
f_row(int r, string k, string v, color vc) =>
    table.cell(dash, 0, r, k, text_color = color.new(color.white, 25), text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if showDash and barstate.islast
    color neutral = color.new(color.white, 10)
    int   bullB = 0
    int   bullM = 0
    int   bearB = 0
    int   bearM = 0
    float supT  = na
    float supB  = na
    float resT  = na
    float resB  = na
    for b in blocks
        if b.dir == 1
            bullB += b.breaker ? 1 : 0
            bullM += b.breaker ? 0 : 1
            if b.top <= close and (na(supT) or b.top > supT)
                supT := b.top
                supB := b.btm
        else
            bearB += b.breaker ? 1 : 0
            bearM += b.breaker ? 0 : 1
            if b.btm >= close and (na(resB) or b.btm < resB)
                resT := b.top
                resB := b.btm
 
    string supTxt = na(supT) ? "—" : str.tostring(supB, format.mintick) + " – " + str.tostring(supT, format.mintick)
    string resTxt = na(resB) ? "—" : str.tostring(resB, format.mintick) + " – " + str.tostring(resT, format.mintick)
 
    f_row(0, "BREAKER & MITIGATION", syminfo.ticker + " · " + timeframe.period, color.white)
    f_row(1, "Structure bias", bias == 1 ? "Bullish" : bias == -1 ? "Bearish" : "—", bias == 1 ? bullBrkCol : bias == -1 ? bearBrkCol : neutral)
    f_row(2, "Bull breakers / MBs", str.tostring(bullB) + " / " + str.tostring(bullM), bullBrkCol)
    f_row(3, "Bear breakers / MBs", str.tostring(bearB) + " / " + str.tostring(bearM), bearBrkCol)
    f_row(4, "Nearest support block", supTxt, neutral)
    f_row(5, "Nearest resistance block", resTxt, neutral)
    f_row(6, "Last event", lastEvent, neutral)
    f_row(7, "Last signal", lastSignal, str.contains(lastSignal, "BUY") ? bullBrkCol : str.contains(lastSignal, "SELL") ? bearBrkCol : neutral)

← 返回列表