本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// Order Block Universal - chart-timeframe Pine adaptation.
// Pine adaptation author and maintainer: legion01 (TradingView).
// Based on the OrderBlockUniversal (RU) MQL5 project.
// OpenAI Codex assisted with the Pine implementation, compilation checks, and testing.
// Deliberate omissions: MTF engines, liquidity pools/sweeps, scoring, nested/flip
// classifications, and FVG lifecycle. Historical depth and drawings are bounded.
// Signals are observations at the first touch close, never trade instructions.
indicator("Order Block Universal - Structure and Retests", "OBU 2.2 EN", overlay = true, max_boxes_count = 100, max_labels_count = 100, max_bars_back = 1000)
sigmaLen = input.int(14, "Median true range length", minval = 5, maxval = 200, group = "Structure")
kSmall = input.int(2, "Small swing strength", minval = 1, maxval = 20, group = "Structure")
kLarge = input.int(5, "Large swing strength (must exceed small)", minval = 2, maxval = 30, group = "Structure")
dispMag = input.float(1.0, "Leg size / sigma", minval = 0.01, group = "Displacement")
dispRange = input.float(1.0, "Bar range / sigma", minval = 0.01, group = "Displacement")
dispBody = input.float(0.5, "Body fraction", minval = 0.01, maxval = 1, group = "Displacement")
dispMaxBars = input.int(5, "Max bars in leg", minval = 2, maxval = 20, group = "Displacement")
dispAdverse = input.float(0.5, "Max adverse move / sigma", minval = 0, group = "Displacement")
lookback = input.int(1, "Opposing candle lookback", minval = 1, maxval = 20, group = "Order Block")
confirmWindow = input.int(5, "Confirmation window", minval = 1, maxval = 100, group = "Order Block")
strictConfirm = input.bool(false, "Strict: displacement and BOS on the same bar", group = "Order Block")
zoneMode = input.string("FULL", "Zone boundaries", options = ["FULL", "BODY", "OPEN_EXT", "WICK_ONLY"], group = "Order Block")
requireFvg = input.bool(false, "Require FVG", group = "Order Block")
fvgMin = input.float(0.25, "Minimum FVG / sigma", minval = 0, group = "Order Block")
mitigation = input.float(0.5, "Mitigation depth", minval = 0, maxval = 1, group = "Zone lifecycle")
invalidMode = input.string("CLOSE", "Invalidation mode", options = ["CLOSE", "CLOSE_WICK"], group = "Zone lifecycle")
invalidBuf = input.float(0, "Close buffer / sigma", minval = 0, group = "Zone lifecycle")
invalidWick = input.float(0, "Wick buffer / sigma", minval = 0, group = "Zone lifecycle")
maxAge = input.int(0, "Zone lifetime in bars (0 = no age expiry)", minval = 0, group = "Zone lifecycle")
expireStructure = input.bool(false, "Expire on structure reversal", group = "Zone lifecycle")
maxZones = input.int(40, "Engine zone capacity", minval = 1, maxval = 80, group = "Engine storage", tooltip = "FIFO: when capacity is exceeded, the engine evicts the oldest zone, even if it is active. It no longer tracks its touches, mitigation, or invalidation. This is separate from the drawing limit.")
maxVisible = input.int(15, "Max visible zones", minval = 1, maxval = 40, group = "Display", tooltip = "Drawing limit only; does not remove zones from engine storage.")
drawAge = input.int(1500, "Max drawing age in bars", minval = 1, maxval = 5000, group = "Display")
drawSigma = input.float(4.0, "Max drawn zone height / sigma", minval = 0.1, group = "Display")
signalAge = input.int(500, "Marker history in bars", minval = 1, maxval = 5000, group = "Display")
showHistory = input.bool(false, "Show historical zones", group = "Display")
showLabels = input.bool(false, "Zone labels", group = "Display")
showConfirm = input.bool(true, "Confirmation marker", group = "Display")
showSignals = input.bool(true, "First retest triangle", group = "Display")
showPanel = input.bool(true, "Status panel", group = "Display")
colBull = input.color(color.lime, "Bullish", group = "Display")
colBear = input.color(color.rgb(255, 99, 71), "Bearish", group = "Display")
colTest = input.color(color.rgb(255, 215, 0), "Tested", group = "Display")
colMit = input.color(color.rgb(160, 82, 45), "Mitigated", group = "Display")
colDead = input.color(color.gray, "Retired", group = "Display")
if kLarge <= kSmall
runtime.error("Large swing strength must exceed small swing strength")
float tr = ta.tr(true)
float sigma = ta.median(tr, sigmaLen)
f_pivot(int k, bool isHigh) =>
bool valid = bar_index >= 2 * k and high[k] > low[k]
if valid
for off = 0 to 2 * k
if off != k
float p = isHigh ? high[off] : low[off]
float c = isHigh ? high[k] : low[k]
// Older (left) equality rejects; newer (right) equality is allowed.
if (isHigh and (off > k ? p >= c : p > c)) or (not isHigh and (off > k ? p <= c : p < c))
valid := false
valid
f_zone(int off, int dir) =>
float zlo = low[off]
float zhi = high[off]
if zoneMode == "BODY"
zlo := math.min(open[off], close[off])
zhi := math.max(open[off], close[off])
else if zoneMode == "OPEN_EXT"
zlo := dir == 1 ? low[off] : open[off]
zhi := dir == 1 ? open[off] : high[off]
else if zoneMode == "WICK_ONLY"
zlo := dir == 1 ? low[off] : math.max(open[off], close[off])
zhi := dir == 1 ? math.min(open[off], close[off]) : high[off]
[zlo, zhi]
f_gap(int cand, int dir, float zlo, float zhi) =>
bool found = false
int n = bar_index - cand
for off = 0 to n - 1
// Gap bar lies after candidate; size uses sigma at the gap bar.
float s = sigma[off]
if not na(s) and s > 0 and bar_index - off >= cand + 1
float glo = dir == 1 ? high[off + 2] : high[off]
float ghi = dir == 1 ? low[off] : low[off + 2]
if ghi > glo and (ghi - glo) / s >= fvgMin and ghi > zlo and glo < zhi
found := true
found
bool ready = bar_index >= math.max(4, 2 * kLarge) and not na(sigma) and sigma > 0 and kLarge > kSmall
float tol = syminfo.mintick * 0.5
// The latest confirmed unbroken pivot and the protected large-swing extreme.
var float sh = na
var float sl = na
var float smallH = na
var float smallL = na
var bool shBroken = true
var bool slBroken = true
var bool smallHBroken = true
var bool smallLBroken = true
var int shKnown = -1
var int slKnown = -1
var int smallHKnown = -1
var int smallLKnown = -1
var int trend = 0
var float protectedL = na
var float protectedH = na
var int lastLargeEvent = -1
var int lastSmallEvent = -1
var int lastBullEvent = -1
var int lastBearEvent = -1
var int lastBullMss = -1
var int lastBearMss = -1
var bool legOn = false
var int legDir = 0
var int legStart = na
var int legBars = 0
var float legRef = na
var float legMaxR = 0
var float legMaxBeta = 0
var float legMae = 0
// States: 0 pending, 2 confirmed, 3 tested, 4 mitigated, 5 invalid, 6 expired.
var array<int> dirs = array.new_int()
var array<int> states = array.new_int()
var array<int> candBars = array.new_int()
var array<int> confBars = array.new_int()
var array<float> lows = array.new_float()
var array<float> highs = array.new_float()
var array<bool> touchedBefore = array.new_bool()
var array<bool> firstTouch = array.new_bool()
var array<bool> observedFvg = array.new_bool()
var array<float> confirmedSigma = array.new_float()
var array<int> endBars = array.new_int()
var array<box> drawings = array.new_box()
var array<label> captions = array.new_label()
bool newBull = false
bool newBear = false
bool touchBull = false
bool touchBear = false
bool mitigatedEvent = false
bool invalidEvent = false
bool retestBull = false
bool retestBear = false
var int liveBull = 0
var int liveBear = 0
var int displayed = 0
var int droppedTracking = 0
if barstate.isconfirmed and ready
liveBull := 0
liveBear := 0
displayed := 0
bool largeHigh = f_pivot(kLarge, true)
bool largeLow = f_pivot(kLarge, false)
bool smallHigh = f_pivot(kSmall, true)
bool smallLow = f_pivot(kSmall, false)
if largeHigh
sh := high[kLarge]
shKnown := bar_index
shBroken := false
if largeLow
sl := low[kLarge]
slKnown := bar_index
slBroken := false
if smallHigh
smallH := high[kSmall]
smallHKnown := bar_index
smallHBroken := false
if smallLow
smallL := low[kSmall]
smallLKnown := bar_index
smallLBroken := false
bool largeBosUp = false
bool largeBosDn = false
bool mssUp = false
bool mssDn = false
if trend == 0
if not shBroken and close > sh + tol and shKnown > lastLargeEvent
largeBosUp := true
trend := 1
protectedL := sl
else if not slBroken and close < sl - tol and slKnown > lastLargeEvent
largeBosDn := true
trend := -1
protectedH := sh
else if trend == 1
if not shBroken and close > sh + tol and shKnown > lastLargeEvent
largeBosUp := true
if not na(sl) and (na(protectedL) or sl > protectedL)
protectedL := sl
else if not na(protectedL) and close < protectedL - tol
mssDn := true
trend := -1
protectedH := sh
protectedL := na
else
if not slBroken and close < sl - tol and slKnown > lastLargeEvent
largeBosDn := true
if not na(sh) and (na(protectedH) or sh < protectedH)
protectedH := sh
else if not na(protectedH) and close > protectedH + tol
mssUp := true
trend := 1
protectedL := sl
protectedH := na
if largeBosUp or largeBosDn or mssUp or mssDn
lastLargeEvent := bar_index
if largeBosUp
shBroken := true
if largeBosDn
slBroken := true
bool smallBosUp = not smallHBroken and close > smallH + tol and smallHKnown > lastSmallEvent
bool smallBosDn = not smallLBroken and close < smallL - tol and smallLKnown > lastSmallEvent
if smallBosUp or smallBosDn
lastSmallEvent := bar_index
if smallBosUp
smallHBroken := true
if smallBosDn
smallLBroken := true
bool bosUp = largeBosUp or smallBosUp
bool bosDn = largeBosDn or smallBosDn
if bosUp or mssUp
lastBullEvent := bar_index
if bosDn or mssDn
lastBearEvent := bar_index
if mssUp
lastBullMss := bar_index
if mssDn
lastBearMss := bar_index
int moveDir = close > close[1] ? 1 : close < close[1] ? -1 : 0
float barRange = high - low
float r = barRange / sigma
float beta = barRange > 0 ? math.abs(close - open) / barRange : 0
bool disp = false
int dispDir = 0
int dispStart = na
if not legOn or moveDir != legDir
legOn := moveDir != 0 and r >= dispRange
if legOn
legDir := moveDir
legStart := bar_index
legBars := 1
legRef := close[1]
legMaxR := r
legMaxBeta := beta
legMae := math.min(0.0, moveDir == 1 ? low - legRef : legRef - high)
else
legBars += 1
legMaxR := math.max(legMaxR, r)
legMaxBeta := math.max(legMaxBeta, beta)
legMae := math.min(0.0, math.min(legMae, legDir == 1 ? low - legRef : legRef - high))
float mag = (close - legRef) * legDir / sigma
disp := mag >= dispMag and legMaxR >= dispRange and legMaxBeta >= dispBody and legBars <= dispMaxBars and math.abs(legMae) <= dispAdverse * sigma
if disp
dispDir := legDir
dispStart := legStart
legOn := false
else if legBars > dispMaxBars or math.abs(legMae) > dispAdverse * sigma
legOn := false
if disp and dispStart > 0
int candidate = na
for j = 1 to lookback
int off = bar_index - dispStart + j
if na(candidate) and dispStart - j >= 0 and close[off] != open[off] and (close[off] > open[off] ? 1 : -1) == -dispDir
candidate := dispStart - j
if not na(candidate) and bar_index - candidate <= confirmWindow
int off = bar_index - candidate
[zlo, zhi] = f_zone(off, dispDir)
bool valid = zhi > zlo + tol and (zoneMode != "BODY" or math.abs(close[off] - open[off]) / (high[off] - low[off]) >= 0.1)
if valid
for j = 0 to off - 1
if dispDir == 1 ? close[j] < zlo - tol : close[j] > zhi + tol
valid := false
if valid
array.push(dirs, dispDir)
array.push(states, 0)
array.push(candBars, candidate)
array.push(confBars, -1)
array.push(lows, zlo)
array.push(highs, zhi)
array.push(touchedBefore, false)
array.push(firstTouch, false)
array.push(observedFvg, false)
array.push(confirmedSigma, na)
array.push(endBars, -1)
array.push(drawings, na)
array.push(captions, na)
int count = array.size(states)
if count > 0
for i = 0 to count - 1
int state = array.get(states, i)
int dir = array.get(dirs, i)
int cand = array.get(candBars, i)
int conf = array.get(confBars, i)
float zlo = array.get(lows, i)
float zhi = array.get(highs, i)
if state == 0
bool broken = dir == 1 ? close < zlo - tol : close > zhi + tol
int evt = dir == 1 ? lastBullEvent : lastBearEvent
bool hasBos = strictConfirm ? disp and dispDir == dir and (dir == 1 ? bosUp : bosDn) : evt > cand and evt <= bar_index
if broken or bar_index - cand > confirmWindow
array.set(states, i, 5)
array.set(endBars, i, bar_index)
else if hasBos
bool hasFvg = f_gap(cand, dir, zlo, zhi)
bool gapOk = not requireFvg or hasFvg
if gapOk
array.set(states, i, 2)
array.set(confBars, i, bar_index)
array.set(observedFvg, i, hasFvg)
array.set(confirmedSigma, i, sigma)
newBull := newBull or dir == 1
newBear := newBear or dir == -1
else
array.set(states, i, 5)
array.set(endBars, i, bar_index)
else if state >= 2 and state <= 4 and bar_index > conf
bool invalid = dir == 1 ? close < zlo - invalidBuf * sigma : close > zhi + invalidBuf * sigma
if invalidMode == "CLOSE_WICK"
invalid := invalid or (dir == 1 ? low < zlo - invalidWick * sigma : high > zhi + invalidWick * sigma)
if invalid
array.set(states, i, 5)
if state != 4
array.set(endBars, i, bar_index)
invalidEvent := true
else if state != 4 and ((maxAge > 0 and bar_index - conf > maxAge) or (expireStructure and trend == -dir))
array.set(states, i, 6)
array.set(endBars, i, bar_index)
else if state != 4
bool touched = low <= zhi and high >= zlo
if touched
bool first = not array.get(firstTouch, i)
if first
array.set(firstTouch, i, true)
touchBull := touchBull or dir == 1
touchBear := touchBear or dir == -1
bool sideClose = dir == 1 ? close > zhi : close < zlo
retestBull := retestBull or (dir == 1 and sideClose)
retestBear := retestBear or (dir == -1 and sideClose)
float penetration = dir == 1 ? (zhi - low) / (zhi - zlo) : (high - zlo) / (zhi - zlo)
if penetration >= mitigation or (close >= zlo and close <= zhi)
array.set(states, i, 4)
array.set(endBars, i, bar_index)
mitigatedEvent := true
else if state == 2
array.set(states, i, 3)
array.set(touchedBefore, i, touched)
while array.size(states) > maxZones
int evictedState = array.get(states, 0)
if evictedState == 0 or (evictedState >= 2 and evictedState <= 4)
droppedTracking += 1
box bx = array.shift(drawings)
if not na(bx)
box.delete(bx)
label lb = array.shift(captions)
if not na(lb)
label.delete(lb)
array.shift(dirs)
array.shift(states)
array.shift(candBars)
array.shift(confBars)
array.shift(lows)
array.shift(highs)
array.shift(touchedBefore)
array.shift(firstTouch)
array.shift(observedFvg)
array.shift(confirmedSigma)
array.shift(endBars)
// Drawing limits never remove a zone from the lifecycle arrays.
int kept = (barstate.islastconfirmedhistory or barstate.islast) ? array.size(states) : 0
if kept > 0
array<bool> selected = array.new_bool(kept, false)
for j = 0 to kept - 1
int state = array.get(states, j)
if state == 2 or state == 3
liveBull += array.get(dirs, j) == 1 ? 1 : 0
liveBear += array.get(dirs, j) == -1 ? 1 : 0
// Newest live zones take priority; historical zones use spare slots.
for phase = 0 to (showHistory ? 1 : 0)
for j = 0 to kept - 1
int i = kept - 1 - j
int state = array.get(states, i)
int cand = array.get(candBars, i)
bool live = state == 2 or state == 3
bool history = state >= 4 and array.get(confBars, i) >= 0 and showHistory
float zlo = array.get(lows, i)
float zhi = array.get(highs, i)
float referenceSigma = array.get(confirmedSigma, i)
bool widthOk = not na(referenceSigma) and zhi - zlo <= drawSigma * referenceSigma
bool eligible = (phase == 0 ? live : history) and bar_index - cand <= drawAge and widthOk
if eligible and displayed < maxVisible
array.set(selected, i, true)
displayed += 1
int dir = array.get(dirs, i)
color base = dir == 1 ? colBull : colBear
int fade = state == 2 ? 82 : state == 3 ? 88 : state == 4 ? 92 : 96
int right = live ? bar_index : array.get(endBars, i)
box bx = array.get(drawings, i)
if na(bx)
bx := box.new(cand, zhi, right, zlo, border_color = color.new(base, fade - 80), bgcolor = color.new(base, fade))
array.set(drawings, i, bx)
else
box.set_right(bx, right)
box.set_border_color(bx, color.new(base, fade - 80))
box.set_bgcolor(bx, color.new(base, fade))
label lb = array.get(captions, i)
if showLabels
string status = state == 2 ? "confirmed" : state == 3 ? "tested" : state == 4 ? "mitigated" : "retired"
string title = (dir == 1 ? "Bullish OB " : "Bearish OB ") + status + (array.get(observedFvg, i) ? " / FVG" : "")
color labelColor = state == 3 ? colTest : state == 4 ? colMit : state >= 5 ? colDead : base
if na(lb)
lb := label.new(right, dir == 1 ? zlo : zhi, title, style = dir == 1 ? label.style_label_up : label.style_label_down, color = labelColor, textcolor = color.white, size = size.tiny)
array.set(captions, i, lb)
else
label.set_xy(lb, right, dir == 1 ? zlo : zhi)
label.set_text(lb, title)
label.set_color(lb, labelColor)
else if not na(lb)
label.delete(lb)
array.set(captions, i, na)
for i = 0 to kept - 1
if not array.get(selected, i)
box bx = array.get(drawings, i)
if not na(bx)
box.delete(bx)
array.set(drawings, i, na)
label lb = array.get(captions, i)
if not na(lb)
label.delete(lb)
array.set(captions, i, na)
plotshape(showConfirm and newBull, "Bullish OB confirmed", shape.circle, location.belowbar, colBull, size = size.tiny, show_last = signalAge)
plotshape(showConfirm and newBear, "Bearish OB confirmed", shape.circle, location.abovebar, colBear, size = size.tiny, show_last = signalAge)
plotshape(showSignals and retestBull, "Bullish zone first retest", shape.triangleup, location.belowbar, colBull, size = size.tiny, show_last = signalAge)
plotshape(showSignals and retestBear, "Bearish zone first retest", shape.triangledown, location.abovebar, colBear, size = size.tiny, show_last = signalAge)
alertcondition(newBull or newBear, "Order block confirmed", "OBU: new order block confirmed")
alertcondition(touchBull or touchBear, "First touch", "OBU: first touch of an order block")
alertcondition(mitigatedEvent, "Order block mitigated", "OBU: order block mitigated")
alertcondition(invalidEvent, "Order block invalidated", "OBU: order block invalidated")
alertcondition(retestBull or retestBear, "First retest with directional close", "OBU: first retest with directional close")
var table panel = table.new(position.top_right, 1, 5, bgcolor = color.new(color.black, 20))
if barstate.islast and showPanel
table.cell(panel, 0, 0, "OBU 2.2 EN", text_color = color.white)
table.cell(panel, 0, 1, "TF: " + timeframe.period + " / " + (strictConfirm ? "STRICT" : "WINDOW"), text_color = color.white)
table.cell(panel, 0, 2, "Active bullish: " + str.tostring(liveBull) + " / bearish: " + str.tostring(liveBear), text_color = color.white)
table.cell(panel, 0, 3, "Drawn zones: " + str.tostring(displayed), text_color = color.white)
table.cell(panel, 0, 4, "FIFO tracking evictions: " + str.tostring(droppedTracking), text_color = color.white)