Order Block Strength

oguzcinar678 · study · 216 行 · 点赞 339 · TradingView 原页

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

Pine Script

//@version=6
indicator("Order Block Strength", "OB Strength", overlay = true, max_boxes_count = 500, max_bars_back = 500)
 
// ─────────────────────────────── Inputs ───────────────────────────────
grpS          = "Structure"
swingLen      = input.int(10, "Swing Length", minval = 2, group = grpS, tooltip = "Bars on each side required to confirm a swing high/low.")
maxLookback   = input.int(300, "Max OB Search Lookback", minval = 10, maxval = 450, group = grpS)
maxOBs        = input.int(5, "Max Active OBs per Side", minval = 1, maxval = 50, group = grpS)
mitigation    = input.string("Close", "Mitigation Source", options = ["Close", "Wick"], group = grpS, tooltip = "Close: OB is invalidated when a candle closes beyond it. Wick: invalidated on any wick beyond it.")
mergeOverlap  = input.bool(true, "Remove Overlapping OBs (keep strongest)", group = grpS)
showMitigated = input.bool(false, "Keep Mitigated OBs on Chart", group = grpS)
 
grpW          = "Strength Score"
wVol          = input.float(35.0, "Volume Weight", minval = 0, group = grpW)
wDisp         = input.float(40.0, "Displacement Weight", minval = 0, group = grpW)
wFvg          = input.float(25.0, "Fair Value Gap Weight", minval = 0, group = grpW)
volLen        = input.int(20, "Volume Average Length", minval = 1, group = grpW)
volFull       = input.float(2.0, "Volume Ratio for Full Score", minval = 0.1, group = grpW, tooltip = "OB candle volume / average volume needed for 100% volume score.")
atrLen        = input.int(14, "ATR Length", minval = 1, group = grpW)
dispFull      = input.float(3.0, "ATR Multiple for Full Displacement", minval = 0.1, group = grpW, tooltip = "Distance (in ATRs) price must travel away from the OB on the break for 100% displacement score.")
touchPenalty  = input.float(15.0, "Penalty per Retest (%)", minval = 0, maxval = 100, group = grpW)
minStrength   = input.float(0.0, "Hide New OBs Below (%)", minval = 0, maxval = 100, group = grpW)
 
