Order Blocks - Structure Break, MTF

Ku_Hero · study · 293 行 · 点赞 27 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Order Blocks - Structure Break, MTF  v1.1
//
// Block rule (closed bars only, the same rule for the chart timeframe and the optional higher timeframe; no ATR)
//  - Swing high / low: ta.pivothigh / ta.pivotlow with N bars on each side (as in these built-in functions, an equal
//    high/low is allowed on one side). A swing is used only after its N right bars have closed.
//  - Structure break up: a bar closes above the latest confirmed swing high that has not been closed above yet
//    (BOS and CHoCH are not separated, and breaks of small swings count too). Each swing can be broken only once.
//  - Bullish order block: the LAST bearish bar (close < open) from the latest confirmed swing low (included) up to
//    the bar before the breaking bar. No bearish bar -> no block. Bearish blocks are the mirror image (last bullish
//    bar between the latest swing high and the bar before a close below the latest swing low).
//  - Block range: high to low of that bar, or open to close with "Body only". The box starts at that bar.
//  - Optional filter: at least one fair value gap in the direction of the break between the block bar and the
//    breaking bar (bullish: low > high[2], bearish: high < low[2], all three bars inside that range).
//  - A bar becomes an order block only once: the bars already used (time and direction, the latest 500) are
//    remembered, so a deleted or dropped block is never created again by a later break.
//  - The search for the block bar goes back at most 300 bars from the breaking bar.
// State, judged from the bar after the breaking bar (the bars of the move itself are not used)
//  - Touched: price reached the near edge / 50% / far edge (wicks; selectable). Touched blocks change color.
//  - Broken : a bar closes beyond the far edge. Broken blocks are deleted, or kept as grey boxes that end at the
//             close of the breaking bar.
// Tracking: only the newest N unbroken (and N grey) blocks per side are kept. An older unbroken block beyond the
//  limit is dropped for good: it is no longer drawn, updated or used for alerts.
// Optional distance filter: blocks whose nearer edge is farther than X% from the close of the last closed bar are
//  not drawn. They are still tracked (state and alerts continue) and are drawn again when price comes back.
// Difference from "Supply Demand Zones" (same author): that script boxes the quiet base bars before an ATR-sized
//  strong bar. This script uses no ATR and no strong-bar rule: it boxes the last opposite-color bar before a close
//  through a confirmed swing.
// Blocks are created and updated only when a bar closes (barstate.isconfirmed). A block never moves after it is created.
// Higher timeframe blocks are requested with [1] and lookahead_on, so only closed higher timeframe bars are used.
// Tick-based higher timeframes are not supported.
// Display only. This is not a buy/sell signal and not a forecast.
indicator("Order Blocks - Structure Break, MTF", shorttitle = "OB", overlay = true, max_boxes_count = 500, max_bars_back = 500)
 
// ---------- Inputs ----------
grpR = "Block rules"
inSwing    = input.int(5, "Swing length (bars on each side)", minval = 1, maxval = 50, group = grpR)
inRange    = input.string("Full candle", "Block range", options = ["Full candle", "Body only"], group = grpR)
inNeedFvg  = input.bool(false, "Require FVG in the move", group = grpR)
inTouch    = input.string("Near edge", "Touched when price reaches", options = ["Near edge", "50%", "Far edge"], group = grpR)
inBroken   = input.string("Delete", "Broken blocks", options = ["Delete", "Grey, stop extending"], group = grpR)
 
