本页源码来自 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("FVG Holding Power [JOAT]", shorttitle = "FVG.HP [JOAT]", overlay = true, max_lines_count = 100, max_labels_count = 200, max_polylines_count = 100)
// ─── Inputs ───────────────────────────────────────────────────────────────
const string G_FVG = "Fair value gaps"
const string G_CRV = "Hold curves"
const string G_PNL = "Panel"
const string G_COL = "Colours"
minSize = input.float(0.25, "Minimum gap size (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = G_FVG, tooltip = "Smallest gap kept, as a multiple of ATR(14) on the bar the gap forms. Bull gap: a candle's low above the high two candles back (the gap runs from that high to this low). Bear gap: a candle's high under the low two candles back (from this high to that low). Gaps form on closed bars only.", display = display.none)
useDisp = input.bool(true, "Displacement filter", group = G_FVG, tooltip = "On: the middle candle of the three needs a body of at least the size below, in the gap's direction (an up candle for a bull gap, a down candle for a bear gap). Off: every gap of the minimum size counts.", display = display.none)
dispMult = input.float(0.6, "Displacement body (ATR)", minval = 0.1, maxval = 5.0, step = 0.1, group = G_FVG, tooltip = "Smallest middle-candle body, as a multiple of ATR(14), while the displacement filter is on.", display = display.none)
maxShown = input.int(3, "Gaps shown per side", minval = 0, maxval = 8, group = G_FVG, tooltip = "Live gaps painted on price: the nearest to price on each side, up to 8 (each tube takes five of Pine's 100 polylines). Every live gap still counts in the curves. Gaps that have been closed through are not drawn.", display = display.none)
drawWithin = input.float(8.0, "Draw within (ATR)", minval = 1.0, maxval = 50.0, step = 0.5, group = G_FVG, tooltip = "Only gaps within this many ATR(14) of the close are painted on price, so a gap far away never squashes the candles. Every gap still counts in the curves and the panel.", display = display.none)
showCE = input.bool(true, "CE line", group = G_FVG, tooltip = "A thin dotted line through each drawn gap at its consequent encroachment (CE), the middle of the gap.", display = display.none)
ceWin = input.int(20, "CE respect window (bars)", minval = 1, maxval = 200, group = G_FVG, tooltip = "CE respect counts a gap once price first touches its CE (a low at or under a bull gap's CE, a high at or over a bear gap's). It held if no candle closed through the gap's far side within this many bars after that touch, it failed if one did; a close through on the touching candle itself counts as failed. Gaps dropped from tracking before the window ends are left out.", display = display.none)
horizon = input.int(100, "Curve horizon (bars)", minval = 30, maxval = 500, group = G_CRV, tooltip = "The oldest age the hold curves cover, in bars from the gap's third candle. Most gaps that get closed through go early, so a short horizon spreads that early drop across the chart; a longer one shows more of the tail. The lead test behind the panel header's colour is measured only up to this age, so changing it can change that colour.", 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 + 40 bars (about 145 at the defaults).", display = display.none)
curveGap = input.int(36, "Space before curve (bars)", minval = 3, maxval = 60, group = G_CRV, tooltip = "Gap between the right end of the tubes and the start of the curve chart. Together with the curve width it sets how much right margin the chart needs (about Space before curve + Curve width + 15 bars).", 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 gaps break fastest, so the curve and the numbers read off it (tube 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 difference. 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 gaps that live through the same price moves.", display = display.none)
linkZones = input.bool(true, "Link gaps to curve", group = G_CRV, tooltip = "Each gap drawn on price gets a numbered badge and the share of its side's gaps that lived to its age, or at most the curve's end value (≤) with the gap's age in brackets once it has outlived the curve. The same numbered badge sits on its side's curve at the gap's age.", display = display.none)
showPanel = input.bool(true, "Show panel", group = G_PNL, tooltip = "The nearest bear gap above price and bull gap below it with their odds of holding the next window, CE respect per side, each side's median life and the live gap 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 = ["Small", "Normal", "Large"], group = G_PNL, tooltip = "Size of the panel text. Small suits most screens; Normal or Large for phones and tablets.", 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 gaps hold this many more bars, given how long each has already held. Odds are given while the gap's age plus this window stays inside the curve horizon.", display = display.none)
preset = input.string("Classic", "Palette", options = ["Classic", "Teal / Purple", "Blue / Orange", "Mono", "Custom"], group = G_COL, tooltip = "Classic = green bull gaps, red bear gaps. Teal / Purple, Blue / Orange and Mono (black and white) are alternates; Custom uses the two colours below. On a light chart the text switches to deeper shades of the same colours.", display = display.none)
bullIn = input.color(#00E676, "Custom bull colour", group = G_COL, tooltip = "Bull gap colour while Palette = Custom.", display = display.none)
bearIn = input.color(#FF1744, "Custom bear colour", group = G_COL, tooltip = "Bear gap colour while Palette = Custom.", display = display.none)
ceIn = input.color(#FFFFFF, "CE line colour", group = G_COL, tooltip = "Colour of the dotted CE line. Where it would not read on the chart background, the chart's text colour is used instead.", display = display.none)
// ─── Constants ────────────────────────────────────────────────────────────
const color MUTED_COL = #9598A1
const color NUM_COL = #131722
const int ZONE_END = 7 // bars past the live bar where the tubes end
const int MAX_LIVE = 60 // live gaps tracked per side; the oldest past this is dropped and recorded as censored
const int PAST_MAX = 4990 // furthest back a tube starts: inside the 5,000 bars of bar times reserved below
const int AHEAD_MAX = 490 // furthest ahead anything is drawn
const int MIN_EV = 5 // breaks per side before the lead is tested
const float SIG_P = 0.05 // p value below which the lead is read as unlikely to be chance
const int ATR_LEN = 14
fg = chart.fg_color
// a tube drawn far back needs the bar times that far back; without this Pine keeps fewer and zooming out can stop the
// script with a historical-buffer error
max_bars_back(time, 5000)
// ─── Colours ──────────────────────────────────────────────────────────────
// text colours that stay readable on the chart's background: the palette 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; fills, badges and curves keep
// the palette 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
shade(color c) =>
color.rgb(color.r(c) * 0.62, color.g(c) * 0.62, color.b(c) * 0.62)
// dark digits on a bright fill, white digits on a deep one (blue, purple, a dark Mono fill)
onFill(color c) =>
lum(c) > 0.18 ? NUM_COL : #FFFFFF
light = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
upCol = preset == "Teal / Purple" ? #00BFA5 : preset == "Blue / Orange" ? #2962FF : preset == "Mono" ? (light ? #2A2E39 : #E0E3EB) : preset == "Custom" ? bullIn : #00E676
dnCol = preset == "Teal / Purple" ? #AA00FF : preset == "Blue / Orange" ? #FF6D00 : preset == "Mono" ? #787B86 : preset == "Custom" ? bearIn : #FF1744
upTxt = ink(light ? shade(upCol) : upCol)
dnTxt = ink(light ? shade(dnCol) : dnCol)
mutedTxt = ink(light ? #6A6D78 : MUTED_COL)
ceCol = ink(ceIn)
// ─── Types ────────────────────────────────────────────────────────────────
type FVG
float top
float bot
int side // 1 = bull, -1 = bear
int bornBar // the gap's third candle: age 0
int midBar // the gap's middle candle: where the tube's nose sits
int bornTime
bool ceHit = false // price has touched the CE
int ceBar = na // bar of that first touch
bool ceDone = false // the CE window has been decided (held or failed)
// one gap's life for the curves: the bar it formed on, 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<FVG> bulls = array.new<FVG>()
var array<FVG> bears = array.new<FVG>()
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 int ceTryB = 0 // touched gaps whose CE window is decided, per side
var int ceHeldB = 0 // ... of which held
var int ceTryR = 0
var int ceHeldR = 0
var float visHi = na
var float visLo = na
var int visBars = 0
// gaps on the bar that just closed: the middle candle is [1], the outer candles [2] and [0]
atrV = ta.atr(ATR_LEN)
body1 = math.abs(close[1] - open[1])
bullGap = low > high[2] and low - high[2] >= minSize * atrV and (not useDisp or (close[1] > open[1] and body1 >= dispMult * atrV))
bearGap = high < low[2] and low[2] - high >= minSize * atrV and (not useDisp or (close[1] < open[1] and body1 >= dispMult * atrV))
// the visible bars: their price range sets the curve chart's height, their count sets how far the badges sit inside the
// tubes and where a gap born before the visible range starts its tube
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 gap has held through closed bars: on a bar still forming, this bar's close check has not happened yet
heldAge(FVG g) =>
bar_index - g.bornBar - (barstate.isconfirmed ? 0 : 1)
// one closed bar for one side's live gaps: the first CE touch, then a close through the far side (a break, recorded
// with its age), then the CE window. Returns the CE windows decided on this bar and how many of them held
stepGaps(array<FVG> gs, array<Life> lives) =>
int tried = 0
int held = 0
if gs.size() > 0
for i = gs.size() - 1 to 0
g = gs.get(i)
bull = g.side == 1
ce = (g.top + g.bot) / 2
if not g.ceHit and (bull ? low <= ce : high >= ce)
g.ceHit := true
g.ceBar := bar_index
if bull ? close < g.bot : close > g.top
lives.push(Life.new(g.bornBar, bar_index - g.bornBar, true))
if g.ceHit and not g.ceDone
tried += 1
gs.remove(i)
else if g.ceHit and not g.ceDone and bar_index - g.ceBar >= ceWin
g.ceDone := true
tried += 1
held += 1
[tried, held]
// a new gap; past MAX_LIVE the oldest stops being tracked and is recorded as censored at the age it reached
addGap(array<FVG> gs, array<Life> lives, int side, float top, float bot) =>
gs.push(FVG.new(top, bot, side, bar_index, bar_index - 1, time))
if gs.size() > MAX_LIVE
old = gs.shift()
lives.push(Life.new(old.bornBar, bar_index - old.bornBar, false))
// distance from price to a gap: 0 when price is inside it
gapDist(FVG g) =>
close > g.top ? close - g.top : close < g.bot ? g.bot - close : 0.0
// every gap'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<FVG> gs) =>
array<Life> out = lives.copy()
for g in gs
out.push(Life.new(g.bornBar, heldAge(g), false))
out
// Kaplan–Meier survival, breaks and number still at risk by age; a gap 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 gap'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 gaps 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 gap's pull on its side's mean life: every age it survived, minus its break if it broke inside the horizon
lifePsi(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)
// gaps 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 gap pulls into the grouped difference (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 * lifePsi(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 = lifePsi(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 difference 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 diff, float v, int g) =>
float p = na
if g > 2
nu = g - 1
th = math.atan(math.abs(diff) / math.sqrt(v * nu)) // t = diff / 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 gaps 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 gap's tag: the curve's value at the gap's exact age (the share of its side's gaps that reach that age), read off the
// full curve rather than the column its badge sits on, so a narrow chart never rounds a young gap up to 100%; a gap older
// than the curve gets the curve's end value as a ceiling, 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 gap 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 tube: a closed outline whose left end is a rounded nose (half an ellipse over `nose` bars) and whose
// right end is square at the tube'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.max(1, 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 gap, painted: five stepped layers in its side's colour over the gap's real top and bottom, each starting `step`
// bars after the one outside it and thinner toward the middle, then the bright core line, then the thin dotted CE line
// over the whole length from the nose. 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(FVG g, int xL, int xR, int step, int nose) =>
col = g.side == 1 ? upCol : dnCol
mid = (g.top + g.bot) / 2
half = math.max((g.top - g.bot) / 2, syminfo.mintick)
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))
if showCE and xR > xL
lns.push(line.new(xL, mid, xR, mid, color = ceCol, width = 1, style = line.style_dotted))
// 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 = 8))
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 badge with a thin white ring: a white circle just bigger than the coloured one sits behind it, and the
// number is a transparent label stacked on top; the default font centres its digits in the label box
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 = onFill(col), size = 17, text_font_family = font.family_default, text_formatting = text.format_bold))
float atrDraw = ta.atr(14)
// one side's live gaps ranked nearest to price first; the painted tubes and the panel's nearest gap both read this one
// ranking, so they always agree, ties included
rankGaps(array<FVG> gs) =>
array<float> dist = array.new<float>()
for g in gs
dist.push(gapDist(g))
dist.sort_indices(order.ascending)
// the live gaps nearest to price on one side, the ones painted on the chart; the rest stay tracked, undrawn
nearestGaps(array<FVG> gs) =>
array<FVG> vis = array.new<FVG>()
for [k, idx] in rankGaps(gs)
if k >= maxShown
break
g = gs.get(idx)
if gapDist(g) <= drawWithin * nz(atrDraw, high - low)
vis.push(g)
vis
// drawn gaps from top to bottom by price: their position is their badge number
sortZones(array<FVG> vis) =>
array<float> mids = array.new<float>()
for g in vis
mids.push((g.top + g.bot) / 2)
rank = mids.sort_indices(order.descending)
array<FVG> out = array.new<FVG>()
for idx in rank
out.push(vis.get(idx))
out
// each numbered gap: its badge on the core line, `inset` bars in from the tube's right end (in the middle of a tube
// narrower than that, so it never sits off the tube), and its odds just past that end; the same badge sits on its curve
// at the gap's age. Gaps at nearly the same price would print their badges and odds on top of each other, so within such
// a stack each badge steps further left, each odds tag steps down a tag's height and the tags carry their gap numbers.
// Gaps past the horizon park in a row starting one slot after the curve's end, spaced wider as more bars are on screen
// (up to 12 bars). Each side has its own row at its curve's end; when both sides have parked gaps and the two curves end
// at nearly the same height, the higher row is lifted clear of the lower one. Furthest x: 7 + 60 + 200 + 12 × 9 = 375
// bars ahead at the input maxima, and clamped to AHEAD_MAX regardless
drawLinks(array<FVG> 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)
// one tag's height, taken from the price span the pane actually shows: the headroom plots plus every drawn tube
float dTop = yBot + 1.40 * span
float dBot = yBot - 0.31 * span
for g in zones
dTop := math.max(dTop, g.top)
dBot := math.min(dBot, g.bot)
rowH = 0.045 * (dTop - dBot)
xMax = bar_index + AHEAD_MAX
int nOldB = 0
int nOldR = 0
for g in zones
if heldAge(g) > horizon
if g.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 * rowH
if rowB >= rowR
rowB := rowR + 1.5 * rowH
else
rowR := rowB + 1.5 * rowH
// each odds tag's price level and its place in a stack of tags that would overlap (0 = not pushed down)
array<float> ly = array.new<float>()
array<int> stack = array.new<int>()
for [n, g] in zones
mid = (g.top + g.bot) / 2
if n > 0 and ly.get(n - 1) - mid < rowH
ly.push(ly.get(n - 1) - rowH)
stack.push(stack.get(n - 1) + 1)
else
ly.push(mid)
stack.push(0)
int outB = 0
int outR = 0
for [n, g] in zones
num = str.tostring(n + 1)
bull = g.side == 1
col = bull ? upCol : dnCol
c = bull ? cB : cR
age = heldAge(g)
old = age > horizon
mid = (g.top + g.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(g.midBar, 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 := math.min(x0 + curveW + step * (1 + (bull ? outB : outR)), xMax)
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(math.min(x0 + curveW + step * (1 + outB), xMax), 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(math.min(x0 + curveW + step * (1 + outR), xMax), rowR, str.tostring(horizon) + "+", color = tr, style = label.style_label_left, textcolor = dnTxt, size = 12, text_font_family = font.family_monospace))
// the live gap on one side nearest to price, na when that side has none
nearestOf(array<FVG> gs) =>
FVG best = na
if gs.size() > 0
best := gs.get(rankGaps(gs).get(0))
best
// a nearest gap's panel line: its badge number on the chart, range and distance from price. On closed bars a live bull
// gap sits at or below price and a live bear gap at or above it, but a bar still forming can poke through one before its
// close decides the break, so whether the gap is above or below is read from where price is now
gapRowTxt(FVG g, array<FVG> zones) =>
string out = "none"
if not na(g)
string num = ""
if linkZones
for [n, z] in zones
if z.side == g.side and z.bornBar == g.bornBar
num := "#" + str.tostring(n + 1) + " · "
break
d = gapDist(g)
out := num + str.tostring(g.bot, format.mintick) + " – " + str.tostring(g.top, format.mintick) + " · " + (d == 0 ? "inside" : str.tostring(d, format.mintick) + (close > g.top ? " below" : " above"))
out
// a nearest gap's tooltip: its CE, whether price has touched it yet, and when the gap formed
gapTip(FVG g) =>
string out = ""
if not na(g)
out := "CE " + str.tostring((g.top + g.bot) / 2, format.mintick) + (g.ceHit ? " · first touched " + barsTxt(bar_index - g.ceBar) + " ago" : " · not touched yet") + " · formed " + str.format_time(g.bornTime, "yyyy-MM-dd HH:mm", syminfo.timezone)
out
// a side's median life for the panel: a dash while the side has no gaps, past the horizon when its curve never reaches 50%
medTxt(int m, int n) =>
n == 0 ? "—" : na(m) ? ">" + str.tostring(horizon) : str.tostring(m)
// CE respect: the share of decided CE windows that held, a dash before the first one
ceTxt(int held, int tried) =>
tried == 0 ? "—" : str.tostring(100.0 * held / tried, "#") + "%"
// ─── Gaps: every state change happens on bar close, so nothing repaints ───
if barstate.isconfirmed
// touches, breaks and CE windows on the live gaps first, then this bar's new gap
[tB, hB] = stepGaps(bulls, bullLives)
[tR, hR] = stepGaps(bears, bearLives)
ceTryB += tB
ceHeldB += hB
ceTryR += tR
ceHeldR += hR
if bullGap
addGap(bulls, bullLives, 1, low, high[2])
if bearGap
addGap(bears, bearLives, -1, low[2], high)
// ─── Headroom: room above the candles for the panel and below for the legend; the price anchor keeps the script on
// the price scale ───
span = nz(visHi - visLo, high - low)
plot(barstate.islast ? visHi + 0.40 * span : na, "Headroom top", color = color.new(#000000, 100), display = display.pane, editable = false)
plot(barstate.islast ? visLo - 0.31 * span : na, "Headroom bottom", color = color.new(#000000, 100), display = display.pane, editable = false)
plot(close, "Price anchor", 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 == "Large" ? size.large : panelTxt == "Normal" ? size.normal : size.small
var table panel = showPanel ? table.new(pos, 2, 8, 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 7
panel.cell(0, r, "")
panel.cell(1, r, "")
for r in array.from(0, 7)
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, string tip) =>
panel.cell(1, r, t, text_color = c, text_halign = text.align_right, text_size = pSize, tooltip = tip)
// ─── Tubes, 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 ? upCol : dnCol
// is the lead real: the mean-life difference tested with gaps 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)
leadReal = 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: tubes end at rightX, the curve starts curveGap bars after them; a badge 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 = nearestGaps(bulls)
zones.concat(nearestGaps(bears))
zones := sortZones(zones)
// painted tubes: each nose sits on its gap's middle candle; the nose and the layer steps widen with zoom, like the
// badges, but a fresh gap too narrow for that keeps steps small enough for all five layers and its core line to fit.
// A gap 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 does not render, leaving only the lines
zoneFrom = bar_index - math.min(visBars + 5, PAST_MAX, bar_index)
for g in zones
xL = math.max(g.midBar, zoneFrom)
paintZone(g, 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 gaps yet has no curve, so nothing of it is drawn
paintHero(bullLead ? cR : cB, bullLead ? cB : cR, x0, yBot, span, bullLead ? dnCol : upCol, 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 gaps
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, dnCol)
if nB > 0
drawCurve(cB, x0, yBot, span, upCol)
// 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, upCol, "bull", bullFirst ? label.style_label_upper_right : label.style_label_lower_left)
drawMedian(cR, medR, x0, yBot, span, dnCol, "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, title, legend, CE respect and the badge note
tr = color.new(#000000, 100)
xR = x0 + int(curveW * 0.55)
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 A FAIR VALUE GAP 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.13 * span, "━ bull FVGs · n " + str.tostring(nB) + " · CE respect " + ceTxt(ceHeldB, ceTryB), color = tr, style = label.style_label_left, textcolor = upTxt, size = 13, text_font_family = font.family_monospace))
lbls.push(label.new(x0 - 1, yBot - 0.19 * span, "━ bear FVGs · n " + str.tostring(nR) + " · CE respect " + ceTxt(ceHeldR, ceTryR), 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.25 * span, "● each gap's number on price is its badge 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 gap above) and support (bull gap 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 gap in the row above lasts this many more bars without a close through its far side, 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)
// the lead, which sets the header colour and is spelled out in the header's tooltip. The p value is cut, not
// rounded, and to four places near the 0.05 line, so the printed value never contradicts the colour
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 = leadReal ? leadCol : MUTED_COL
leadTxt = not ready ? "collecting · needs " + str.tostring(MIN_EV) + " breaks each side" : na(pVal) ? lead + " gaps hold " + xTxt + " · too little history to test" : leadReal ? lead + " gaps hold " + xTxt + " · unlikely to be chance (" + pTxt + ")" : lead + " gaps hold " + xTxt + " · could be chance (" + pTxt + ")"
headTip = "Header colour: the side whose gaps hold longer on average inside the curve horizon (the area under its curve over the other's), shown only when that difference is unlikely to be chance (p below 0.05, gaps that lived through the same stretch of price tested as one group); grey otherwise. Now: " + leadTxt
setTxt = "gap ≥ " + str.tostring(minSize) + " ATR · " + (useDisp ? "body ≥ " + str.tostring(dispMult) + " ATR" : "no body filter") + " · horizon " + str.tostring(horizon) + "\nsmoothing " + str.tostring(smoothBars, "#") + " · hold window " + str.tostring(holdWin) + " · CE window " + str.tostring(ceWin)
ceRow = ceTxt(ceHeldB, ceTryB) + " bull (n " + str.tostring(ceTryB) + ") · " + ceTxt(ceHeldR, ceTryR) + " bear (n " + str.tostring(ceTryR) + ")"
// name bar, settings, nearest gaps, CE respect, median life, live gaps, last bar
panel.cell(0, 0, "FVG HOLDING POWER · hold curves", bgcolor = statCol, text_color = lum(statCol) > 0.18 ? #000000 : #FFFFFF, text_halign = text.align_left, text_size = pSize, text_formatting = text.format_bold, tooltip = headTip + "\n\nSettings: " + setTxt + "\nLive gaps: " + str.format("{0} bull · {1} bear", bulls.size(), bears.size()))
rowL(1, "Resistance (bear FVG)", "The live bear gap nearest above price: its number on the chart, range and distance from price. Hover the value for its CE and when it formed.")
rowR(1, gapRowTxt(nBear, zones), bearCol, gapTip(nBear))
rowL(2, holdLbl, holdTip)
rowR(2, na(nBear) ? "—" : holdOdds(smR, heldAge(nBear)), bearCol, "")
rowL(3, "Support (bull FVG)", "The live bull gap nearest below price: its number on the chart, range and distance from price. Hover the value for its CE and when it formed.")
rowR(3, gapRowTxt(nBull, zones), bullCol, gapTip(nBull))
rowL(4, holdLbl, holdTip)
rowR(4, na(nBull) ? "—" : holdOdds(smB, heldAge(nBull)), bullCol, "")
rowL(5, "CE respect (" + barsTxt(ceWin) + ")", "Of the gaps whose CE (the middle of the gap) price has touched, the share with no close through the far side within the CE window after that first touch. n = touched gaps whose window is decided; gaps dropped from tracking before then are left out.")
rowR(5, ceRow, fg, "")
rowL(6, "Median life (bars)", "Age by which half of each side's gaps have been closed through, live ones included.")
rowR(6, medTxt(medB, nB) + " bull · " + medTxt(medR, nR) + " bear", fg, "")
panel.cell(0, 7, "Last bar " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) + " exchange time · " + str.tostring(bar_index + 1, "#,##0") + " bars", text_color = fg, text_halign = text.align_left, text_size = pSize)