grpV          = "Visuals"
bullColor     = input.color(color.teal, "Bullish OB", group = grpV)
bearColor     = input.color(color.red, "Bearish OB", group = grpV)
textColor     = input.color(#B2B5BE, "Text", group = grpV)
labelOffset   = input.int(15, "Label Offset (bars right of price)", minval = 1, maxval = 200, group = grpV)
 
grpA          = "Alerts"
alertMin      = input.float(60.0, "Retest Alert Min Strength (%)", minval = 0, maxval = 100, group = grpA)
 
// ─────────────────────────────── Types & series ───────────────────────────────
type OB
    float top
    float btm
    float score
    int   touches
    bool  inZone
    box   bx
 
var array<OB> bullOBs = array.new<OB>()
var array<OB> bearOBs = array.new<OB>()
 
volAvg = ta.sma(volume, volLen)
atr    = ta.atr(atrLen)
 
// ─────────────────────────────── Helpers ───────────────────────────────
transpFor(float score) =>
    88 - score * 0.38   // stronger OB = more opaque box
 
currentScore(OB ob) =>
    math.max(ob.score - ob.touches * touchPenalty, 0)
 
obText(bool bullish, float score, int touches) =>
    string t = (bullish ? "Bull OB " : "Bear OB ") + str.tostring(score, "#") + "%"
    touches > 0 ? t + " (" + str.tostring(touches) + (touches == 1 ? " retest)" : " retests)") : t
 
// Finds the bar offset of the OB candle: the most extreme opposite-colored candle
// between the swing point and the break. Falls back to the most extreme candle overall.
findOB(bool bullish, int len) =>
    int   idx    = na
    float ext    = na
    int   idxAny = 1
    float extAny = bullish ? low[1] : high[1]
    for i = 1 to len
        float v   = bullish ? low[i] : high[i]
        bool  opp = bullish ? close[i] < open[i] : close[i] > open[i]
        if bullish ? v < extAny : v > extAny
            extAny := v
            idxAny := i
        if opp and (na(ext) or (bullish ? v < ext : v > ext))
            ext := v
            idx := i
    na(idx) ? idxAny : idx
 
// Strength score 0–100 from volume, displacement and FVG presence
scoreOB(bool bullish, int idx, float top, float btm) =>
    float vr   = na(volume[idx]) or na(volAvg[idx]) or volAvg[idx] == 0 ? na : volume[idx] / volAvg[idx]
    float volS = na(vr) ? 0.5 : math.min(vr / volFull, 1.0)   // neutral if no volume data
    float dist = bullish ? close - top : btm - close
    float dispS = na(atr) or atr == 0 ? 0.0 : math.max(math.min(dist / (atr * dispFull), 1.0), 0.0)
    bool  fvg  = false
    if idx >= 2
        for k = 0 to idx - 2
            if bullish ? low[k] > high[k + 2] : high[k] < low[k + 2]
                fvg := true
                break
    float fvgS = fvg ? 1.0 : 0.0
    float wSum = wVol + wDisp + wFvg
    wSum > 0 ? (wVol * volS + wDisp * dispS + wFvg * fvgS) / wSum * 100 : 0.0
 
// Creates a new OB. With overlap removal on, a new OB is skipped if a stronger
// overlapping OB exists; otherwise weaker overlapping OBs are replaced.
createOB(array<OB> arr, bool bullish, int idx, float score) =>
    float top  = high[idx]
    float btm  = low[idx]
    bool  keep = true
    if mergeOverlap and arr.size() > 0
        for ex in arr
            if top >= ex.btm and btm <= ex.top and currentScore(ex) >= score
                keep := false
                break
        if keep
            for i = arr.size() - 1 to 0
                OB ex = arr.get(i)
                if top >= ex.btm and btm <= ex.top
                    ex.bx.delete()
                    arr.remove(i)
    if keep
        color base = bullish ? bullColor : bearColor
        box b = box.new(bar_index - idx, top, bar_index + labelOffset, btm, border_color = color.new(base, 40), bgcolor = color.new(base, transpFor(score)), text = obText(bullish, score, 0), text_color = textColor, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small)
        arr.unshift(OB.new(top, btm, score, 0, false, b))
        if arr.size() > maxOBs
            OB old = arr.pop()
            old.bx.delete()
    keep
 
// Handles retests and mitigation. Returns the highest current strength of an OB retested this bar.
updateOBs(array<OB> arr, bool bullish) =>
    float bestTouch = 0.0
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            OB ob = arr.get(i)
            float src = mitigation == "Close" ? close : (bullish ? low : high)
            bool  mitigated = bullish ? src < ob.btm : src > ob.top
            if mitigated
                if showMitigated
                    ob.bx.set_right(bar_index)
                    ob.bx.set_bgcolor(color.new(color.gray, 88))
                    ob.bx.set_border_color(color.new(color.gray, 60))
                    ob.bx.set_text("Mitigated (" + str.tostring(currentScore(ob), "#") + "%)")
                    ob.bx.set_text_size(size.tiny)
                else
                    ob.bx.delete()
                arr.remove(i)
            else
                bool inside = bullish ? low <= ob.top : high >= ob.btm
                if inside and not ob.inZone
                    ob.touches += 1
                    bestTouch := math.max(bestTouch, currentScore(ob))
                ob.inZone := inside
                float cur = currentScore(ob)
                color base = bullish ? bullColor : bearColor
                ob.bx.set_right(bar_index + labelOffset)
                ob.bx.set_text(obText(bullish, cur, ob.touches))
                ob.bx.set_bgcolor(color.new(base, transpFor(cur)))
    bestTouch
 
// ─────────────────────────────── Market structure ───────────────────────────────
ph = ta.pivothigh(high, swingLen, swingLen)
pl = ta.pivotlow(low, swingLen, swingLen)
 
var float swingHigh    = na
var int   swingHighBar = na
var bool  shBroken     = true
var float swingLow     = na
var int   swingLowBar  = na
var bool  slBroken     = true
 
if not na(ph)
    swingHigh    := ph
    swingHighBar := bar_index - swingLen
    shBroken     := false
if not na(pl)
    swingLow    := pl
    swingLowBar := bar_index - swingLen
    slBroken    := false
 
// Update existing OBs first (so a new OB isn't retested on its own bar)
bullTouch = updateOBs(bullOBs, true)
bearTouch = updateOBs(bearOBs, false)
 
bool  newBull      = false
bool  newBear      = false
float newBullScore = na
float newBearScore = na
 
// Bullish break of structure → bullish OB
if not shBroken and not na(swingHigh) and close > swingHigh
    shBroken := true
    int len = math.min(bar_index - swingHighBar, maxLookback)
    if len >= 1
        int   idx = findOB(true, len)
        float s   = scoreOB(true, idx, high[idx], low[idx])
        if s >= minStrength
            if createOB(bullOBs, true, idx, s)
                newBull      := true
                newBullScore := s
 
// Bearish break of structure → bearish OB
if not slBroken and not na(swingLow) and close < swingLow
    slBroken := true
    int len = math.min(bar_index - swingLowBar, maxLookback)
    if len >= 1
        int   idx = findOB(false, len)
        float s   = scoreOB(false, idx, high[idx], low[idx])
        if s >= minStrength
            if createOB(bearOBs, false, idx, s)
                newBear      := true
                newBearScore := s
 
// ─────────────────────────────── Alerts ───────────────────────────────
alertcondition(newBull, "New Bullish OB", "New bullish order block formed on {{ticker}} ({{interval}})")
alertcondition(newBear, "New Bearish OB", "New bearish order block formed on {{ticker}} ({{interval}})")
alertcondition(bullTouch >= alertMin and bullTouch > 0, "Strong Bullish OB Retest", "Price is retesting a strong bullish OB on {{ticker}}")
alertcondition(bearTouch >= alertMin and bearTouch > 0, "Strong Bearish OB Retest", "Price is retesting a strong bearish OB on {{ticker}}")
 
if newBull
    alert("New Bullish OB on " + syminfo.ticker + " | Strength: " + str.tostring(newBullScore, "#") + "%", alert.freq_once_per_bar_close)
if newBear
    alert("New Bearish OB on " + syminfo.ticker + " | Strength: " + str.tostring(newBearScore, "#") + "%", alert.freq_once_per_bar_close)
if bullTouch >= alertMin and bullTouch > 0
    alert("Bullish OB retest on " + syminfo.ticker + " | Strength: " + str.tostring(bullTouch, "#") + "%", alert.freq_once_per_bar_close)
if bearTouch >= alertMin and bearTouch > 0
    alert("Bearish OB retest on " + syminfo.ticker + " | Strength: " + str.tostring(bearTouch, "#") + "%", alert.freq_once_per_bar_close)

← 返回列表