本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © AlgoNorth
//@version=6
indicator("Order Block Holding Power [AlgoNorth]", shorttitle = "O.B.H.P", overlay = true, max_lines_count = 100, max_labels_count = 200, max_polylines_count = 100)
// ─── Inputs ───────────────────────────────────────────────────────────────
const string G_OB = "Order blocks"
const string G_CRV = "Hold curves"
const string G_PNL = "Panel"
pivotLen = input.int(5, "Swing length", minval = 2, maxval = 30, group = G_OB, tooltip = "Bars on each side that confirm the swing high / low. A close through it is a structure break, and the last opposite candle before the break becomes the order block. Blocks form and break only on bar close. A block's age is counted from the structure break, not from the order block candle, so the painted zone starts a few bars before age zero.", display = display.none)
obLookback = input.int(15, "Order block search", minval = 2, maxval = 50, group = G_OB, tooltip = "How many bars back from the structure break to look for the last opposite candle.", display = display.none)
maxShown = input.int(3, "Zones shown per side", minval = 0, maxval = 8, group = G_OB, tooltip = "Live order blocks painted on price: the nearest to price on each side, up to 8 (each zone takes five of Pine's 100 polylines). Every live block still counts in the curves.", display = display.none)
horizon = input.int(150, "Curve horizon (bars)", minval = 30, maxval = 500, group = G_CRV, tooltip = "The oldest age the hold curves cover. The lead, the ratio and the p value are measured only up to this age, so changing it can change the verdict.", display = display.none)
curveW = input.int(70, "Curve width (bars)", minval = 30, maxval = 200, group = G_CRV, tooltip = "Width of the curve chart, drawn to the right of the last bar. Each curve has one point per bar column across it. The chart needs room there: set the chart's right margin to about Space before curve + Curve width + 15 bars (about 115 at the defaults).", display = display.none)
curveGap = input.int(28, "Space before curve (bars)", minval = 3, maxval = 60, group = G_CRV, tooltip = "Gap between the right end of the zones and the start of the curve chart. Together with the curve width it sets how much right margin the chart needs.", display = display.none)
smoothBars = input.float(8.0, "Curve smoothing (bars)", minval = 1.0, maxval = 30.0, step = 1.0, group = G_CRV, tooltip = "Width of the smoothing applied along age, in bars. It narrows near age 0, where blocks break fastest, so the curve and the numbers read off it (zone percentages, medians, hold odds) stay close to the raw hold rate. Higher = rounder curves.", display = display.none)
showBand = input.bool(false, "Confidence band", group = G_CRV, tooltip = "Off by default: the painted curves already show the gap. On: a 95% band at each age around the leading side's curve, shown once each side has 5 breaks inside the horizon; Greenwood's band widened for blocks that live through the same price moves.", display = display.none)
linkZones = input.bool(true, "Link zones to curve", group = G_CRV, tooltip = "Each zone drawn on price gets a numbered circle and the share of blocks that reach its age, or at most the curve's end value (≤) with the block's age in brackets once it has outlived the curve. The same numbered circle sits on its side's curve at the zone's age.", display = display.none)
showPanel = input.bool(true, "Show panel", group = G_PNL, tooltip = "The nearest bear block above price and bull block below it with their odds of holding, which side's blocks hold longer and whether that gap could be chance, each side's median life and the live block count. Every count is taken on closed bars only.", display = display.none)
panelPos = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_PNL, tooltip = "Corner of the chart the panel sits in. Top left shares its corner with TradingView's own chart legend.", display = display.none)
panelTxt = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = G_PNL, tooltip = "Size of the panel text.", display = display.none)
holdWin = input.int(20, "Hold window (bars)", minval = 1, maxval = 200, group = G_PNL, tooltip = "The panel's odds that the nearest support and resistance blocks hold this many more bars, given how long each has already held. Odds are given while the block's age plus this window stays inside the curve horizon.", display = display.none)
// ─── Constants ────────────────────────────────────────────────────────────
const color UP_COL = #00E676
const color DN_COL = #FF1744
const color MUTED_COL = #9598A1
const color NUM_COL = #131722
const int ZONE_END = 7 // bars past the live bar where the zones end
const int MAX_LIVE = 60 // live blocks tracked per side; the oldest past this stops being tracked
const int PAST_MAX = 4990 // furthest back a zone starts: inside the 5,000 bars of bar times reserved below
const int MIN_EV = 5 // breaks per side before the lead is tested and painted
const float SIG_P = 0.05 // p value below which the lead is read as unlikely to be chance
fg = chart.fg_color
// a zone drawn far back needs the bar times that far back; without this Pine keeps fewer, and zooming out stopped the
// indicator with a historical-buffer error
max_bars_back(time, 5000)
// text colours that stay readable on the chart's background: the signature colours on a dark chart, deeper shades of the
// same hues on a light one, and the chart's own text colour wherever neither reaches a 3:1 contrast (a mid-grey
// background); fills, circles and curves keep the signature colours either way
chan(float v) =>
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))
ink(color c) =>
a = lum(c)
b = lum(chart.bg_color)
(math.max(a, b) + 0.05) / (math.min(a, b) + 0.05) >= 3.0 ? c : fg
light = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
upTxt = ink(light ? #007A36 : UP_COL)
dnTxt = ink(light ? #D3002D : DN_COL)
mutedTxt = ink(light ? #6A6D78 : MUTED_COL)
// ─── Types ────────────────────────────────────────────────────────────────
type OB
float top
float bot
int side // 1 = bull, -1 = bear
int bornBar // bar of the structure break that created it
int obBar // bar of the order block candle
// one block's life for the curves: the bar of the break that created it, its age when it broke, was dropped or (still
// live) has held to now, and whether it broke
type Life
int born
int age
bool broke
// ─── State ────────────────────────────────────────────────────────────────
var array<OB> bulls = array.new<OB>()
var array<OB> bears = array.new<OB>()
var array<Life> bullLives = array.new<Life>()
var array<Life> bearLives = array.new<Life>()
var array<polyline> polys = array.new<polyline>()
var array<line> lns = array.new<line>()
var array<label> lbls = array.new<label>()
var float lastPH = na
var float lastPL = na
var bool phLive = false
var bool plLive = false
var float visHi = na
var float visLo = na
var int visBars = 0
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
// the visible bars: their price range sets the curve chart's height, their count sets how far the circles sit inside the
// zones and where a zone born before the visible range starts
if time >= chart.left_visible_bar_time
visBars += 1
visHi := na(visHi) ? high : math.max(visHi, high)
visLo := na(visLo) ? low : math.min(visLo, low)
// ─── Helpers ──────────────────────────────────────────────────────────────
// age a block has held through closed bars: on a bar still forming, this bar's close check has not happened yet
heldAge(OB o) =>
bar_index - o.bornBar - (barstate.isconfirmed ? 0 : 1)
breakCheck(array<OB> obs, array<Life> lives) =>
if obs.size() > 0
for i = obs.size() - 1 to 0
ob = obs.get(i)
if ob.side == 1 ? close < ob.bot : close > ob.top
lives.push(Life.new(ob.bornBar, bar_index - ob.bornBar, true))
obs.remove(i)
addOB(array<OB> obs, array<Life> lives, int side, float top, float bot, int obX) =>
bool dup = false
for o in obs
if o.obBar == obX
dup := true
break
if not dup
obs.push(OB.new(top, bot, side, bar_index, obX))
if obs.size() > MAX_LIVE
old = obs.shift()
lives.push(Life.new(old.bornBar, bar_index - old.bornBar, false))
// distance from price to a block: 0 when price is inside it
obDist(OB o) =>
close > o.top ? close - o.top : close < o.bot ? o.bot - close : 0.0
// every block's life so far: the ones no longer tracked as recorded, the live ones censored at the age they have held
lifeTable(array<Life> lives, array<OB> obs) =>
array<Life> out = lives.copy()
for o in obs
out.push(Life.new(o.bornBar, heldAge(o), false))
out
// Kaplan–Meier survival, breaks and number still at risk by age; a block that broke after the horizon counts as having
// outlived it
km(array<Life> lf) =>
ev = array.new<int>(horizon + 1, 0)
cnt = array.new<int>(horizon + 2, 0)
for b in lf
k = math.min(b.age, horizon + 1)
cnt.set(k, cnt.get(k) + 1)
if b.broke and b.age <= horizon
ev.set(k, ev.get(k) + 1)
risk = array.new<int>(horizon + 1, 0)
int acc = cnt.get(horizon + 1)
for t = horizon to 1
acc += cnt.get(t)
risk.set(t, acc)
s = array.new<float>(horizon + 1, 1.0)
float sv = 1.0
for t = 1 to horizon
d = ev.get(t)
if d > 0
sv *= 1.0 - float(d) / risk.get(t)
s.set(t, sv)
[s, ev, risk]
// Greenwood variance of the curve by age, needed only for the band
greenwood(array<float> s, array<int> ev, array<int> risk) =>
array<float> g = array.new<float>(horizon + 1, 0.0)
float gw = 0.0
for t = 1 to horizon
n = risk.get(t)
d = ev.get(t)
if n > d
gw += float(d) / (n * (n - d))
g.set(t, s.get(t) * s.get(t) * gw)
g
// each block's pull on its side's mean life (its influence): bk = the pull of a break at that age, sv = the pull of
// every age survived up to it
lifeInfluence(array<float> s, array<int> ev, array<int> risk) =>
array<float> area = array.new<float>(horizon + 2, 0.0)
for t = horizon to 1
area.set(t, area.get(t + 1) + s.get(t))
array<float> bk = array.new<float>(horizon + 1, 0.0)
array<float> sv = array.new<float>(horizon + 1, 0.0)
for t = 1 to horizon
n = risk.get(t)
h = n > 0 ? float(ev.get(t)) / n : 0.0
if n > 0 and h < 1.0
bk.set(t, area.get(t) / ((1.0 - h) * n))
sv.set(t, sv.get(t - 1) + bk.get(t) * h)
[bk, sv]
// spread of summed influences once blocks are grouped by stretch of price: [variance, number of groups]
clusterVar(array<float> cl) =>
float sq = 0.0
int g = 0
for v in cl
if v != 0.0
sq += v * v
g += 1
[g > 1 ? sq * g / (g - 1) : na, g]
// one block's pull on its side's mean life: every age it survived, minus its break if it broke inside the horizon
blockPsi(Life b, array<float> bk, array<float> sv) =>
a = math.min(b.age, horizon)
sv.get(a) - (b.broke and b.age <= horizon ? bk.get(a) : 0.0)
// blocks born in the same stretch of 2 × horizon bars live through the same price moves, so they form one group
groupOf(Life b) =>
int(b.born / (2 * horizon))
// adds one side's block pulls into the grouped gap (sign +1 bull, -1 bear)
groupGap(array<Life> lf, array<float> bk, array<float> sv, array<float> clGap, float sign) =>
for b in lf
idx = groupOf(b)
clGap.set(idx, clGap.get(idx) + sign * blockPsi(b, bk, sv))
// the band's widening factor for one side, needed only for the band: its grouped spread over its ungrouped spread,
// at least 1
bandWiden(array<Life> lf, array<float> bk, array<float> sv, int groups) =>
array<float> cl = array.new<float>(groups, 0.0)
float sq = 0.0
for b in lf
psi = blockPsi(b, bk, sv)
idx = groupOf(b)
cl.set(idx, cl.get(idx) + psi)
sq += psi * psi
[vC, gC] = clusterVar(cl)
gC > 1 ? math.max(1.0, vC / sq) : 1.0
// is the lead real: the gap in mean life over its grouped spread, read as a t with (groups - 1) degrees of freedom.
// Returns the exact two-sided p value from the t distribution's finite series for whole-number degrees of freedom
// (even and odd forms), na when there are too few groups to test
leadP(float gap, float v, int g) =>
float p = na
if g > 2
nu = g - 1
th = math.atan(math.abs(gap) / math.sqrt(v * nu)) // t = gap / sqrt(v), angle atan(|t| / sqrt(nu))
c2 = math.pow(math.cos(th), 2)
float term = 1.0
float acc = 1.0
int k = 1
if nu % 2 == 0
while 2 * k < nu
term *= c2 * (2.0 * k - 1.0) / (2.0 * k)
acc += term
k += 1
p := 1.0 - math.sin(th) * acc
else
while 2 * k + 3 <= nu
term *= c2 * (2.0 * k) / (2.0 * k + 1.0)
acc += term
k += 1
p := 1.0 - 2.0 / math.pi * (th + math.sin(th) * math.cos(th) * acc)
p := math.max(0.0, p)
p
// band edge by age: survival ± z standard errors, clipped to 0–100%
bound(array<float> s, array<float> g, float z) =>
array<float> out = array.new<float>(horizon + 1, 1.0)
for t = 1 to horizon
out.set(t, math.max(0.0, math.min(1.0, s.get(t) + z * math.sqrt(g.get(t)))))
out
// least-squares fit that never falls (pool adjacent violators): any run that drops is replaced by its average
rising(array<float> y) =>
array<float> vals = array.new<float>()
array<int> lens = array.new<int>()
for v in y
vals.push(v)
lens.push(1)
while vals.size() > 1
n = vals.size()
if vals.get(n - 2) <= vals.get(n - 1)
break
v2 = vals.pop()
l2 = lens.pop()
l1 = lens.get(n - 2)
vals.set(n - 2, (vals.get(n - 2) * l1 + v2 * l2) / (l1 + l2))
lens.set(n - 2, l1 + l2)
array<float> out = array.new<float>()
for [i, v] in vals
for k = 1 to lens.get(i)
out.push(v)
out
// the drawn curve: the raw hold rate's slope fitted so it only eases off with age (no kink can form), then that slope
// smoothed with a width that shrinks near age 0, where blocks break fastest, so the curve and every number read off it
// stay on the raw hold rate there instead of being rounded upward; the start (100%) and the end value are kept exactly
convexKM(array<float> s) =>
array<float> d = array.new<float>()
for t = 1 to horizon
d.push(s.get(t) - s.get(t - 1))
d := rising(d)
array<float> e = array.new<float>(horizon, 0.0)
for t = 0 to horizon - 1
sg = math.max(0.5, math.min(smoothBars, (t + 1) / 3.0))
r = int(math.ceil(3.0 * sg))
float acc = 0.0
float wsum = 0.0
for j = -r to r
w = math.exp(-0.5 * j * j / (sg * sg))
acc += w * d.get(math.max(0, math.min(horizon - 1, t + j)))
wsum += w
e.set(t, acc / wsum)
e := rising(e)
float k = e.sum() != 0.0 ? d.sum() / e.sum() : 0.0
array<float> out = array.new<float>(horizon + 1, 1.0)
float lvl = 1.0
for t = 1 to horizon
lvl += k * e.get(t - 1)
out.set(t, math.max(0.0, lvl)) // float rounding at a fully broken tail would otherwise print -0%
out
// one exact value per bar column across the curve chart
sampleCols(array<float> sm) =>
array<float> c = array.new<float>(curveW + 1, 1.0)
for k = 0 to curveW
a = float(k) * horizon / curveW
i0 = int(math.floor(a))
i1 = math.min(i0 + 1, horizon)
f = a - i0
c.set(k, sm.get(i0) * (1.0 - f) + sm.get(i1) * f)
c
colOf(int age) =>
int(math.round(float(age) * curveW / horizon))
barsTxt(int n) =>
str.tostring(n) + (n == 1 ? " bar" : " bars")
// a zone's label: the curve's value at the zone's exact age (share of blocks that reach that age), read off the full
// curve rather than the column its circle sits on, so a narrow chart never rounds a young block up to 100%; a block older
// than the curve gets the curve's end value as a ceiling, since no more blocks reach its age than reach the end, with its
// own age in brackets
oddsPct(array<float> sm, int age) =>
age > horizon ? "≤" + str.tostring(100.0 * sm.get(horizon), "#") + "% (" + str.tostring(age) + " bars)" : str.tostring(100.0 * sm.get(age), "#") + "%"
// odds a live block holds holdWin more bars given it has held `age` bars: curve at age + holdWin over curve at age
holdOdds(array<float> sm, int age) =>
string out = "—"
if age > horizon
out := "outlived " + str.tostring(horizon) + " bars"
else if age + holdWin > horizon
out := "window runs past the " + str.tostring(horizon) + "-bar horizon · " + barsTxt(age) + " old"
else if sm.get(age) > 0
out := str.tostring(100.0 * sm.get(age + holdWin) / sm.get(age), "#") + "% · " + barsTxt(age) + " old"
out
medianAge(array<float> sm) =>
int m = na
for t = 1 to horizon
if sm.get(t) <= 0.5
m := t
break
m
drawCurve(array<float> c, int x0, float yBot, float span, color col) =>
array<chart.point> pts = array.new<chart.point>()
for k = 0 to curveW
pts.push(chart.point.from_index(x0 + k, yBot + c.get(k) * span))
polys.push(polyline.new(pts, curved = true, line_color = col, line_width = 3))
// drawn straight: one point per column is already smooth, and a curved closed shape overshoots at its right-end turn
drawBand(array<float> cu, array<float> cl, int x0, float yBot, float span, color col) =>
array<chart.point> pts = array.new<chart.point>()
for k = 0 to curveW
pts.push(chart.point.from_index(x0 + k, yBot + cu.get(k) * span))
for k = curveW to 0
pts.push(chart.point.from_index(x0 + k, yBot + cl.get(k) * span))
polys.push(polyline.new(pts, closed = true, line_color = color.new(col, 100), fill_color = color.new(col, 82)))
// the painted hold curves: the trailing side's curve filled down to 0% (lagOn) and the leader's lead over it filled up to
// the leading curve (leadOn), each in four strips of its own colour, most see-through at the bottom of each. Every strip
// is its own shape, so no shade stacks on another. Where the leader dips under the trailing curve, its strips close to
// nothing
paintHero(array<float> lag, array<float> lead, int x0, float yBot, float span, color lagCol, color leadCol, bool lagOn, bool leadOn) =>
lagT = array.from(84, 76, 67, 58)
leadT = array.from(81, 72, 61, 50)
for j = 0 to 3
ka = j / 4.0
kb = (j + 1) / 4.0
if lagOn
array<chart.point> a = array.new<chart.point>()
for k = 0 to curveW
a.push(chart.point.from_index(x0 + k, yBot + kb * lag.get(k) * span))
for k = curveW to 0
a.push(chart.point.from_index(x0 + k, yBot + ka * lag.get(k) * span))
polys.push(polyline.new(a, false, true, line_color = na, fill_color = color.new(lagCol, lagT.get(j))))
if leadOn
array<chart.point> b = array.new<chart.point>()
for k = 0 to curveW
b.push(chart.point.from_index(x0 + k, yBot + (lag.get(k) + kb * math.max(0.0, lead.get(k) - lag.get(k))) * span))
for k = curveW to 0
b.push(chart.point.from_index(x0 + k, yBot + (lag.get(k) + ka * math.max(0.0, lead.get(k) - lag.get(k))) * span))
polys.push(polyline.new(b, false, true, line_color = na, fill_color = color.new(leadCol, leadT.get(j))))
// one layer of a painted zone: a closed outline whose left end is a rounded nose (half an ellipse over `nose` bars)
// and whose right end is square at the zone's end. Straight segments: the nose is already smooth bar to bar
zoneLayer(int xa, int xb, int nose, float mid, float a, color c) =>
if xb - xa >= 2
r = math.min(nose, xb - xa - 1)
array<chart.point> pts = array.new<chart.point>()
pts.push(chart.point.from_index(xa, mid))
for x = xa + 1 to xa + r
u = float(x - xa) / r
pts.push(chart.point.from_index(x, mid + a * math.sqrt(u * (2.0 - u))))
pts.push(chart.point.from_index(xb, mid + a))
pts.push(chart.point.from_index(xb, mid - a))
for x = xa + r to xa + 1
u = float(x - xa) / r
pts.push(chart.point.from_index(x, mid - a * math.sqrt(u * (2.0 - u))))
polys.push(polyline.new(pts, false, true, line_color = na, fill_color = c))
// a drawn zone, painted: five stepped layers in its side's colour, each starting `step` bars after the one outside it
// and thinner toward the middle, then the bright core line through its middle. The layers are see-through and stack,
// so on a dark chart they build up to the deep-to-bright ramp and on a light chart to soft tints of the same colour
paintZone(OB o, int xL, int xR, int step, int nose) =>
col = o.side == 1 ? UP_COL : DN_COL
mid = (o.top + o.bot) / 2
half = (o.top - o.bot) / 2
lt = array.from(81, 89, 85, 82, 74)
for i = 0 to 4
zoneLayer(xL + i * step, xR, nose, mid, half * (1.0 - 0.17 * i), color.new(col, lt.get(i)))
if xL + 5 * step < xR
lns.push(line.new(xL + 5 * step, mid, xR, mid, color = col, width = 2))
// a side's median: dotted line down to the age axis, a small dot in the side's colour where the curve crosses 50%, and
// the age in words beside it, in the chart's text colour so it reads on any paint
drawMedian(array<float> c, int m, int x0, float yBot, float span, color col, string side, string lstyle) =>
if not na(m)
k = colOf(m)
y = yBot + c.get(k) * span
lns.push(line.new(x0 + k, y, x0 + k, yBot, color = color.new(fg, 55), style = line.style_dotted))
lbls.push(label.new(x0 + k, y, "", color = col, style = label.style_circle, size = size.tiny))
lbls.push(label.new(x0 + k, y, side + " median · " + barsTxt(m), color = color.new(#000000, 100), style = lstyle, textcolor = fg, size = 13, text_font_family = font.family_monospace))
// a numbered circle with a thin white ring: a white circle just bigger than the coloured one sits behind it (typographic
// size 11, a touch under size.normal, so the ring is thinner), and Pine's circle label draws no text, so the number is a
// transparent label stacked on top; the default font centres its digits in the label box, so it sits in the middle of the dot
badge(int x, float y, string num, color col) =>
lbls.push(label.new(x, y, "", color = #FFFFFF, style = label.style_circle, size = 11))
lbls.push(label.new(x, y, "", color = col, style = label.style_circle, size = size.small))
lbls.push(label.new(x, y, num, color = color.new(#000000, 100), style = label.style_label_center, textcolor = NUM_COL, size = 17, text_font_family = font.family_default, text_formatting = text.format_bold))
// one side's live blocks ranked nearest to price first; the painted zones and the panel's nearest block both read this
// one ranking, so they always agree, ties included
rankOBs(array<OB> obs) =>
array<float> dist = array.new<float>()
for o in obs
dist.push(obDist(o))
dist.sort_indices(order.ascending)
// the live blocks nearest to price on one side, the ones painted on the chart; the rest stay tracked, undrawn
nearestOBs(array<OB> obs) =>
array<OB> vis = array.new<OB>()
for [k, idx] in rankOBs(obs)
if k >= maxShown
break
vis.push(obs.get(idx))
vis
// drawn zones from top to bottom by price: their position is their badge number
sortZones(array<OB> vis) =>
array<float> mids = array.new<float>()
for o in vis
mids.push((o.top + o.bot) / 2)
rank = mids.sort_indices(order.descending)
array<OB> out = array.new<OB>()
for idx in rank
out.push(vis.get(idx))
out
// each numbered zone: its numbered circle on the core line, `inset` bars in from the zone's right end (in the middle of
// a zone narrower than that, so it never sits off the zone), and its odds just past that end; the same numbered circle
// sits on its curve at the zone's age. Zones at nearly the same price would print their circles and odds on top of each
// other, so within such a stack each circle steps further left, each odds label steps down a label's height and the labels
// carry their zone numbers. Zones past the horizon park in a row starting one slot after the curve's end, so they clear a
// circle sitting at the very end of the curve, spaced wider as more bars are on screen (up to 12 bars) so they stay apart
// at normal zoom. Each side has its own row at its curve's end; when both sides have parked zones and the two curves end
// at nearly the same height, the higher row is lifted clear of the lower one so the circles never sit on top of each other
drawLinks(array<OB> zones, array<float> cB, array<float> cR, array<float> smB, array<float> smR, int x0, float yBot, float span, int rightX, int inset, int zoneFrom) =>
tr = color.new(#000000, 100)
step = math.min(12, 2 * inset)
gap = 0.04 * span // about one label's height: the pane shows roughly one and a half spans with the headroom
int nOldB = 0
int nOldR = 0
for o in zones
if heldAge(o) > horizon
if o.side == 1
nOldB += 1
else
nOldR += 1
float rowB = yBot + cB.get(curveW) * span
float rowR = yBot + cR.get(curveW) * span
if nOldB > 0 and nOldR > 0 and math.abs(rowB - rowR) < 1.5 * gap
if rowB >= rowR
rowB := rowR + 1.5 * gap
else
rowR := rowB + 1.5 * gap
// each odds label's price level and its place in a stack of labels that would overlap (0 = not pushed down)
array<float> ly = array.new<float>()
array<int> stack = array.new<int>()
for [n, o] in zones
mid = (o.top + o.bot) / 2
if n > 0 and ly.get(n - 1) - mid < gap
ly.push(ly.get(n - 1) - gap)
stack.push(stack.get(n - 1) + 1)
else
ly.push(mid)
stack.push(0)
int outB = 0
int outR = 0
for [n, o] in zones
num = str.tostring(n + 1)
bull = o.side == 1
col = bull ? UP_COL : DN_COL
c = bull ? cB : cR
age = heldAge(o)
old = age > horizon
mid = (o.top + o.bot) / 2
si = stack.get(n)
tag = si > 0 or (n + 1 < zones.size() and stack.get(n + 1) > 0) ? "#" + num + " · " : ""
lbls.push(label.new(rightX, ly.get(n), tag + oddsPct(bull ? smB : smR, age), color = tr, style = label.style_label_left, textcolor = bull ? upTxt : dnTxt, size = 14, text_font_family = font.family_monospace, text_formatting = text.format_bold))
xL = math.max(o.obBar, zoneFrom)
xIn = rightX - inset * (1 + 2 * si)
badge(xIn >= xL ? xIn : int((xL + rightX) / 2), mid, num, col)
int x = na
float y = na
if old
x := x0 + curveW + step * (1 + (bull ? outB : outR))
y := bull ? rowB : rowR
if bull
outB += 1
else
outR += 1
else
k = colOf(age)
x := x0 + k
y := yBot + c.get(k) * span
lns.push(line.new(x, y, x, yBot, color = color.new(fg, 50), style = line.style_dotted))
badge(x, y, num, col)
if outB > 0
lbls.push(label.new(x0 + curveW + step * (1 + outB), rowB, str.tostring(horizon) + "+", color = tr, style = label.style_label_left, textcolor = upTxt, size = 12, text_font_family = font.family_monospace))
if outR > 0
lbls.push(label.new(x0 + curveW + step * (1 + outR), rowR, str.tostring(horizon) + "+", color = tr, style = label.style_label_left, textcolor = dnTxt, size = 12, text_font_family = font.family_monospace))
// the live block on one side nearest to price, na when that side has none
nearestOf(array<OB> obs) =>
OB best = na
if obs.size() > 0
best := obs.get(rankOBs(obs).get(0))
best
// a nearest block's panel line: its circle number on the chart, range and distance from price. On closed bars a live bull
// block sits at or below price and a live bear block at or above it, but a bar still forming can poke through one before
// its close decides the break, so whether the block is above or below is read from where price is now
obRowTxt(OB o, array<OB> zones) =>
string out = "none"
if not na(o)
string num = ""
if linkZones
for [n, z] in zones
if z.side == o.side and z.obBar == o.obBar
num := "#" + str.tostring(n + 1) + " · "
break
d = obDist(o)
out := num + str.tostring(o.bot, format.mintick) + " – " + str.tostring(o.top, format.mintick) + " · " + (d == 0 ? "inside" : str.tostring(d, format.mintick) + (close > o.top ? " below" : " above"))
out
// a side's median life for the panel: a dash while the side has no blocks, past the horizon when its curve never
// reaches 50%
medTxt(int m, int n) =>
n == 0 ? "—" : na(m) ? ">" + str.tostring(horizon) : str.tostring(m)
// ─── Blocks: every state change happens on bar close, so nothing repaints ──
if barstate.isconfirmed
if not na(ph)
lastPH := ph
phLive := true
if not na(pl)
lastPL := pl
plLive := true
// breaks first, then new blocks from structure breaks
breakCheck(bulls, bullLives)
breakCheck(bears, bearLives)
int upIdx = na
if phLive and close > lastPH
phLive := false
for i = 1 to obLookback
if close[i] < open[i]
upIdx := i
break
if not na(upIdx)
addOB(bulls, bullLives, 1, high[upIdx], low[upIdx], bar_index - upIdx)
int dnIdx = na
if plLive and close < lastPL
plLive := false
for i = 1 to obLookback
if close[i] > open[i]
dnIdx := i
break
if not na(dnIdx)
addOB(bears, bearLives, -1, high[dnIdx], low[dnIdx], bar_index - dnIdx)
// ─── Headroom: room above the candles for the panel and below for the legend ─
span = nz(visHi - visLo, high - low)
plot(barstate.islast ? visHi + 0.30 * span : na, "Headroom top", color = color.new(#000000, 100), display = display.pane, editable = false)
plot(barstate.islast ? visLo - 0.16 * span : na, "Headroom bottom", color = color.new(#000000, 100), display = display.pane, editable = false)
// ─── Panel: house layout, merged rows made once ───────────────────────────
pos = switch panelPos
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
pSize = panelTxt == "Tiny" ? size.tiny : panelTxt == "Normal" ? size.normal : size.small
var table panel = showPanel ? table.new(pos, 2, 10, bgcolor = chart.bg_color, frame_color = color.new(fg, 70), frame_width = 1, border_color = color.new(fg, 85), border_width = 1) : na
// merged rows: header, settings, last bar
if barstate.isfirst and showPanel
for r = 0 to 9
panel.cell(0, r, "")
panel.cell(1, r, "")
for r in array.from(0, 1, 9)
panel.merge_cells(0, r, 1, r)
rowL(int r, string t, string tip) =>
panel.cell(0, r, t, text_color = fg, text_halign = text.align_left, text_size = pSize, tooltip = tip)
rowR(int r, string t, color c) =>
panel.cell(1, r, t, text_color = c, text_halign = text.align_right, text_size = pSize)
// ─── Zones, curves and panel on the last bar ──────────────────────────────
if barstate.islast
for p in polys
p.delete()
polys.clear()
for l in lns
l.delete()
lns.clear()
for l in lbls
l.delete()
lbls.clear()
lifeB = lifeTable(bullLives, bulls)
lifeR = lifeTable(bearLives, bears)
[sB, eB, rB] = km(lifeB)
[sR, eR, rR] = km(lifeR)
nB = lifeB.size()
nR = lifeR.size()
ready = eB.sum() >= MIN_EV and eR.sum() >= MIN_EV
rmB = sB.sum() - 1.0 // area under each curve = mean bars held within the horizon
rmR = sR.sum() - 1.0
bullLead = rmB >= rmR
leadCol = bullLead ? UP_COL : DN_COL
// is the lead real: the mean-life gap tested with blocks grouped by the stretch of price they lived through;
// the same grouping widens the band
[bkB, svB] = lifeInfluence(sB, eB, rB)
[bkR, svR] = lifeInfluence(sR, eR, rR)
clGap = array.new<float>(int(bar_index / (2 * horizon)) + 1, 0.0)
groupGap(lifeB, bkB, svB, clGap, 1.0)
groupGap(lifeR, bkR, svR, clGap, -1.0)
[vGap, gGap] = clusterVar(clGap)
pVal = leadP(rmB - rmR, vGap, gGap)
real = ready and pVal < SIG_P // a comparison with na is false, so too little history never reads as real
// kink-free smoothed curves, sampled one value per column
smB = convexKM(sB)
smR = convexKM(sR)
cB = sampleCols(smB)
cR = sampleCols(smR)
medB = medianAge(smB)
medR = medianAge(smR)
// geometry, all on bar columns: zones end at rightX, the curve starts curveGap bars after them; a circle is a
// fixed size on screen, so its inset in bars grows as more bars are on screen
rightX = bar_index + ZONE_END
x0 = rightX + curveGap
yBot = visLo
yTop = visHi
inset = math.max(2, int(math.ceil(visBars / 80.0)))
zones = nearestOBs(bulls)
zones.concat(nearestOBs(bears))
zones := sortZones(zones)
// painted zones: each nose sits on its order block candle; the nose and the layer steps widen with zoom, like the
// circles, but a fresh zone too narrow for that keeps steps small enough for all five layers and its core line to fit.
// A zone born before the visible range starts just off screen to the left instead, never before the first loaded bar:
// a filled polyline anchored thousands of bars back or outside the data doesn't render, leaving only the core line
zoneFrom = bar_index - math.min(visBars + 5, PAST_MAX, bar_index)
for o in zones
xL = math.max(o.obBar, zoneFrom)
paintZone(o, xL, rightX, math.max(1, math.min(int(inset / 3), int((rightX - xL - 1) / 5))), inset)
// painted curves: the trailing side filled to 0% and, once each side has enough breaks to call a leader, the leader's
// lead filled above it. A side with no blocks yet has no curve, so nothing of it is drawn
paintHero(bullLead ? cR : cB, bullLead ? cB : cR, x0, yBot, span, bullLead ? DN_COL : UP_COL, leadCol, (bullLead ? nR : nB) > 0, ready)
// grid and axes
for q in array.from(0.25, 0.5, 0.75)
lns.push(line.new(x0, yBot + q * span, x0 + curveW, yBot + q * span, color = color.new(fg, 85), style = line.style_dashed))
lns.push(line.new(x0, yBot, x0, yTop, color = color.new(fg, 70)))
lns.push(line.new(x0, yBot, x0 + curveW, yBot, color = color.new(fg, 70)))
// band, curves, medians, numbered zones
if showBand and ready
sL = bullLead ? sB : sR
gL = greenwood(sL, bullLead ? eB : eR, bullLead ? rB : rR)
zL = 1.96 * math.sqrt(bandWiden(bullLead ? lifeB : lifeR, bullLead ? bkB : bkR, bullLead ? svB : svR, clGap.size()))
drawBand(sampleCols(convexKM(bound(sL, gL, zL))), sampleCols(convexKM(bound(sL, gL, -zL))), x0, yBot, span, leadCol)
if nR > 0
drawCurve(cR, x0, yBot, span, DN_COL)
if nB > 0
drawCurve(cB, x0, yBot, span, UP_COL)
// each median's words go on its own outer side: the earlier median reads to the left, the later one to the right,
// so neither label runs past the other side's dot
bullFirst = not na(medB) and not na(medR) and medB < medR
drawMedian(cB, medB, x0, yBot, span, UP_COL, "bull", bullFirst ? label.style_label_upper_right : label.style_label_lower_left)
drawMedian(cR, medR, x0, yBot, span, DN_COL, "bear", bullFirst ? label.style_label_lower_left : label.style_label_upper_right)
if linkZones
drawLinks(zones, cB, cR, smB, smR, x0, yBot, span, rightX, inset, zoneFrom)
// axis labels, header and legend
tr = color.new(#000000, 100)
lbls.push(label.new(x0 - 1, yTop, "100%", color = tr, style = label.style_label_right, textcolor = mutedTxt, size = 13, text_font_family = font.family_monospace))
lbls.push(label.new(x0 - 1, yBot + 0.5 * span, "50%", color = tr, style = label.style_label_right, textcolor = mutedTxt, size = 13, text_font_family = font.family_monospace))
lbls.push(label.new(x0 - 1, yBot, "0%", color = tr, style = label.style_label_right, textcolor = mutedTxt, size = 13, text_font_family = font.family_monospace))
// a narrow curve chart has room for the first and last age ticks only
for t in (curveW < 50 ? array.from(0, horizon) : array.from(0, int(math.round(horizon / 3.0)), int(math.round(2.0 * horizon / 3.0)), horizon))
lbls.push(label.new(x0 + colOf(t), yBot, t == horizon ? str.tostring(t) + " bars old" : str.tostring(t), color = tr, style = label.style_label_up, textcolor = mutedTxt, size = 13, text_font_family = font.family_monospace))
lbls.push(label.new(x0 - 1, yTop + 0.06 * span, "CHANCE AN ORDER BLOCK IS STILL HOLDING · BY AGE", color = tr, style = label.style_label_left, textcolor = mutedTxt, size = 14, text_font_family = font.family_monospace))
lbls.push(label.new(x0 - 1, yBot - 0.07 * span, "━ bull OBs · n " + str.tostring(nB), color = tr, style = label.style_label_left, textcolor = upTxt, size = 13, text_font_family = font.family_monospace))
lbls.push(label.new(x0 + int(curveW * 0.55), yBot - 0.07 * span, "━ bear OBs · n " + str.tostring(nR), color = tr, style = label.style_label_left, textcolor = dnTxt, size = 13, text_font_family = font.family_monospace))
if linkZones
lbls.push(label.new(x0 - 1, yBot - 0.11 * span, "● each zone's number on price is its circle on the curve", color = tr, style = label.style_label_left, textcolor = fg, size = 13, text_font_family = font.family_monospace))
if showPanel
// nearest resistance (bear block above) and support (bull block below), each with its odds of holding the window
nBear = nearestOf(bears)
nBull = nearestOf(bulls)
bearCol = na(nBear) ? mutedTxt : dnTxt
bullCol = na(nBull) ? mutedTxt : upTxt
holdLbl = "Holds next " + barsTxt(holdWin)
holdTip = "Chance the block in the row above lasts this many more bars, given how long it has already held: its side's curve at its age plus the hold window, over the curve at its age."
ratio = bullLead ? (rmR > 0 ? rmB / rmR : na) : (rmB > 0 ? rmR / rmB : na)
// name bar, settings, nearest levels, lead, median life, live blocks, last bar
// cut, not rounded, and to four places near the 0.05 line, so the printed p value never contradicts the call
pTxt = pVal < 0.001 ? "p < 0.001" : pVal < 0.06 ? "p " + str.tostring(math.floor(pVal * 10000) / 10000.0, "0.0000") : "p " + str.tostring(math.floor(pVal * 1000) / 1000.0, "0.000")
lead = bullLead ? "bull" : "bear"
xTxt = na(ratio) ? "longer" : "×" + str.tostring(ratio, "0.00") + " as long"
statCol = real ? leadCol : MUTED_COL // name bar fill
leadTxt = not ready ? "collecting · needs " + str.tostring(MIN_EV) + " breaks each side" : na(pVal) ? lead + " " + xTxt + " · too little history to test" : real ? lead + " " + xTxt + " · unlikely to be chance (" + pTxt + ")" : lead + " " + xTxt + " · could be chance (" + pTxt + ")"
leadInk = real ? (bullLead ? upTxt : dnTxt) : fg
leadTip = "How much longer the leading side's blocks hold on average inside the curve horizon (the area under its curve over the other's, as a multiple), and whether that gap could be chance. Blocks that lived through the same stretch of price are tested as one group; below p 0.05 the gap is read as unlikely to be chance. Shown once each side has " + str.tostring(MIN_EV) + " breaks inside the horizon."
panel.cell(0, 0, "Order Block Holding Power [AlgoNorth] · hold curves", bgcolor = statCol, text_color = #000000, text_halign = text.align_left, text_size = pSize, text_formatting = text.format_bold)
panel.cell(0, 1, str.format("swing {0} · search {1} · horizon {2} · smoothing {3,number,#} · hold window {4}", pivotLen, obLookback, horizon, smoothBars, holdWin), text_color = fg, text_halign = text.align_left, text_size = pSize)
rowL(2, "Resistance (bear)", "The live bear block nearest above price: its number on the chart, range and distance from price.")
rowR(2, obRowTxt(nBear, zones), bearCol)
rowL(3, holdLbl, holdTip)
rowR(3, na(nBear) ? "—" : holdOdds(smR, heldAge(nBear)), bearCol)
rowL(4, "Support (bull)", "The live bull block nearest below price: its number on the chart, range and distance from price.")
rowR(4, obRowTxt(nBull, zones), bullCol)
rowL(5, holdLbl, holdTip)
rowR(5, na(nBull) ? "—" : holdOdds(smB, heldAge(nBull)), bullCol)
rowL(6, "Lead", leadTip)
rowR(6, leadTxt, leadInk)
rowL(7, "Median life (bars)", "Age by which half of each side's blocks have been closed through, live ones included.")
rowR(7, medTxt(medB, nB) + " bull · " + medTxt(medR, nR) + " bear", fg)
rowL(8, "Live OBs", "Blocks not yet closed through on each side, up to 60 tracked per side. Every one counts in the curves; the nearest on each side are drawn.")
rowR(8, str.format("{0} bull · {1} bear", bulls.size(), bears.size()), fg)
panel.cell(0, 9, "Last bar " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) + " exchange time · " + str.tostring(bar_index + 1) + " bars", text_color = fg, text_halign = text.align_left, text_size = pSize)