Order Blocks (Body Method)

edwinli51 · study · 186 行 · 点赞 157 · TradingView 原页

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

Pine Script

//@version=6
indicator("Order Blocks (Body Method)", shorttitle="OB", overlay=true, max_lines_count=500, max_labels_count=500)
 
// ── Types ───────────────────────────────────────────────────────────────
type Pend
    float lvl
    int   bar
 
type Fvg
    float top
    float bot
 
type OB
    line  ln
    label lb
    float lvl
    bool  bull
    int   touches
    bool  inTouch
    bool  star
    int   born
 
// ── Inputs ──────────────────────────────────────────────────────────────
swingLen   = input.int(3, "Swing length", minval=1, tooltip="Bars on each side that define a swing high/low. 2-4 suits a 1-5 minute chart; raise it for only the bigger highs/lows.")
levelMode  = input.string("Candle body", "Mark level from", options=["Candle body", "Wick"], tooltip="Candle body = top of bodies at a high / bottom of bodies at a low (the video's method). Wick = the extreme wick.")
maxPending = input.int(20, "Unbroken highs/lows tracked", minval=1, maxval=100)
maxOBs     = input.int(12, "Max active blocks", minval=1, maxval=100)
showDead   = input.bool(true, "Keep disrespected blocks (faded)")
lineBars   = input.int(10, "Line length after the break (bars)", minval=0, maxval=100, tooltip="How far the line runs to the right of the candle that closed through the level. A block stops being tracked once its line ends.")
 
showGrade  = input.bool(true, "Mark confluence blocks with a star", group="Confluence")
onlyGrade  = input.bool(false, "Only show blocks with confluence", group="Confluence", tooltip="Confluence = trend structure in the block's direction (HH+HL for bullish, LH+LL for bearish) AND an unfilled FVG in the same direction near the level.")
fvgTol     = input.float(0.5, "FVG distance tolerance (x ATR)", minval=0.0, step=0.1, group="Confluence")
 
bullCol    = input.color(color.green, "Bullish OB (+)", group="Colors")
bearCol    = input.color(color.red, "Bearish OB (-)", group="Colors")
deadCol    = input.color(color.new(color.gray, 40), "Disrespected", group="Colors")
 
// ── Helpers ─────────────────────────────────────────────────────────────
f_txt(bool bull, int touches, bool star) =>
    (bull ? "+OB" : "-OB") + (touches > 0 ? " ✓" + str.tostring(touches) : "") + (star ? " ★" : "")
 
f_hasFvg(array<Fvg> arr, float lvl, float tol) =>
    bool found = false
    for f in arr
        if f.bot <= lvl + tol and f.top >= lvl - tol
            found := true
            break
    found
 
// ── State ───────────────────────────────────────────────────────────────
var pendHigh = array.new<Pend>()
var pendLow  = array.new<Pend>()
var bullFvgs = array.new<Fvg>()
var bearFvgs = array.new<Fvg>()
var obs      = array.new<OB>()
 
var float phLast = na
var float phPrev = na
var float plLast = na
var float plPrev = na
 
bool newBull = false
bool newBear = false
bool respBull = false
bool respBear = false
bool disBull = false
bool disBear = false
 
atr = ta.atr(14)
ph  = ta.pivothigh(high, swingLen, swingLen)
pl  = ta.pivotlow(low, swingLen, swingLen)
 
// ── 1. Register swing highs / lows (marked at candle bodies) ────────────
if not na(ph)
    phPrev := phLast
    phLast := ph
    lvlH = levelMode == "Candle body" ? math.max(open[swingLen], close[swingLen]) : high[swingLen]
    pendHigh.push(Pend.new(lvlH, bar_index - swingLen))
    if pendHigh.size() > maxPending
        pendHigh.shift()
 
if not na(pl)
    plPrev := plLast
    plLast := pl
    lvlL = levelMode == "Candle body" ? math.min(open[swingLen], close[swingLen]) : low[swingLen]
    pendLow.push(Pend.new(lvlL, bar_index - swingLen))
    if pendLow.size() > maxPending
        pendLow.shift()
 
// ── 2. Track fair value gaps (for the confluence star) ──────────────────
if low > high[2]
    bullFvgs.push(Fvg.new(low, high[2]))
    if bullFvgs.size() > 30
        bullFvgs.shift()
if high < low[2]
    bearFvgs.push(Fvg.new(low[2], high))
    if bearFvgs.size() > 30
        bearFvgs.shift()
 
