本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © officialjackofalltrades
//@version=6
indicator("Order Block Matrix [JOAT]", "OBM [JOAT]", overlay = true, max_lines_count = 500, max_labels_count = 500,
max_boxes_count = 150, max_bars_back = 500)
// ─── Inputs ───────────────────────────────────────────────────────────────
const string G_GEN = "General"
const string G_STR = "Market structure"
const string G_OB = "Order blocks"
const string G_BRK = "Breakers and mitigation blocks"
const string G_LIQ = "Liquidity"
const string G_PD = "Premium / discount"
const string G_HTF = "Higher-timeframe levels"
const string G_CF = "Confluence score"
const string G_DSH = "Dashboard"
const string G_CUS = "Custom theme colours"
string displayMode = input.string("Live", "Display mode", options = ["Live", "All history"], group = G_GEN, display = display.none,
tooltip = "Live keeps the newest 6 major and 6 minor structure breaks, 6 sweeps and 6 equal highs / lows on the chart. All history keeps up to 100 breaks of each kind, 80 sweeps and 50 equal highs / lows.")
string theme = input.string("Emerald Ruby", "Theme", options = ["Emerald Ruby", "Mystic", "Ice Magenta", "Royal Gold", "Aqua Ember", "Ocean Amber", "Sakura Teal", "Aurora", "Mono", "Custom"], group = G_GEN, display = display.none,
tooltip = "Colour pair for bull / bear and the dashboard. Emerald Ruby is this indicator's own palette. Mono is a clean grey pair that switches to dark greys on a light chart. Custom uses the colours at the bottom of the settings.")
bool paintBars = input.bool(true, "Paint candles by major bias", group = G_GEN, display = display.none,
tooltip = "Candles take the bull colour while the major structure is bullish and the bear colour while it is bearish.")
string tagSizeIn = input.string("Small", "Tag size", options = ["Small", "Normal"], group = G_GEN, display = display.none,
tooltip = "Size of the right-edge tags. The tags are stacked so they never overlap; Normal spaces them a little wider.")
string pivEngine = input.string("Adaptive ZigZag", "Major pivot engine", options = ["Adaptive ZigZag", "Fixed window"], group = G_STR, display = display.none,
tooltip = "Adaptive ZigZag confirms a swing once price has reversed from it by the ATR multiple below, so swings follow volatility. Fixed window needs a set number of lower highs / higher lows on each side.")
float pivAtrMult = input.float(1.8, "ZigZag reversal (ATR)", minval = 0.5, maxval = 10.0, step = 0.1, group = G_STR, display = display.none,
tooltip = "How far price must turn from a swing, in ATR(14), before the swing is confirmed. Higher = fewer, larger swings.")
int pivWindow = input.int(25, "Fixed window (bars each side)", minval = 3, maxval = 100, group = G_STR, display = display.none,
tooltip = "Used by the Fixed window engine only.")
int microWin = input.int(4, "Minor pivot window (bars each side)", minval = 2, maxval = 20, group = G_STR, display = display.none,
tooltip = "Bars on each side of a minor swing high / low. Minor swings feed the dashed structure, the sweeps and (by default) the equal highs / lows.")
bool showMajor = input.bool(true, "Show major structure", group = G_STR, display = display.none)
bool showMinor = input.bool(true, "Show minor structure", group = G_STR, display = display.none)
bool markMss = input.bool(true, "Mark displacement CHoCH as MSS", group = G_STR, display = display.none,
tooltip = "A change of character whose breaking candle is a displacement (body at least 55% of its range and at least the size below) is tagged MSS instead of CHoCH.")
float dispMult = input.float(1.2, "Displacement body (ATR)", minval = 0.3, maxval = 5.0, step = 0.1, group = G_STR, display = display.none)
bool showSwings = input.bool(false, "Label major swings (HH / HL / LH / LL)", group = G_STR, display = display.none)
bool showOB = input.bool(true, "Show order blocks", group = G_OB, display = display.none)
string obBuildOn = input.string("Major breaks", "Build blocks on", options = ["Major breaks", "Major and minor breaks"], group = G_OB, display = display.none,
tooltip = "Major breaks give fewer, structural blocks. Adding minor breaks also builds a block for each internal break.")
int obShow = input.int(3, "Live blocks drawn per side", minval = 1, maxval = 10, group = G_OB, display = display.none,
tooltip = "Up to 12 live blocks per side are tracked. Only the nearest ones to price are drawn, and only inside Draw within (ATR).")
float drawAtr = input.float(8.0, "Draw within (ATR)", minval = 1.0, maxval = 100.0, step = 0.5, group = G_OB, display = display.none,
tooltip = "Blocks and breakers further than this from the close (in ATR) are not drawn, so a far zone never squashes the candles. They still count in the dashboard.")
int obWalk = input.int(60, "Max search window (bars)", minval = 5, maxval = 200, group = G_OB, display = display.none,
tooltip = "The block is searched from the swing extreme of the breaking leg to the break. The search never reaches back further than this.")
string obRule = input.string("Close", "Violated by", options = ["Close", "Wick"], group = G_OB, display = display.none,
tooltip = "Close: a block dies when a candle closes beyond its far edge. Wick: a wick beyond the far edge is enough.")
bool obVolReq = input.bool(false, "Candle must have above-average volume", group = G_OB, display = display.none)
float obVolMult = input.float(1.25, "Volume multiple", minval = 1.0, maxval = 5.0, step = 0.05, group = G_OB, display = display.none)
int minScore = input.int(0, "Min block score", minval = 0, maxval = 100, group = G_OB, display = display.none,
tooltip = "Blocks scoring below this are not built.")
bool showSplit = input.bool(true, "Volumetric split bars", group = G_OB, display = display.none,
tooltip = "Two bars inside each block: the bought share of its candle (bull colour, upper bar) and the sold share (bear colour, lower bar), by where the candle closed inside its range. Each bar's length is its share of the block's width.")
int zoneExt = input.int(8, "Zones end (bars right of the last bar)", minval = 2, maxval = 60, group = G_OB, display = display.none,
tooltip = "Blocks, breakers and the premium / discount gradient end here and their tags start here.")
bool showBrk = input.bool(true, "Show breaker blocks", group = G_BRK, display = display.none,
tooltip = "A block that price closes through flips role and becomes a breaker (dashed, opposite colour). It dies when price closes back through it.")
int brkShow = input.int(2, "Breakers drawn per side", minval = 1, maxval = 6, group = G_BRK, display = display.none)
bool showMb = input.bool(true, "Tag the first block after a BOS as MB", group = G_BRK, display = display.none,
tooltip = "After a major BOS, the first block built on that side is tagged MB (mitigation block) instead of OB.")
bool showEq = input.bool(true, "Show equal highs / lows", group = G_LIQ, display = display.none)
string eqSrc = input.string("Minor pivots", "Equal highs / lows from", options = ["Minor pivots", "Major pivots"], group = G_LIQ, display = display.none)
float eqTol = input.float(0.15, "Equal tolerance (ATR)", minval = 0.01, maxval = 1.0, step = 0.01, group = G_LIQ, display = display.none,
tooltip = "Two swing highs (lows) closer than this, with no candle beyond them in between, are equal highs (lows).")
int eqLook = input.int(100, "Equal scan depth (bars)", minval = 10, maxval = 300, group = G_LIQ, display = display.none)
bool showSweep = input.bool(true, "Show liquidity sweeps (X)", group = G_LIQ, display = display.none,
tooltip = "A candle whose wick runs through an unbroken swing high / low and closes back inside. The wick must be at least the size below and 35% of the candle.")
float swWick = input.float(0.6, "Min sweep wick (ATR)", minval = 0.1, maxval = 3.0, step = 0.05, group = G_LIQ, display = display.none)
int swCool = input.int(8, "Sweep cooldown (bars)", minval = 1, maxval = 50, group = G_LIQ, display = display.none)
bool showPD = input.bool(true, "Show premium / discount", group = G_PD, display = display.none,
tooltip = "The dealing range runs from the latest major swing high to the latest major swing low (each extended by any new extreme since). Above equilibrium is premium, below is discount.")
string eqMethod = input.string("AVWAP", "Equilibrium", options = ["AVWAP", "Range midpoint"], group = G_PD, display = display.none,
tooltip = "AVWAP: volume-weighted average price anchored at the start of the dealing range. Range midpoint: the 50% level.")
int pdSteps = input.int(6, "Gradient steps", minval = 2, maxval = 12, group = G_PD, display = display.none)
bool showPDH = input.bool(false, "Previous day high / low", group = G_HTF, display = display.none)
bool showPWH = input.bool(false, "Previous week high / low", group = G_HTF, display = display.none)
bool showPMH = input.bool(false, "Previous month high / low", group = G_HTF, display = display.none,
tooltip = "Each switched-on level is drawn when it sits near the visible price range. Levels need a chart timeframe below their own.")
float cfProx = input.float(3.0, "Block proximity range (ATR)", minval = 0.5, maxval = 20.0, step = 0.5, group = G_CF, display = display.none,
tooltip = "The block part of the score fades from full (price inside the block) to zero at this distance.")
int cfSweep = input.int(20, "A sweep counts for (bars)", minval = 1, maxval = 200, group = G_CF, display = display.none,
tooltip = "The sweep part of the score fades from full on the sweep bar to zero after this many bars.")
bool showDash = input.bool(true, "Show dashboard", group = G_DSH, display = display.none)
string dashPos = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Middle Center", "Bottom Right", "Bottom Left", "Bottom Center"], group = G_DSH, display = display.none)
string dashSize = input.string("Small", "Text size", options = ["Small", "Normal", "Large"], group = G_DSH, display = display.none)
int dashTrans = input.int(15, "Background transparency", minval = 0, maxval = 75, group = G_DSH, display = display.none)
bool dashRoom = input.bool(true, "Keep room for the dashboard", group = G_DSH, display = display.none,
tooltip = "With the dashboard at the top (or bottom), an invisible plot on the last bar adds empty room above (below) the candles so the dashboard and the right-edge tags never cover each other.")
color cusBull = input.color(#00C896, "Bull", group = G_CUS, display = display.none)
color cusBear = input.color(#E0115F, "Bear", group = G_CUS, display = display.none)
color cusBg = input.color(#0B2A26, "Dashboard background", group = G_CUS, display = display.none)
color cusFrame = input.color(#123D36, "Dashboard frame", group = G_CUS, display = display.none)
color cusHl = input.color(#7FFFD4, "Highlight row", group = G_CUS, display = display.none)
// ─── Constants ────────────────────────────────────────────────────────────
const int PAST_MAX = 4990 // furthest back a drawing starts (inside the 5,000 bar times reserved below)
const int FWD_MAX = 490 // furthest ahead a drawing reaches
const int OB_TRACK = 12 // live blocks tracked per side
const int BRK_TRACK = 6 // live breakers tracked per side
const int D_ROWS = 10 // dashboard rows
const color TR = #00000000
const color WHITE = #FFFFFF
const color MUTED = #A8B0BD
const color EQ_GREY = #9598A1
const color NEUTRAL = #F0F8FF
// a drawing anchored far back needs the bar times that far back
max_bars_back(time, 5000)
// ─── Palette ──────────────────────────────────────────────────────────────
bool light = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
color BULL = #00C896
color BEAR = #E0115F
color DBG = #0B2A26
color DFR = #123D36
color DHL = #7FFFD4
if theme == "Mystic"
BULL := #00CED1
BEAR := #9400D3
DBG := #191970
DFR := #241A3A
DHL := #B39DDB
else if theme == "Ice Magenta"
BULL := #00B7FF
BEAR := #FF2EA6
DBG := #1A1035
DFR := #2A1A50
DHL := #C77DFF
else if theme == "Royal Gold"
BULL := #FFC233
BEAR := #8A5CFF
DBG := #1C1433
DFR := #2C2150
DHL := #FFE08A
else if theme == "Aqua Ember"
BULL := #00E5C0
BEAR := #FF8C1A
DBG := #0F2230
DFR := #1B3448
DHL := #FFD2A1
else if theme == "Ocean Amber"
BULL := #00A8E8
BEAR := #FFB000
DBG := #0A1F33
DFR := #15324F
DHL := #7FD8FF
else if theme == "Sakura Teal"
BULL := #2EC4B6
BEAR := #FF6B9D
DBG := #1B1530
DFR := #2C2248
DHL := #FFC2D6
else if theme == "Aurora"
BULL := #00F5A0
BEAR := #7B2FF7
DBG := #120D2B
DFR := #221A45
DHL := #B8F5DC
else if theme == "Mono"
BULL := #E6E6E6
BEAR := #7A7A7A
DBG := #111111
DFR := #2E2E2E
DHL := #CFCFCF
else if theme == "Custom"
BULL := cusBull
BEAR := cusBear
DBG := cusBg
DFR := cusFrame
DHL := cusHl
// the dashboard is always dark, so it keeps the bright pair; on a light chart Mono turns to dark greys on price
color dBull = BULL
color dBear = BEAR
if theme == "Mono" and light
BULL := #2A2E39
BEAR := #8A8F9C
// ─── Colour helpers ───────────────────────────────────────────────────────
chan(float v) =>
float u = v / 255.0
u <= 0.03928 ? u / 12.92 : math.pow((u + 0.055) / 1.055, 2.4)
lum(color c) =>
0.2126 * chan(color.r(c)) + 0.7152 * chan(color.g(c)) + 0.0722 * chan(color.b(c))
// plain text keeps its colour where it reaches 3:1 contrast with the chart, else the chart's own text colour
ink(color c) =>
float a = lum(c)
float b = lum(chart.bg_color)
(math.max(a, b) + 0.05) / (math.min(a, b) + 0.05) >= 3.0 ? c : chart.fg_color
// a deeper shade for text on a light chart
deep(color c) =>
color.rgb(color.r(c) * 0.62, color.g(c) * 0.62, color.b(c) * 0.62)
// text on a filled tag: white, or near-black on the light fills (gold, aqua, grey)
onFill(color c) =>
lum(c) > 0.5 ? #0B0F14 : WHITE
// what a fill at transparency t looks like over a background
blend(color c, color bg, int t) =>
float k = 1.0 - t / 100.0
color.rgb(color.r(c) * k + color.r(bg) * (1.0 - k), color.g(c) * k + color.g(bg) * (1.0 - k), color.b(c) * k + color.b(bg) * (1.0 - k))
color bullTxt = ink(light ? deep(BULL) : BULL)
color bearTxt = ink(light ? deep(BEAR) : BEAR)
color mutedTxt = ink(light ? #6A6D78 : MUTED)
int tagAlpha = light ? 8 : 20
tagSize = tagSizeIn == "Normal" ? size.normal : size.small
// ─── Core series ──────────────────────────────────────────────────────────
float atr = ta.atr(14)
float volAvg = ta.sma(nz(volume), 20)
float hi300 = ta.highest(high, 300)
float lo300 = ta.lowest(low, 300)
bool cf = barstate.isconfirmed
// running sums for an AVWAP that can be anchored at any confirmed swing without a loop
float vW = nz(volume) > 0 ? volume : 1.0
var float cumPV = 0.0
var float cumV = 0.0
float cpvPrev = cumPV
float cvPrev = cumV
cumPV += hlc3 * vW
cumV += vW
// ─── Types and state ──────────────────────────────────────────────────────
type Pivot
int bar
float price
int kind // +1 high, -1 low
float cpv // running price x volume before the pivot bar
float cv // running volume before the pivot bar
type Zone
int leftBar // the block candle
int bornBar // the break that built it
float top
float bottom
int dir // +1 bull role, -1 bear role
float score
float sSize
float sDisp
float sVol
float sFvg
float buyPct
float hAtr
int tests
bool inside
bool isMb
bool isBrk
int brkBar
string src
type EqLvl
float level
int kind
int x1
line ln
label lb
bool swept
var array<Pivot> majorPivots = array.new<Pivot>()
var array<Pivot> minorPivots = array.new<Pivot>()
var array<Zone> bullOBs = array.new<Zone>()
var array<Zone> bearOBs = array.new<Zone>()
var array<Zone> bullBrks = array.new<Zone>() // breakers now acting as support (former bear blocks)
var array<Zone> bearBrks = array.new<Zone>() // breakers now acting as resistance (former bull blocks)
var array<line> majLines = array.new<line>()
var array<label> majTags = array.new<label>()
var array<line> minLines = array.new<line>()
var array<label> minTags = array.new<label>()
var array<label> swingTags = array.new<label>()
var array<label> sweepTags = array.new<label>()
var array<EqLvl> eqs = array.new<EqLvl>()
bool live = displayMode == "Live"
int capStruct = live ? 6 : 100
int capSwing = live ? 10 : 80
int capSweep = live ? 6 : 80
int capEq = live ? 6 : 50
// ─── Small helpers ────────────────────────────────────────────────────────
clampX(int x) =>
math.max(x, bar_index - PAST_MAX)
fmtP(float p) =>
str.tostring(p, format.mintick)
isDisp(float o, float c, float h, float l, float minBody) =>
float body = math.abs(c - o)
float rng = h - l
rng > 0 and body / rng >= 0.55 and body >= minBody
dirWord(int d) =>
d == 1 ? "up" : "down"
// structure line + filled tag; major = solid width 2, tag right of the break; minor = dashed, tag left of it
drawStruct(int x1, float y, int x2, string txt, int dir, bool internal, string tip) =>
color col = dir == 1 ? BULL : BEAR
line ln = line.new(clampX(x1), y, x2, y, color = internal ? color.new(col, 20) : col,
style = internal ? line.style_dashed : line.style_solid, width = internal ? 1 : 2)
label lb = label.new(x2, y, txt, style = internal ? label.style_label_right : label.style_label_left,
color = color.new(col, internal ? 35 : 15), textcolor = onFill(col), size = size.small,
text_formatting = text.format_bold, tooltip = tip)
if internal
minLines.push(ln)
minTags.push(lb)
while minLines.size() > capStruct
line.delete(minLines.shift())
while minTags.size() > capStruct
label.delete(minTags.shift())
else
majLines.push(ln)
majTags.push(lb)
while majLines.size() > capStruct
line.delete(majLines.shift())
while majTags.size() > capStruct
label.delete(majTags.shift())
// ─── Major pivots: adaptive zigzag or fixed window ────────────────────────
var float rcHigh = high
var int rcHighBar = bar_index
var float rcHighCpv = 0.0
var float rcHighCv = 0.0
var float rcLow = low
var int rcLowBar = bar_index
var float rcLowCpv = 0.0
var float rcLowCv = 0.0
var int lastConf = 0
float fixPh = ta.pivothigh(high, pivWindow, pivWindow)
float fixPl = ta.pivotlow(low, pivWindow, pivWindow)
float microPh = ta.pivothigh(high, microWin, microWin)
float microPl = ta.pivotlow(low, microWin, microWin)
float fixCpv = nz(cpvPrev[pivWindow])
float fixCv = nz(cvPrev[pivWindow])
Pivot newHi = na
Pivot newLo = na
if pivEngine == "Adaptive ZigZag"
if high >= rcHigh
rcHigh := high
rcHighBar := bar_index
rcHighCpv := cpvPrev
rcHighCv := cvPrev
if low <= rcLow
rcLow := low
rcLowBar := bar_index
rcLowCpv := cpvPrev
rcLowCv := cvPrev
if cf and not na(atr)
float thr = atr * pivAtrMult
if lastConf != 1 and rcHigh - low >= thr
newHi := Pivot.new(rcHighBar, rcHigh, 1, rcHighCpv, rcHighCv)
lastConf := 1
rcLow := low
rcLowBar := bar_index
rcLowCpv := cpvPrev
rcLowCv := cvPrev
else if lastConf != -1 and high - rcLow >= thr
newLo := Pivot.new(rcLowBar, rcLow, -1, rcLowCpv, rcLowCv)
lastConf := -1
rcHigh := high
rcHighBar := bar_index
rcHighCpv := cpvPrev
rcHighCv := cvPrev
else if cf
if not na(fixPh)
newHi := Pivot.new(bar_index - pivWindow, fixPh, 1, fixCpv, fixCv)
if not na(fixPl)
newLo := Pivot.new(bar_index - pivWindow, fixPl, -1, fixCpv, fixCv)
if not na(newHi)
majorPivots.push(newHi)
if not na(newLo)
majorPivots.push(newLo)
while majorPivots.size() > 60
majorPivots.shift()
// ─── Minor pivots ─────────────────────────────────────────────────────────
Pivot newMinHi = na
Pivot newMinLo = na
if cf and not na(microPh)
newMinHi := Pivot.new(bar_index - microWin, microPh, 1, 0.0, 0.0)
minorPivots.push(newMinHi)
if cf and not na(microPl)
newMinLo := Pivot.new(bar_index - microWin, microPl, -1, 0.0, 0.0)
minorPivots.push(newMinLo)
while minorPivots.size() > 120
minorPivots.shift()
// ─── Optional swing names ─────────────────────────────────────────────────
swingName(Pivot p) =>
string nm = p.kind == 1 ? "H" : "L"
int sz = majorPivots.size()
if sz >= 2
for i = sz - 2 to math.max(sz - 20, 0)
Pivot q = majorPivots.get(i)
if q.kind == p.kind and q.bar != p.bar
nm := p.kind == 1 ? (p.price > q.price ? "HH" : "LH") : (p.price < q.price ? "LL" : "HL")
break
nm
if showSwings
if not na(newHi)
swingTags.push(label.new(clampX(newHi.bar), newHi.price, swingName(newHi), style = label.style_label_down,
color = TR, textcolor = bearTxt, size = size.small))
if not na(newLo)
swingTags.push(label.new(clampX(newLo.bar), newLo.price, swingName(newLo), style = label.style_label_up,
color = TR, textcolor = bullTxt, size = size.small))
while swingTags.size() > capSwing
label.delete(swingTags.shift())
// ─── Dealing range and equilibrium ────────────────────────────────────────
var Pivot lastHi = na
var Pivot lastLo = na
var float rangeHi = na
var float rangeLo = na
if not na(newHi)
lastHi := newHi
rangeHi := newHi.price
if not na(newLo)
lastLo := newLo
rangeLo := newLo.price
if not na(rangeHi)
rangeHi := math.max(rangeHi, high)
if not na(rangeLo)
rangeLo := math.min(rangeLo, low)
int rangeStart = na
float eqAv = na
if not na(lastHi) and not na(lastLo)
Pivot anc = lastHi.bar <= lastLo.bar ? lastHi : lastLo
rangeStart := anc.bar
float dv = cumV - anc.cv
if dv > 0
eqAv := (cumPV - anc.cpv) / dv
float eqMid = (rangeHi + rangeLo) / 2.0
float eqLvl = eqMethod == "AVWAP" and not na(eqAv) ? math.max(rangeLo, math.min(rangeHi, eqAv)) : eqMid
// ─── Major structure: BOS / CHoCH / MSS ───────────────────────────────────
var float pendH = na
var int pendHBar = na
var float pendL = na
var int pendLBar = na
var bool hSwept = false
var bool lSwept = false
var int majState = 0
var string lastKind = ""
var int lastDir = 0
var int lastBar = na
var bool needMbBull = false
var bool needMbBear = false
if not na(newHi)
pendH := newHi.price
pendHBar := newHi.bar
hSwept := false
if not na(newLo)
pendL := newLo.price
pendLBar := newLo.bar
lSwept := false
bool bullMaj = cf and not na(pendH) and close > pendH and close[1] <= pendH
bool bearMaj = cf and not na(pendL) and close < pendL and close[1] >= pendL
int brokenHBar = pendHBar
int brokenLBar = pendLBar
string bullKind = ""
string bearKind = ""
if bullMaj
bool dispOk = isDisp(open, close, high, low, nz(atr) * dispMult)
bullKind := majState == -1 ? (markMss and dispOk ? "MSS" : "CHoCH") : "BOS"
if showMajor
drawStruct(pendHBar, pendH, bar_index, bullKind, 1, false,
"Major " + bullKind + " up: closed above the major swing high at " + fmtP(pendH) + ", "
+ str.tostring(bar_index - pendHBar) + " bars after it formed" + (dispOk ? ", on a displacement candle" : ""))
majState := 1
pendH := na
lastKind := bullKind
lastDir := 1
lastBar := bar_index
needMbBear := false
if bullKind == "BOS"
needMbBull := true
if bearMaj
bool dispOk = isDisp(open, close, high, low, nz(atr) * dispMult)
bearKind := majState == 1 ? (markMss and dispOk ? "MSS" : "CHoCH") : "BOS"
if showMajor
drawStruct(pendLBar, pendL, bar_index, bearKind, -1, false,
"Major " + bearKind + " down: closed below the major swing low at " + fmtP(pendL) + ", "
+ str.tostring(bar_index - pendLBar) + " bars after it formed" + (dispOk ? ", on a displacement candle" : ""))
majState := -1
pendL := na
lastKind := bearKind
lastDir := -1
lastBar := bar_index
needMbBull := false
if bearKind == "BOS"
needMbBear := true
// ─── Minor structure: iBOS / iCHoCH ───────────────────────────────────────
var float pendHm = na
var int pendHmBar = na
var float pendLm = na
var int pendLmBar = na
var bool hmSwept = false
var bool lmSwept = false
var int minState = 0
var int lastMinHiBar = na
var int lastMinLoBar = na
if not na(newMinHi)
pendHm := newMinHi.price
pendHmBar := newMinHi.bar
hmSwept := false
lastMinHiBar := newMinHi.bar
if not na(newMinLo)
pendLm := newMinLo.price
pendLmBar := newMinLo.bar
lmSwept := false
lastMinLoBar := newMinLo.bar
bool bullMin = cf and not na(pendHm) and close > pendHm and close[1] <= pendHm
bool bearMin = cf and not na(pendLm) and close < pendLm and close[1] >= pendLm
int brokenHmBar = pendHmBar
int brokenLmBar = pendLmBar
if bullMin
string k = minState == -1 ? "iCHoCH" : "iBOS"
if showMinor and not bullMaj
drawStruct(pendHmBar, pendHm, bar_index, k, 1, true,
"Minor " + k + " up: closed above the minor swing high at " + fmtP(pendHm))
minState := 1
pendHm := na
if bearMin
string k = minState == 1 ? "iCHoCH" : "iBOS"
if showMinor and not bearMaj
drawStruct(pendLmBar, pendLm, bar_index, k, -1, true,
"Minor " + k + " down: closed below the minor swing low at " + fmtP(pendLm))
minState := -1
pendLm := na
// ─── Order blocks: structural-extreme search, score, volumetric split ─────
// dir +1: the most extreme (lowest) bear candle of the leg that broke the swing high; -1 mirrored.
// Score 0-100 = size 25 + displacement 30 + volume 25 + FVG 20.
// called on every bar (history offsets stay consistent); it only searches when active (a break on this bar)
pushOB(array<Zone> arr, int dir, int window, bool mb, string src, bool active) =>
bool made = false
int w = math.max(2, math.min(nz(window, obWalk), obWalk))
int k = -1
float zt = na
float zb = na
float a = math.max(nz(atr), syminfo.mintick)
if active
for i = 1 to w
float o_ = open[i]
float c_ = close[i]
float h_ = high[i]
float l_ = low[i]
float rg = h_ - l_
bool opp = dir == 1 ? c_ < o_ : c_ > o_
bool ok = opp and rg > 0 and rg < a * 2.5 and math.abs(c_ - o_) / rg >= 0.2
if ok and obVolReq
ok := nz(volume[i]) >= nz(volAvg[i]) * obVolMult
if ok
if dir == 1 ? (na(zb) or l_ < zb) : (na(zt) or h_ > zt)
k := i
zt := h_
zb := l_
if k > 0
float hA = (zt - zb) / a
float sS = math.min(hA / 1.5, 1.0) * 25.0
float mxBody = 0.0
for j = 0 to k - 1
mxBody := math.max(mxBody, math.abs(close[j] - open[j]))
float sD = math.min(mxBody / (1.5 * a), 1.0) * 30.0
float va = nz(volAvg[k])
float sV = va > 0 ? math.min(nz(volume[k]) / va / 2.0, 1.0) * 25.0 : 12.5
float sF = 0.0
if k >= 2
for j = 0 to k - 2
bool gap = dir == 1 ? low[j] > high[j + 2] : high[j] < low[j + 2]
if gap
float nearEdge = dir == 1 ? high[j + 2] : low[j + 2]
bool close1 = dir == 1 ? nearEdge <= zt + a : nearEdge >= zb - a
sF := math.max(sF, close1 ? 20.0 : 10.0)
float sc = sS + sD + sV + sF
int lb = bar_index - k
bool skip = sc < minScore
// overlap rule: a same-side block sharing half of the smaller height keeps only the higher score
if not skip
for z in arr
float ov = math.min(z.top, zt) - math.max(z.bottom, zb)
float smh = math.min(z.top - z.bottom, zt - zb)
if z.leftBar == lb or (smh > 0 and ov >= 0.5 * smh and z.score >= sc)
skip := true
break
if not skip
int n = arr.size()
if n > 0
for i = n - 1 to 0
Zone z = arr.get(i)
float ov = math.min(z.top, zt) - math.max(z.bottom, zb)
float smh = math.min(z.top - z.bottom, zt - zb)
if smh > 0 and ov >= 0.5 * smh
arr.remove(i)
float hk = high[k]
float lk = low[k]
float bp = hk > lk ? (close[k] - lk) / (hk - lk) : 0.5
arr.push(Zone.new(lb, bar_index, zt, zb, dir, sc, sS, sD, sV, sF, bp, hA, 0, false, mb, false, na, src))
made := true
while arr.size() > OB_TRACK
arr.shift()
made
// search window: from the swing extreme that launched the breaking leg (3 bars of slack), never before the broken
// swing unless that extreme is older, capped by Max search window
obWindow(int extBar, int brokenBar) =>
int org = na(extBar) ? brokenBar : na(brokenBar) ? extBar : math.max(extBar, brokenBar)
na(org) ? obWalk : bar_index - org + 3
bool minorObs = obBuildOn == "Major and minor breaks"
int winBullMj = obWindow(na(lastLo) ? na : lastLo.bar, brokenHBar)
int winBearMj = obWindow(na(lastHi) ? na : lastHi.bar, brokenLBar)
int winBullMn = obWindow(lastMinLoBar, brokenHmBar)
int winBearMn = obWindow(lastMinHiBar, brokenLmBar)
bool mbBullMj = showMb and needMbBull
bool madeBullMj = pushOB(bullOBs, 1, winBullMj, mbBullMj, "major " + bullKind, showOB and bullMaj)
if madeBullMj and mbBullMj
needMbBull := false
bool mbBearMj = showMb and needMbBear
bool madeBearMj = pushOB(bearOBs, -1, winBearMj, mbBearMj, "major " + bearKind, showOB and bearMaj)
if madeBearMj and mbBearMj
needMbBear := false
bool mbBullMn = showMb and needMbBull
bool madeBullMn = pushOB(bullOBs, 1, winBullMn, mbBullMn, "minor break", showOB and minorObs and bullMin and not bullMaj)
if madeBullMn and mbBullMn
needMbBull := false
bool mbBearMn = showMb and needMbBear
bool madeBearMn = pushOB(bearOBs, -1, winBearMn, mbBearMn, "minor break", showOB and minorObs and bearMin and not bearMaj)
if madeBearMn and mbBearMn
needMbBear := false
// ─── Block life: visits, violation, flip to breaker ───────────────────────
isDead(Zone z, int dir) =>
dir == 1 ? (obRule == "Close" ? close < z.bottom : low < z.bottom) : (obRule == "Close" ? close > z.top : high > z.top)
updateOBs(array<Zone> arr, array<Zone> flipTo, int dir) =>
bool entered = false
int n = arr.size()
if n > 0
for i = n - 1 to 0
Zone z = arr.get(i)
if z.bornBar < bar_index
if isDead(z, dir)
arr.remove(i)
if showBrk
z.dir := -dir
z.isBrk := true
z.brkBar := bar_index
z.tests := 0
z.inside := true
flipTo.push(z)
while flipTo.size() > BRK_TRACK
flipTo.shift()
else
bool touch = dir == 1 ? low <= z.top : high >= z.bottom
if touch and not z.inside
z.tests += 1
entered := true
z.inside := touch
entered
updateBrks(array<Zone> arr, int dir) =>
int n = arr.size()
if n > 0
for i = n - 1 to 0
Zone z = arr.get(i)
if z.brkBar < bar_index
if isDead(z, dir)
arr.remove(i)
else
bool touch = dir == 1 ? low <= z.top : high >= z.bottom
if touch and not z.inside
z.tests += 1
z.inside := touch
n
bool enteredBull = false
bool enteredBear = false
if cf
enteredBull := updateOBs(bullOBs, bearBrks, 1)
enteredBear := updateOBs(bearOBs, bullBrks, -1)
updateBrks(bullBrks, 1)
updateBrks(bearBrks, -1)
// ─── Equal highs / lows ───────────────────────────────────────────────────
// a pair of same-kind swings within the tolerance, no candle beyond the level between them
findEq(Pivot p, array<Pivot> arr) =>
float tol = nz(atr) * eqTol
int sz = arr.size()
Pivot hit = na
if sz >= 2 and tol > 0
for i = sz - 2 to math.max(sz - 25, 0)
Pivot q = arr.get(i)
if bar_index - q.bar > eqLook
break
if q.kind == p.kind and q.bar < p.bar and math.abs(q.price - p.price) <= tol
float lvl = p.kind == 1 ? math.max(p.price, q.price) : math.min(p.price, q.price)
bool clean = true
int j0 = bar_index - p.bar + 1
int j1 = bar_index - q.bar - 1
if j1 >= j0
for j = j0 to j1
if p.kind == 1 ? high[j] > lvl : low[j] < lvl
clean := false
break
if clean
hit := q
break
hit
makeEq(Pivot p, Pivot q) =>
float lvl = p.kind == 1 ? math.max(p.price, q.price) : math.min(p.price, q.price)
bool dupe = false
for e in eqs
if not e.swept and e.kind == p.kind and math.abs(e.level - lvl) <= nz(atr) * eqTol
dupe := true
if not dupe
color col = p.kind == 1 ? BEAR : BULL
line ln = line.new(clampX(q.bar), lvl, bar_index, lvl, color = color.new(col, 20), style = line.style_dotted, width = 1)
label lb = label.new(int(math.round((q.bar + p.bar) / 2.0)), lvl, p.kind == 1 ? "EQH" : "EQL",
style = p.kind == 1 ? label.style_label_down : label.style_label_up, color = TR,
textcolor = p.kind == 1 ? bearTxt : bullTxt, size = size.small,
tooltip = (p.kind == 1 ? "Equal highs at " : "Equal lows at ") + fmtP(lvl) + ": resting liquidity, the line runs until price trades through it")
eqs.push(EqLvl.new(lvl, p.kind, q.bar, ln, lb, false))
while eqs.size() > capEq
EqLvl old = eqs.shift()
line.delete(old.ln)
label.delete(old.lb)
not dupe
Pivot eqHiP = eqSrc == "Minor pivots" ? newMinHi : newHi
Pivot eqLoP = eqSrc == "Minor pivots" ? newMinLo : newLo
array<Pivot> eqArr = eqSrc == "Minor pivots" ? minorPivots : majorPivots
if showEq and not na(eqHiP)
Pivot q = findEq(eqHiP, eqArr)
if not na(q)
makeEq(eqHiP, q)
if showEq and not na(eqLoP)
Pivot q = findEq(eqLoP, eqArr)
if not na(q)
makeEq(eqLoP, q)
// untaken levels extend to the live bar; a taken level ends at the bar that took it, dims and loses its text
if cf and eqs.size() > 0
for e in eqs
if not e.swept
bool taken = e.kind == 1 ? high > e.level : low < e.level
line.set_x2(e.ln, bar_index)
if taken or bar_index - e.x1 > PAST_MAX - 200
e.swept := true
line.set_color(e.ln, color.new(e.kind == 1 ? BEAR : BULL, 75))
label.delete(e.lb)
// ─── Liquidity sweeps ─────────────────────────────────────────────────────
var int lastBullSw = na // liquidity under a swing low taken, closed back above (X below, bull colour)
var int lastBearSw = na // liquidity over a swing high taken, closed back below (X above, bear colour)
float topWick = high - math.max(open, close)
float botWick = math.min(open, close) - low
float rngNow = high - low
bool wickHiOk = rngNow > 0 and topWick >= swWick * nz(atr) and topWick / rngNow >= 0.35
bool wickLoOk = rngNow > 0 and botWick >= swWick * nz(atr) and botWick / rngNow >= 0.35
bool hitHm = not na(pendHm) and not hmSwept and bar_index - pendHmBar > 2 and high > pendHm and close < pendHm
bool hitH = not na(pendH) and not hSwept and high > pendH and close < pendH
bool hitLm = not na(pendLm) and not lmSwept and bar_index - pendLmBar > 2 and low < pendLm and close > pendLm
bool hitL = not na(pendL) and not lSwept and low < pendL and close > pendL
bool bearSweep = cf and wickHiOk and (hitHm or hitH) and (na(lastBearSw) or bar_index - lastBearSw > swCool)
bool bullSweep = cf and wickLoOk and (hitLm or hitL) and (na(lastBullSw) or bar_index - lastBullSw > swCool)
if bearSweep
lastBearSw := bar_index
hmSwept := hitHm ? true : hmSwept
hSwept := hitH ? true : hSwept
if showSweep
float lvl = hitH ? pendH : pendHm
sweepTags.push(label.new(bar_index, high, "X", style = label.style_label_down, color = BEAR, textcolor = onFill(BEAR),
size = size.small, text_formatting = text.format_bold,
tooltip = "Liquidity sweep: the wick ran above the " + (hitH ? "major" : "minor") + " swing high at " + fmtP(lvl) + " and the candle closed back below it"))
if bullSweep
lastBullSw := bar_index
lmSwept := hitLm ? true : lmSwept
lSwept := hitL ? true : lSwept
if showSweep
float lvl = hitL ? pendL : pendLm
sweepTags.push(label.new(bar_index, low, "X", style = label.style_label_up, color = BULL, textcolor = onFill(BULL),
size = size.small, text_formatting = text.format_bold,
tooltip = "Liquidity sweep: the wick ran below the " + (hitL ? "major" : "minor") + " swing low at " + fmtP(lvl) + " and the candle closed back above it"))
while sweepTags.size() > capSweep
label.delete(sweepTags.shift())
// ─── Higher-timeframe levels (optional; the chart's own timeframe is asked for while off) ──
int tfSec = timeframe.in_seconds()
bool useD = showPDH and tfSec < 86400
bool useW = showPWH and tfSec < 604800
bool useM = showPMH and tfSec < 2419200
[dH, dL] = request.security(syminfo.tickerid, useD ? "D" : "", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[wH, wL] = request.security(syminfo.tickerid, useW ? "W" : "", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[mH, mL] = request.security(syminfo.tickerid, useM ? "M" : "", [high[1], low[1]], lookahead = barmerge.lookahead_on)
// ─── Nearest zones and the confluence score (every bar: plotted and alertable) ──
zDist(Zone z) =>
close > z.top ? close - z.top : close < z.bottom ? z.bottom - close : 0.0
nearestZ(array<Zone> a) =>
Zone best = na
float bd = na
for z in a
float d = zDist(z)
if na(bd) or d < bd or (d == bd and z.score > best.score)
bd := d
best := z
best
closerZ(Zone a, Zone b) =>
na(a) ? b : na(b) ? a : zDist(b) < zDist(a) ? b : a
containingZ(array<Zone> a, Zone cur) =>
Zone best = cur
for z in a
if close <= z.top and close >= z.bottom
if na(best) or z.score > best.score
best := z
best
Zone nBullOB = nearestZ(bullOBs)
Zone nBearOB = nearestZ(bearOBs)
Zone nBullBk = nearestZ(bullBrks)
Zone nBearBk = nearestZ(bearBrks)
// price zone inside the dealing range: within 5% of the range around equilibrium = EQ
float rngH = rangeHi - rangeLo
string pzName = "None"
float posPct = na
if not na(rngH) and rngH > 0 and not na(eqLvl)
posPct := (close - rangeLo) / rngH * 100.0
pzName := close > eqLvl + 0.05 * rngH ? "Premium" : close < eqLvl - 0.05 * rngH ? "Discount" : "EQ"
// CONFLUENCE (0-100), read toward the major bias (the minor bias when there is no major one yet):
// bias 30 = 15 when a major bias exists + 15 when the minor bias agrees with the lean
// zone 20 = price in discount for a bull lean / premium for a bear lean (EQ = 10)
// block 35 = nearest bias-side block or breaker: 35 x proximity x (0.5 + 0.5 x its score / 100),
// proximity 1 inside the block, fading to 0 at "Block proximity range (ATR)"
// sweep 15 = a sweep on the bias side, fading from 15 on its bar to 0 after "A sweep counts for (bars)"
int lean = majState != 0 ? majState : minState
float cBias = (majState != 0 ? 15.0 : 0.0) + (minState != 0 and minState == lean ? 15.0 : 0.0)
float cZone = lean == 1 ? (pzName == "Discount" ? 20.0 : pzName == "EQ" ? 10.0 : 0.0) : lean == -1 ? (pzName == "Premium" ? 20.0 : pzName == "EQ" ? 10.0 : 0.0) : 0.0
Zone leanZ = lean == 1 ? closerZ(nBullOB, nBullBk) : lean == -1 ? closerZ(nBearOB, nBearBk) : na
float cOB = 0.0
if not na(leanZ) and nz(atr) > 0
float d = zDist(leanZ)
float prox = d <= 0 ? 1.0 : math.max(0.0, 1.0 - d / (cfProx * atr))
cOB := 35.0 * prox * (0.5 + 0.5 * leanZ.score / 100.0)
int swAge = lean == 1 ? (na(lastBullSw) ? na : bar_index - lastBullSw) : lean == -1 ? (na(lastBearSw) ? na : bar_index - lastBearSw) : na
float cSw = not na(swAge) and swAge <= cfSweep ? 15.0 * (1.0 - swAge / (cfSweep + 1.0)) : 0.0
int conf = int(math.round(cBias + cZone + cOB + cSw))
// ─── Visible range (tag spacing, headroom) ────────────────────────────────
var float visHi = na
var float visLo = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
visHi := na(visHi) ? high : math.max(visHi, high)
visLo := na(visLo) ? low : math.min(visLo, low)
float vHi = na(visHi) ? nz(hi300, high) : visHi
float vLo = na(visLo) ? nz(lo300, low) : visLo
float vSpan = math.max(vHi - vLo, syminfo.mintick * 10)
bool dashTop = showDash and dashRoom and (dashPos == "Top Right" or dashPos == "Top Center")
bool dashBot = showDash and dashRoom and (dashPos == "Bottom Right" or dashPos == "Bottom Center")
float headFrac = dashSize == "Large" ? 0.95 : dashSize == "Normal" ? 0.7 : 0.5
// ─── Plots (12 of 64): scale anchor, headroom, candles, data window, alerts ──
plot(close, "Scale anchor (invisible)", color = TR, display = display.pane, editable = false)
plot(barstate.islast and dashTop ? vHi + headFrac * vSpan : na, "Headroom top", color = TR, display = display.pane, editable = false)
plot(barstate.islast and dashBot ? vLo - headFrac * vSpan : na, "Headroom bottom", color = TR, display = display.pane, editable = false)
barcolor(paintBars and majState != 0 ? (majState == 1 ? BULL : BEAR) : na, title = "Bias candles", editable = false)
plot(conf, "Confluence", color = DHL, display = display.data_window, editable = false)
plot(majState, "Major bias", color = MUTED, display = display.data_window, editable = false)
plot(eqLvl, "Equilibrium", color = EQ_GREY, display = display.data_window, editable = false)
alertcondition(bullMaj, "Major structure break up", "OBM [JOAT]: major structure broke up (BOS / CHoCH / MSS) on {{ticker}} {{interval}}")
alertcondition(bearMaj, "Major structure break down", "OBM [JOAT]: major structure broke down (BOS / CHoCH / MSS) on {{ticker}} {{interval}}")
alertcondition(enteredBull, "Price reached a bull order block", "OBM [JOAT]: price reached a live bull order block on {{ticker}} {{interval}}")
alertcondition(enteredBear, "Price reached a bear order block", "OBM [JOAT]: price reached a live bear order block on {{ticker}} {{interval}}")
alertcondition(bullSweep or bearSweep, "Liquidity sweep", "OBM [JOAT]: a swing high / low was swept and the candle closed back inside on {{ticker}} {{interval}}")
// ─── Right-edge drawings: rebuilt on the last bar ─────────────────────────
var array<box> rlBoxes = array.new<box>()
var array<line> rlLines = array.new<line>()
var array<label> rlLabels = array.new<label>()
var array<float> tqY = array.new<float>()
var array<int> tqH = array.new<int>()
var array<string> tqTxt = array.new<string>()
var array<color> tqBg = array.new<color>()
var array<color> tqFg = array.new<color>()
var array<string> tqTip = array.new<string>()
var array<bool> tqFill = array.new<bool>()
queueTag(float y, int h, string txt, color bg, color fg, string tip, bool filled) =>
tqY.push(y)
tqH.push(h)
tqTxt.push(txt)
tqBg.push(bg)
tqFg.push(fg)
tqTip.push(tip)
tqFill.push(filled)
// the nearest live zones within Draw within (ATR), nearest first
pickDraw(array<Zone> a, int nMax) =>
array<Zone> cand = array.new<Zone>()
array<float> dist = array.new<float>()
float lim = drawAtr * nz(atr)
for z in a
float d = zDist(z)
if d <= lim
cand.push(z)
dist.push(d)
array<Zone> res = array.new<Zone>()
if cand.size() > 0
array<int> idx = dist.sort_indices(order.ascending)
for i = 0 to math.min(nMax, idx.size()) - 1
res.push(cand.get(idx.get(i)))
res
testsLine(int t) =>
t > 0 ? "\ntested " + str.tostring(t) + "x" : ""
drawOB(Zone z, int rx) =>
color col = z.dir == 1 ? BULL : BEAR
int lx = math.max(z.leftBar, bar_index - PAST_MAX)
rlBoxes.push(box.new(lx, z.top, rx, z.bottom, border_color = color.new(col, 45), border_width = z.isMb ? 2 : 1,
bgcolor = color.new(col, showSplit ? 87 : 82)))
if showSplit
float h = z.top - z.bottom
float mid = z.bottom + h * 0.5
int len = rx - lx
int xb = lx + math.max(1, math.round(len * z.buyPct))
int xs = lx + math.max(1, math.round(len * (1.0 - z.buyPct)))
rlBoxes.push(box.new(lx, z.top - h * 0.08, xb, mid + h * 0.03, border_color = TR, bgcolor = color.new(BULL, 78)))
rlBoxes.push(box.new(lx, mid - h * 0.03, xs, z.bottom + h * 0.08, border_color = TR, bgcolor = color.new(BEAR, 78)))
int bPct = math.round(z.buyPct * 100)
string head = (z.isMb ? "MB " : "OB ") + str.tostring(math.round(z.score)) + " · " + str.tostring(bPct) + "% buy · "
+ str.tostring(z.hAtr, "0.0") + " ATR"
string tip = (z.dir == 1 ? "Bull " : "Bear ") + (z.isMb ? "mitigation block (first block after a BOS)" : "order block")
+ ", built on a " + z.src + "\nScore " + str.tostring(math.round(z.score)) + " = size " + str.tostring(math.round(z.sSize))
+ " + displacement " + str.tostring(math.round(z.sDisp)) + " + volume " + str.tostring(math.round(z.sVol))
+ " + FVG " + str.tostring(math.round(z.sFvg)) + "\nBlock candle: " + str.tostring(bPct) + "% bought / "
+ str.tostring(100 - bPct) + "% sold by close position\n" + fmtP(z.bottom) + " to " + fmtP(z.top) + " ("
+ str.tostring(z.hAtr, "0.0") + " ATR)\nVisits since it formed: " + str.tostring(z.tests)
queueTag((z.top + z.bottom) / 2.0, z.tests > 0 ? 2 : 1, head + testsLine(z.tests), color.new(col, tagAlpha), onFill(col), tip, true)
drawBrk(Zone z, int rx) =>
color col = z.dir == 1 ? BULL : BEAR
int lx = math.max(z.brkBar, bar_index - PAST_MAX)
rlBoxes.push(box.new(lx, z.top, rx, z.bottom, border_color = color.new(col, 25), border_width = 1,
border_style = line.style_dashed, bgcolor = color.new(col, 88)))
string tip = (z.dir == 1 ? "Bull breaker: a bear block price closed up through, " : "Bear breaker: a bull block price closed down through, ")
+ str.tostring(bar_index - z.brkBar) + " bars ago. Score carried from the block: " + str.tostring(math.round(z.score))
+ "\n" + fmtP(z.bottom) + " to " + fmtP(z.top) + "\nVisits since it flipped: " + str.tostring(z.tests)
queueTag((z.top + z.bottom) / 2.0, z.tests > 0 ? 2 : 1, "BRK " + str.tostring(math.round(z.score)) + testsLine(z.tests),
color.new(col, tagAlpha), onFill(col), tip, true)
htfLevel(float lvl, string nm, int rx, float lo, float hi) =>
if not na(lvl) and lvl >= lo and lvl <= hi
rlLines.push(line.new(bar_index - 30, lvl, rx, lvl, color = color.new(mutedTxt, 25), style = line.style_dotted, width = 1))
queueTag(lvl, 1, nm + " " + fmtP(lvl), TR, mutedTxt, nm + " (previous period, closed)", false)
// right-edge tags never overlap: sorted top to bottom, pushed apart pairwise until every neighbour pair is at least
// gap x (lines of both) / 2 apart, then held under the ceiling and above the floor
stackTags(array<float> ys, array<int> hs, float gap, float ceilY, float floorY) =>
int n = ys.size()
if n > 1
for it = 1 to 60
bool moved = false
for i = 1 to n - 1
float need = gap * (hs.get(i - 1) + hs.get(i)) / 2.0
float d = ys.get(i - 1) - ys.get(i)
if d < need * 0.999
float p = (need - d) / 2.0
ys.set(i - 1, ys.get(i - 1) + p)
ys.set(i, ys.get(i) - p)
moved := true
if not moved
break
if n > 0
ys.set(0, math.min(ys.get(0), ceilY))
if n > 1
for i = 1 to n - 1
float need = gap * (hs.get(i - 1) + hs.get(i)) / 2.0
ys.set(i, math.min(ys.get(i), ys.get(i - 1) - need))
ys.set(n - 1, math.max(ys.get(n - 1), floorY))
if n > 1
for i = n - 2 to 0
float need = gap * (hs.get(i) + hs.get(i + 1)) / 2.0
ys.set(i, math.max(ys.get(i), ys.get(i + 1) + need))
n
if barstate.islast
for b in rlBoxes
box.delete(b)
rlBoxes.clear()
for l in rlLines
line.delete(l)
rlLines.clear()
for t in rlLabels
label.delete(t)
rlLabels.clear()
tqY.clear()
tqH.clear()
tqTxt.clear()
tqBg.clear()
tqFg.clear()
tqTip.clear()
tqFill.clear()
int rx = bar_index + math.min(zoneExt, FWD_MAX)
float lim = drawAtr * nz(atr)
float dHi = vHi
float dLo = vLo
// premium / discount: nested boxes from each range edge toward equilibrium (no seams), the band at EQ at
// transparency 85 and the band at the edge at 55
if showPD and not na(rangeHi) and not na(rangeLo) and rangeHi > rangeLo and not na(eqLvl) and not na(rangeStart)
int lx = math.max(rangeStart, bar_index - PAST_MAX)
for k = 1 to pdSteps
float f = float(k) / pdSteps
float oK = 0.45 - 0.30 * float(k - 1) / math.max(pdSteps - 1, 1)
float oN = k < pdSteps ? 0.45 - 0.30 * float(k) / math.max(pdSteps - 1, 1) : 0.0
int t = int(math.round(100.0 * (1.0 - oK) / (1.0 - oN)))
rlBoxes.push(box.new(lx, rangeHi, rx, rangeHi - (rangeHi - eqLvl) * f, border_color = TR, bgcolor = color.new(BEAR, t)))
rlBoxes.push(box.new(lx, rangeLo + (eqLvl - rangeLo) * f, rx, rangeLo, border_color = TR, bgcolor = color.new(BULL, t)))
rlLines.push(line.new(lx, rangeHi, rx, rangeHi, color = BEAR, width = 1))
rlLines.push(line.new(lx, eqLvl, rx, eqLvl, color = color.new(EQ_GREY, 30), style = line.style_dashed, width = 1))
rlLines.push(line.new(lx, rangeLo, rx, rangeLo, color = BULL, width = 1))
string rTip = "Dealing range " + fmtP(rangeLo) + " to " + fmtP(rangeHi) + ", equilibrium " + fmtP(eqLvl)
+ (eqMethod == "AVWAP" ? " (AVWAP from the start of the range)" : " (midpoint)")
queueTag(rangeHi, 1, "Premium", TR, bearTxt, rTip, false)
queueTag(eqLvl, 1, eqMethod == "AVWAP" ? "AVWAP EQ" : "EQ 50%", TR, mutedTxt, rTip, false)
queueTag(rangeLo, 1, "Discount", TR, bullTxt, rTip, false)
dHi := math.max(dHi, math.min(rangeHi, close + lim))
dLo := math.min(dLo, math.max(rangeLo, close - lim))
// breakers under the blocks, blocks on top
if showBrk
for z in pickDraw(bullBrks, brkShow)
drawBrk(z, rx)
dHi := math.max(dHi, z.top)
dLo := math.min(dLo, z.bottom)
for z in pickDraw(bearBrks, brkShow)
drawBrk(z, rx)
dHi := math.max(dHi, z.top)
dLo := math.min(dLo, z.bottom)
if showOB
for z in pickDraw(bullOBs, obShow)
drawOB(z, rx)
dHi := math.max(dHi, z.top)
dLo := math.min(dLo, z.bottom)
for z in pickDraw(bearOBs, obShow)
drawOB(z, rx)
dHi := math.max(dHi, z.top)
dLo := math.min(dLo, z.bottom)
// previous day / week / month, only near the visible range
float hLo = vLo - 0.25 * vSpan
float hHi = vHi + 0.25 * vSpan
if useD
htfLevel(dH, "PDH", rx, hLo, hHi)
htfLevel(dL, "PDL", rx, hLo, hHi)
if useW
htfLevel(wH, "PWH", rx, hLo, hHi)
htfLevel(wL, "PWL", rx, hLo, hHi)
if useM
htfLevel(mH, "PMH", rx, hLo, hHi)
htfLevel(mL, "PML", rx, hLo, hHi)
// stack: gap = 0.045 x the displayed span (visible candles plus everything drawn, plus the headroom)
int nT = tqY.size()
if nT > 0
float dispSpan = (dHi - dLo) + (dashTop or dashBot ? headFrac * vSpan : 0.0)
float gapU = 0.045 * dispSpan * (tagSizeIn == "Normal" ? 1.3 : 1.0)
float ceilY = dashPos == "Top Right" and dashTop ? vHi + 0.03 * vSpan : vHi + 0.3 * vSpan
float floorY = dashPos == "Bottom Right" and dashBot ? vLo - 0.03 * vSpan : vLo - 0.3 * vSpan
array<int> idx = tqY.sort_indices(order.descending)
array<float> ys = array.new<float>()
array<int> hs = array.new<int>()
for i in idx
ys.push(tqY.get(i))
hs.push(tqH.get(i))
stackTags(ys, hs, gapU, ceilY, floorY)
for j = 0 to nT - 1
int i = idx.get(j)
rlLabels.push(label.new(rx, ys.get(j), tqTxt.get(i), style = label.style_label_left, color = tqBg.get(i),
textcolor = tqFg.get(i), size = tagSize, text_formatting = tqFill.get(i) ? text.format_bold : text.format_none,
tooltip = tqTip.get(i)))
// ─── Dashboard: OB MATRIX CONFLUENCE | STATE ──────────────────────────────
posOf(string s) =>
switch s
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Right" => position.middle_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
=> position.top_right
dSize = dashSize == "Large" ? size.large : dashSize == "Normal" ? size.normal : size.small
var table dash = showDash ? table.new(posOf(dashPos), 2, D_ROWS, bgcolor = color.new(DBG, 100),
frame_color = color.new(DFR, 60), frame_width = 1, border_color = color.new(DFR, 65), border_width = 1) : na
// rows fade from the dashboard transparency at the top to +25 at the bottom
rowBg(int r) =>
color.new(DBG, int(math.round(dashTrans + 25.0 * r / (D_ROWS - 1))))
dRow(int r, string k, string v, color vc, string tip) =>
dash.cell(0, r, k, text_color = color.new(MUTED, 10), text_halign = text.align_left, text_size = dSize, bgcolor = rowBg(r), tooltip = tip)
dash.cell(1, r, v, text_color = vc, text_halign = text.align_right, text_size = dSize, bgcolor = rowBg(r), tooltip = tip)
biasTxt(int s) =>
s == 1 ? "Bull" : s == -1 ? "Bear" : "Flat"
biasCol(int s) =>
s == 1 ? color.new(dBull, 50) : s == -1 ? color.new(dBear, 50) : color.new(EQ_GREY, 70)
obCell(Zone z) =>
na(z) ? "None" : str.tostring(math.round(z.score)) + " · " + (zDist(z) <= 0 ? "inside" : str.tostring(zDist(z) / close * 100.0, "0.00") + "%")
if barstate.islast and showDash
color hdr = color.new(DBG, dashTrans)
dash.cell(0, 0, "OB MATRIX CONFLUENCE", text_color = WHITE, text_halign = text.align_left, text_size = dSize, bgcolor = hdr,
text_font_family = font.family_monospace, text_formatting = text.format_bold)
dash.cell(1, 0, "STATE", text_color = WHITE, text_halign = text.align_right, text_size = dSize, bgcolor = hdr,
text_font_family = font.family_monospace, text_formatting = text.format_bold)
dRow(1, "Major Bias", biasTxt(majState), biasCol(majState), "Direction of the last major structure break.")
dRow(2, "Minor Bias", biasTxt(minState), biasCol(minState), "Direction of the last minor structure break.")
color pzCol = pzName == "Premium" ? dBear : pzName == "Discount" ? dBull : color.new(NEUTRAL, 30)
string pzTxt = na(posPct) ? "None" : pzName + " · " + str.tostring(posPct, "0") + "%"
dRow(3, "Price Zone", pzTxt, pzCol, "Where the close sits in the dealing range (0% = range low, 100% = range high). Within 5% of the range around equilibrium reads EQ.")
dRow(4, "Nearest Bull OB", showOB ? obCell(nBullOB) : "Off", na(nBullOB) ? color.new(NEUTRAL, 30) : dBull,
"Nearest live bull block: its score and how far the close is from its top, in % of price.")
dRow(5, "Nearest Bear OB", showOB ? obCell(nBearOB) : "Off", na(nBearOB) ? color.new(NEUTRAL, 30) : dBear,
"Nearest live bear block: its score and how far the close is from its bottom, in % of price.")
Zone inZ = na
inZ := containingZ(bullOBs, inZ)
inZ := containingZ(bearOBs, inZ)
inZ := containingZ(bullBrks, inZ)
inZ := containingZ(bearBrks, inZ)
string inTxt = na(inZ) ? "No" : (inZ.dir == 1 ? "Bull " : "Bear ") + (inZ.isBrk ? "BRK" : inZ.isMb ? "MB" : "OB") + " · " + str.tostring(math.round(inZ.score))
dRow(6, "In OB?", inTxt, na(inZ) ? color.new(NEUTRAL, 30) : inZ.dir == 1 ? dBull : dBear,
"The highest-scoring block or breaker the close is inside.")
string bkTxt = not showBrk ? "Off" : bullBrks.size() + bearBrks.size() == 0 ? "None" : str.tostring(bullBrks.size()) + " bull · " + str.tostring(bearBrks.size()) + " bear"
dRow(7, "Breakers live", bkTxt, color.new(NEUTRAL, 30), "Live breakers by the role they play now (bull = former bear block now under price).")
string lsTxt = na(lastBar) ? "None" : lastKind + (lastDir == 1 ? " up · " : " down · ") + str.tostring(bar_index - lastBar) + " bars"
dRow(8, "Last structure", lsTxt, lastDir == 1 ? dBull : lastDir == -1 ? dBear : color.new(NEUTRAL, 30), "The last major break and how many bars ago it printed.")
color hlL = color.new(DHL, 60)
color hlR = color.new(DHL, 30)
string cTip = "Bias " + str.tostring(math.round(cBias)) + " + zone side " + str.tostring(math.round(cZone)) + " + nearest block "
+ str.tostring(math.round(cOB)) + " + recent sweep " + str.tostring(math.round(cSw)) + (lean == 1 ? ", read toward the bull side" : lean == -1 ? ", read toward the bear side" : ", no bias yet")
dash.cell(0, D_ROWS - 1, "Confluence", text_color = onFill(blend(DHL, DBG, 60)), text_halign = text.align_left, text_size = dSize,
bgcolor = hlL, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = cTip)
dash.cell(1, D_ROWS - 1, str.tostring(conf) + " / 100", text_color = onFill(blend(DHL, DBG, 30)), text_halign = text.align_right,
text_size = dSize, bgcolor = hlR, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = cTip)