grpD = "Display"
inMaxU     = input.int(5, "Unbroken blocks shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inMaxB     = input.int(5, "Broken (grey) blocks shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inExtend   = input.int(10, "Extend unbroken blocks to the right by N bars", minval = 0, maxval = 500, group = grpD, display = display.none)
inHide     = input.bool(true, "Hide blocks farther than X% from current price", group = grpD, inline = "hd", display = display.none)
inHidePct  = input.float(10.0, "", minval = 0.01, maxval = 100.0, step = 0.5, group = grpD, inline = "hd", display = display.none)
inLabels   = input.bool(false, "Show state labels", group = grpD, display = display.none)
cBullF     = input.color(#26A69A, "Bullish OB: fresh / touched", group = grpD, inline = "bu", display = display.none)
cBullT     = input.color(#80CBC4, "", group = grpD, inline = "bu", display = display.none)
cBearF     = input.color(#EF5350, "Bearish OB: fresh / touched", group = grpD, inline = "be", display = display.none)
cBearT     = input.color(#EF9A9A, "", group = grpD, inline = "be", display = display.none)
cBrk       = input.color(#9E9E9E, "Broken OB", group = grpD, display = display.none)
inFillT    = input.int(80, "Fill transparency (0-100)", minval = 0, maxval = 100, group = grpD, display = display.none)
inBorder   = input.bool(true, "Border: show / width", group = grpD, inline = "bd", display = display.none)
inBorderW  = input.int(1, "", minval = 1, maxval = 4, group = grpD, inline = "bd", display = display.none)
inBorderT  = input.int(40, "Border transparency (0-100)", minval = 0, maxval = 100, group = grpD, display = display.none)
inLblSize  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpD, display = display.none)
 
grpH = "Higher timeframe OBs (optional)"
inHtfOn    = input.bool(false, "Show higher timeframe OBs", group = grpH)
inHtf      = input.timeframe("240", "Higher timeframe", group = grpH)
inHtfMaxU  = input.int(3, "HTF unbroken blocks shown per side", minval = 1, maxval = 20, group = grpH, display = display.none)
inHtfMaxB  = input.int(2, "HTF broken (grey) blocks shown per side", minval = 1, maxval = 20, group = grpH, display = display.none)
cHtfBull   = input.color(#1E88E5, "HTF bullish OB", group = grpH, inline = "hb", display = display.none)
cHtfBear   = input.color(#FB8C00, "HTF bearish OB", group = grpH, inline = "hs", display = display.none)
 
// ---------- Settings ----------
int  MAXLEG    = 300
bool bodyOnly  = inRange == "Body only"
int  touchMode = inTouch == "Near edge" ? 0 : inTouch == "50%" ? 1 : 2
bool keepB     = inBroken == "Grey, stop extending"
bool htfTick   = inHtfOn and str.contains(inHtf, "T")
bool htfLow    = inHtfOn and not htfTick and timeframe.in_seconds(inHtf) <= timeframe.in_seconds(timeframe.period)
bool htfOn     = inHtfOn and not htfTick and not htfLow
 
// ---------- Block engine ----------
type OB
    float top
    float bot
    int   dir      // +1 bullish / -1 bearish
    int   tLeft    // open time of the block bar
    bool  touched
    bool  broken
    int   tBrk     // open time of the bar that closed beyond the far edge
    bool  pin      // previous bar was inside the block
 
// Processes the current bar when gate is true.
// Returns [blocks (oldest first), new bullish, new bearish, price entered an unbroken bullish block, ... bearish block].
// Only the newest maxU unbroken and (when kept) maxB broken blocks per side are tracked. An older unbroken block
// beyond maxU is dropped for good (no longer drawn, updated or used for alerts).
f_engine(bool gate, int n, bool body, bool needFvg, int tMode, int maxU, bool kb, int maxB) =>
    var array<OB> zs = array.new<OB>()
    var float shP    = na
    var int   shI    = na
    var bool  shUsed = true
    var float slP    = na
    var int   slI    = na
    var bool  slUsed = true
    var array<int> made = array.new<int>()   // keys of bars already used as blocks: +time bullish, -time bearish
    float ph = ta.pivothigh(high, n, n)
    float pl = ta.pivotlow(low, n, n)
    bool nBull = false
    bool nBear = false
    bool eBull = false
    bool eBear = false
    if gate
        int k = bar_index
        // 1) update the existing blocks with this closed bar
        for z in zs
            if not z.broken
                bool up = z.dir > 0
                if up ? close < z.bot : close > z.top
                    z.broken := true
                    z.tBrk   := time
                else
                    bool inz = up ? low <= z.top : high >= z.bot
                    if inz and not z.pin
                        if up
                            eBull := true
                        else
                            eBear := true
                    z.pin := inz
                    float mid = (z.top + z.bot) / 2.0
                    float lvl = up ? (tMode == 0 ? z.top : tMode == 1 ? mid : z.bot) : (tMode == 0 ? z.bot : tMode == 1 ? mid : z.top)
                    if not z.touched and (up ? low <= lvl : high >= lvl)
                        z.touched := true
        // 2) newly confirmed swings (the swing bar is n bars back)
        if not na(ph)
            shP    := ph
            shI    := k - n
            shUsed := false
        if not na(pl)
            slP    := pl
            slI    := k - n
            slUsed := false
        // 3) structure breaks -> order blocks
        for s = 0 to 1
            int  d   = s == 0 ? 1 : -1
            bool brk = d > 0 ? (not shUsed and not na(shP) and close > shP) : (not slUsed and not na(slP) and close < slP)
            if brk
                if d > 0
                    shUsed := true
                else
                    slUsed := true
                int origin = d > 0 ? slI : shI
                if not na(origin)
                    int span  = math.min(k - origin, MAXLEG)
                    int obOff = -1
                    if span >= 1
                        for j = 1 to span
                            if d > 0 ? close[j] < open[j] : close[j] > open[j]
                                obOff := j
                                break
                    if obOff > 0
                        bool fvgOk = not needFvg
                        if needFvg and obOff >= 2
                            for j = 0 to obOff - 2
                                if d > 0 ? low[j] > high[j + 2] : high[j] < low[j + 2]
                                    fvgOk := true
                                    break
                        if fvgOk
                            float t  = body ? math.max(open[obOff], close[obOff]) : high[obOff]
                            float b  = body ? math.min(open[obOff], close[obOff]) : low[obOff]
                            int   tl = time[obOff]
                            int  key = d > 0 ? tl : -tl
                            if not made.includes(key) and t > b
                                made.push(key)
                                if made.size() > 500
                                    made.shift()
                                zs.push(OB.new(t, b, d, tl, false, false, 0, false))
                                if d > 0
                                    nBull := true
                                else
                                    nBear := true
        // 4) keep only the newest maxU unbroken / maxB broken blocks per side (drop the older ones)
        int m = zs.size()
        if m > 0
            int uB = 0
            int uS = 0
            int bB = 0
            int bS = 0
            for i = m - 1 to 0
                OB z = zs.get(i)
                bool up = z.dir > 0
                if not z.broken
                    if up
                        if uB >= maxU
                            zs.remove(i)
                        else
                            uB += 1
                    else
                        if uS >= maxU
                            zs.remove(i)
                        else
                            uS += 1
                else if not kb
                    zs.remove(i)
                else if up
                    if bB >= maxB
                        zs.remove(i)
                    else
                        bB += 1
                else
                    if bS >= maxB
                        zs.remove(i)
                    else
                        bS += 1
    [zs, nBull, nBear, eBull, eBear]
 
// Higher timeframe: a deep copy per bar so that [1] returns the state of the previous (closed) HTF bar.
// gate = true: inside request.security barstate.isconfirmed is not reliable, and [1] already reads closed HTF bars only.
f_htfCopy(int n, bool body, bool needFvg, int tMode, int maxU, bool kb, int maxB) =>
    [src, hnB, hnS, heB, heS] = f_engine(true, n, body, needFvg, tMode, maxU, kb, maxB)
    array<OB> out = array.new<OB>()
    for z in src
        out.push(z.copy())
    out
 
// ---------- Chart timeframe ----------
[cz, newBull, newBear, entBull, entBear] = f_engine(barstate.isconfirmed, inSwing, bodyOnly, inNeedFvg, touchMode, inMaxU, keepB, inMaxB)
 
// ---------- Higher timeframe ----------
array<OB> hz = na
if htfOn
    hz := request.security(syminfo.tickerid, inHtf, f_htfCopy(inSwing, bodyOnly, inNeedFvg, touchMode, inHtfMaxU, keepB, inHtfMaxB)[1], lookahead = barmerge.lookahead_on)
 
// ---------- Alerts (chart timeframe, on bar close) ----------
alertcondition(newBull, "New bullish OB", "New bullish order block on {{ticker}} {{interval}}")
alertcondition(newBear, "New bearish OB", "New bearish order block on {{ticker}} {{interval}}")
alertcondition(entBull, "Price entered a bullish OB", "Price entered an unbroken bullish order block on {{ticker}} {{interval}}")
alertcondition(entBear, "Price entered a bearish OB", "Price entered an unbroken bearish order block on {{ticker}} {{interval}}")
if newBull
    alert("New bullish order block on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if newBear
    alert("New bearish order block on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if entBull
    alert("Price entered an unbroken bullish order block on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if entBear
    alert("Price entered an unbroken bearish order block on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
 
// ---------- Drawing (last bar only) ----------
f_tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    s >= 2419200 ? str.tostring(math.round(s / 2628003.0)) + "M" : s >= 604800 ? str.tostring(s / 604800) + "W" : s >= 86400 ? str.tostring(s / 86400) + "D" : s >= 3600 ? str.tostring(s / 3600) + "H" : s >= 60 ? str.tostring(s / 60) + "m" : str.tostring(s) + "s"
 
f_txtSize() =>
    inLblSize == "Tiny" ? size.tiny : inLblSize == "Normal" ? size.normal : size.small
 
f_state(OB z) =>
    z.broken ? "broken" : z.touched ? "touched" : "fresh"
 
// Distance in percent from the reference price to the nearer edge of the block (0 when the price is inside).
f_distPct(OB z, float ref) =>
    float d = ref > z.top ? ref - z.top : ref < z.bot ? z.bot - ref : 0.0
    ref > 0 ? d / ref * 100.0 : 0.0
 
// Draws the stored blocks (oldest first, so newer blocks are on top). Blocks beyond the distance filter are skipped.
f_drawSet(array<OB> zs, bool isHtf, int rightT, int barMs, string tfLbl, float ref, array<box> store) =>
    for z in zs
        if inHide and f_distPct(z, ref) > inHidePct
            continue
        bool  up   = z.dir > 0
        color base = z.broken ? cBrk : isHtf ? (up ? cHtfBull : cHtfBear) : up ? (z.touched ? cBullT : cBullF) : (z.touched ? cBearT : cBearF)
        int   r    = z.broken ? z.tBrk + barMs : rightT
        int   bw   = isHtf ? inBorderW + 1 : inBorderW
        color bc   = inBorder or isHtf ? color.new(base, inBorderT) : color.new(base, 100)
        string side = up ? "Bull OB" : "Bear OB"
        string txt  = isHtf ? tfLbl + " OB" + (inLabels ? " " + f_state(z) : "") : inLabels ? side + " " + f_state(z) : ""
        store.push(box.new(z.tLeft, z.top, r, z.bot, xloc = xloc.bar_time, border_color = bc, border_width = bw,
             bgcolor = color.new(base, inFillT), text = txt, text_size = f_txtSize(), text_color = color.new(base, 0),
             text_halign = text.align_right, text_valign = text.align_center))
 
var array<box> boxes = array.new<box>()
var table msgTbl = table.new(position.top_right, 1, 1, border_width = 0)
if barstate.islast
    for b in boxes
        b.delete()
    boxes.clear()
    int   tfMs   = timeframe.in_seconds(timeframe.period) * 1000
    int   rightT = time + inExtend * tfMs
    float refPx  = barstate.isconfirmed ? close : close[1]   // close of the last closed bar
    if htfOn and not na(hz)
        f_drawSet(hz, true, rightT, timeframe.in_seconds(inHtf) * 1000, f_tfName(inHtf), refPx, boxes)
    f_drawSet(cz, false, rightT, tfMs, "", refPx, boxes)
    string msg = htfTick ? "OB: tick-based higher timeframes are not supported (HTF blocks are off)" : htfLow ? "OB: higher timeframe must be above the chart timeframe (HTF blocks are off)" : htfOn and na(hz) ? "OB: loading higher timeframe data" : ""
    if msg != ""
        table.cell(msgTbl, 0, 0, msg, text_color = color.rgb(255, 69, 0), text_size = size.small)
    else
        table.clear(msgTbl, 0, 0)

← 返回列表