if bullFvgs.size() > 0
    for i = bullFvgs.size() - 1 to 0
        if close < bullFvgs.get(i).bot
            bullFvgs.remove(i)
if bearFvgs.size() > 0
    for i = bearFvgs.size() - 1 to 0
        if close > bearFvgs.get(i).top
            bearFvgs.remove(i)
 
// ── 3. Existing blocks: respected (wick in, no close through) or disrespected (close through)
if obs.size() > 0
    for i = obs.size() - 1 to 0
        blk = obs.get(i)
        bool dead = blk.bull ? close < blk.lvl : close > blk.lvl
        bool touching = blk.bull ? low <= blk.lvl : high >= blk.lvl
        if dead
            if showDead
                blk.ln.set_x2(bar_index)
                blk.lb.set_x(bar_index)
                blk.ln.set_color(deadCol)
                blk.ln.set_style(line.style_dotted)
                blk.lb.set_textcolor(deadCol)
                blk.lb.set_text(f_txt(blk.bull, blk.touches, blk.star and showGrade) + " ✗")
            else
                blk.ln.delete()
                blk.lb.delete()
            obs.remove(i)
            if blk.bull
                disBull := true
            else
                disBear := true
        else
            if touching and not blk.inTouch
                blk.touches := blk.touches + 1
                blk.lb.set_text(f_txt(blk.bull, blk.touches, blk.star and showGrade))
                if blk.bull
                    respBull := true
                else
                    respBear := true
            blk.inTouch := touching
            if bar_index - blk.born >= lineBars
                obs.remove(i)
 
// ── 4. New bullish OBs: a candle closes above a marked high ─────────────
if pendHigh.size() > 0
    for i = pendHigh.size() - 1 to 0
        p = pendHigh.get(i)
        if close > p.lvl
            bool trendOk = not na(phPrev) and not na(plPrev) and phLast > phPrev and plLast > plPrev
            bool hasFvg = f_hasFvg(bullFvgs, p.lvl, fvgTol * atr)
            bool star = trendOk and hasFvg
            if not onlyGrade or star
                ln = line.new(p.bar, p.lvl, bar_index + lineBars, p.lvl, color=bullCol, width=2)
                lb = label.new(bar_index + lineBars, p.lvl, f_txt(true, 0, star and showGrade), style=label.style_label_left, color=color.new(color.black, 100), textcolor=bullCol, size=size.small)
                obs.push(OB.new(ln, lb, p.lvl, true, 0, false, star, bar_index))
                newBull := true
            pendHigh.remove(i)
 
// ── 5. New bearish OBs: a candle closes below a marked low ──────────────
if pendLow.size() > 0
    for i = pendLow.size() - 1 to 0
        p = pendLow.get(i)
        if close < p.lvl
            bool trendOk = not na(phPrev) and not na(plPrev) and phLast < phPrev and plLast < plPrev
            bool hasFvg = f_hasFvg(bearFvgs, p.lvl, fvgTol * atr)
            bool star = trendOk and hasFvg
            if not onlyGrade or star
                ln = line.new(p.bar, p.lvl, bar_index + lineBars, p.lvl, color=bearCol, width=2)
                lb = label.new(bar_index + lineBars, p.lvl, f_txt(false, 0, star and showGrade), style=label.style_label_left, color=color.new(color.black, 100), textcolor=bearCol, size=size.small)
                obs.push(OB.new(ln, lb, p.lvl, false, 0, false, star, bar_index))
                newBear := true
            pendLow.remove(i)
 
// ── 6. Cap how many blocks stay on the chart ────────────────────────────
if obs.size() > maxOBs
    old = obs.shift()
    old.ln.delete()
    old.lb.delete()
 
// ── Alerts ──────────────────────────────────────────────────────────────
alertcondition(newBull, "New bullish OB (+)", "New bullish order block on {{ticker}}")
alertcondition(newBear, "New bearish OB (-)", "New bearish order block on {{ticker}}")
alertcondition(respBull, "Bullish OB respected", "Bullish order block respected on {{ticker}}")
alertcondition(respBear, "Bearish OB respected", "Bearish order block respected on {{ticker}}")
alertcondition(disBull, "Bullish OB disrespected", "Bullish order block disrespected on {{ticker}}")
alertcondition(disBear, "Bearish OB disrespected", "Bearish order block disrespected on {{ticker}}")

← 返回列表