本页源码来自 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/
// © GBB
//@version=6
indicator("Liquidity Sweep Map [GBB]", shorttitle = "LSM [GBB]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
// ═══════════════════════════════════════════════════════════════════════════════
// Liquidity Sweep Map — where resting liquidity plausibly sits, drawn as a heat
// map, and the exact bar it gets taken. Visual context, not signals.
// ═══════════════════════════════════════════════════════════════════════════════
// ───────────────────────────────────────────────
SRC_SW = 1
SRC_EQ = 2
SRC_PD = 3
SRC_PW = 4
SRC_SS = 5
SRC_OR = 6
CLS_RECLAIM = 1
CLS_DELAYED = 2
CLS_BREAK = 3
ST_ACTIVE = 0
ST_SWEPT = 1
ST_BROKEN = 2
ST_EXPIRED = 3
ST_PENDING = 4
ST_ROLLED = 5
ST_DROPPED = 6
CH_SWEPT = 1
CH_TARGET = 2
CH_HIT = 10
CH_INVALID = 11
CH_TIMEOUT = 12
CH_NOFVG = 13
CH_NOCONF = 14
// ─── inputs: look ──────────────────────────────────────────────────────────────
G_L = "Look"
palette = input.string("Ember", "Heat palette", options = ["Ember", "Liquidation", "Fire", "Ice", "Mono", "Classic"], group = G_L, tooltip = "Ember: indigo → magenta → amber → white-hot (deepens to burnt orange on light charts). Liquidation: purple → teal → yellow. Fire: navy → orange → white. Ice: deep blue → cyan → white. Mono: follows your chart text colour. Classic: red above, teal below.")
colHi = input.color(#F23645, "Classic: highs", inline = "cl", group = G_L)
colLo = input.color(#089981, "lows", inline = "cl", group = G_L)
glowOn = input.bool(true, "Glow", inline = "gl", group = G_L)
glowK = input.float(0.5, "size (× ATR)", minval = 0.0, step = 0.05, inline = "gl", group = G_L)
heatMode = input.string("Relative", "Heat scale", options = ["Relative", "Fixed"], group = G_L, tooltip = "Relative: the strongest visible band is always the hottest (like a liquidation heatmap). Fixed: a colour means the same weight on every chart.")
weightScale = input.float(4.0, "Fixed: full heat at weight", minval = 0.5, step = 0.5, group = G_L)
ladderOn = input.bool(true, "Depth ladder at the right edge", group = G_L)
ladderLen = input.int(20, "Ladder length (bars)", minval = 3, maxval = 100, group = G_L)
rightPad = input.int(6, "Gap after last bar", minval = 1, maxval = 100, group = G_L)
labelsOn = input.bool(true, "Level labels", inline = "lb", group = G_L)
priceOn = input.bool(true, "with price", inline = "lb", group = G_L)
labelPill = input.bool(true, "Filled pill labels", group = G_L, tooltip = "Labels sit on a pill in the band's heat colour. Off: coloured text only.")
labelSizeIn = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_L)
legendOn = input.bool(true, "Heat legend", inline = "lg", group = G_L)
legendPos = input.string("Top right", "", options = ["Top right", "Bottom right", "Bottom left", "Top left"], inline = "lg", group = G_L)
G_D = "Declutter"
bandsPerSide = input.int(6, "Bands above and below price", minval = 1, maxval = 30, group = G_D)
renderRange = input.float(6.0, "Only within (× ATR of price)", minval = 0.5, step = 0.5, group = G_D)
mergeTolK = input.float(0.15, "Merge levels closer than (× ATR)", minval = 0.0, step = 0.01, group = G_D)
bandPadK = input.float(0.08, "Band thickness (× ATR)", minval = 0.0, step = 0.01, group = G_D)
maxLookback = input.int(300, "Start bands at most N bars back", minval = 10, maxval = 4999, group = G_D)
G_SW = "Sweeps"
showSweeps = input.bool(true, "Mark sweeps", group = G_SW)
showGhosts = input.bool(true, "Ghost lines for taken levels", group = G_SW)
showBreaks = input.bool(false, "Ghost lines for broken levels", group = G_SW)
heroOn = input.bool(true, "Spotlight the latest sweep", group = G_SW, tooltip = "The most recent sweep gets a box on the wick and a named callout. Older sweeps fade to a small ✕.")
sweepNames = input.bool(false, "Name the level on older sweep marks", group = G_SW, tooltip = "Off keeps the chart clean; the name is always in the hover tooltip.")
keepSweeps = input.int(12, "Keep last N sweeps", minval = 1, maxval = 150, group = G_SW)
// ─── inputs: engine ────────────────────────────────────────────────────────────
G_P = "Pools"
useSW = input.bool(true, "Swing highs/lows", group = G_P, tooltip = "Equal highs/lows are built from swings, so they need this on.")
useEQ = input.bool(true, "Equal highs/lows", group = G_P)
usePD = input.bool(true, "Previous day high/low", group = G_P)
usePW = input.bool(true, "Previous week high/low", group = G_P)
useAsia = input.bool(true, "Asia high/low", inline = "ss", group = G_P)
useLondon = input.bool(true, "London", inline = "ss", group = G_P)
useNYs = input.bool(false, "NY", inline = "ss", group = G_P)
useOR = input.bool(false, "Opening range high/low", group = G_P)
pivL = input.int(5, "Pivot left", minval = 1, inline = "piv", group = G_P)
pivR = input.int(3, "right", minval = 1, inline = "piv", group = G_P)
kEq = input.float(0.10, "Equal tolerance (× ATR)", minval = 0.0, step = 0.01, group = G_P)
maxEqSpan = input.int(100, "Max equal-high span (bars)", minval = 1, group = G_P)
halfLife = input.float(200.0, "Heat half-life (bars)", minval = 1.0, group = G_P, tooltip = "Applies to swing and equal highs/lows. Previous day/week and session levels keep full heat until the next period replaces them.")
minWeight = input.float(0.15, "Remove below weight", minval = 0.0, step = 0.01, group = G_P)
maxActive = input.int(150, "Max tracked pools", minval = 10, maxval = 400, group = G_P)
G_C = "Calendar"
tzIn = input.string("America/New_York", "Timezone", group = G_C, tooltip = "Used for trading days, weeks and sessions. Crypto: UTC.")
rollH = input.int(18, "Trading day starts at (hour)", minval = 0, maxval = 23, group = G_C, tooltip = "CME futures 18, FX 17, crypto 0.")
sessAsia = input.session("2000-0000", "Asia", group = G_C)
sessLondon = input.session("0200-0500", "London", group = G_C)
sessNY = input.session("0930-1600", "New York", group = G_C)
orStartIn = input.string("0930", "Opening range start (HHMM)", inline = "or", group = G_C)
orMinutes = input.int(30, "minutes", minval = 1, inline = "or", group = G_C)
G_W = "Heat weights"
bSW = input.float(1.0, "Swing", inline = "w1", group = G_W)
bEQ = input.float(1.6, "Equal", inline = "w1", group = G_W)
bSS = input.float(1.4, "Session", inline = "w1", group = G_W)
bPD = input.float(1.8, "Day", inline = "w2", group = G_W)
bPW = input.float(2.0, "Week", inline = "w2", group = G_W)
bOR = input.float(1.2, "OR", inline = "w2", group = G_W)
touchStep = input.float(0.25, "Per extra touch", inline = "w3", group = G_W)
touchCap = input.float(2.0, "cap", inline = "w3", group = G_W)
G_S = "Sweep rules"
atrLen = input.int(14, "ATR length", minval = 1, group = G_S)
minTicks = input.int(2, "Min penetration (ticks)", minval = 0, group = G_S)
kPen = input.float(0.02, "Min penetration (× ATR)", minval = 0.0, step = 0.01, group = G_S)
useMaxPen = input.bool(true, "Deeper than", inline = "mp", group = G_S)
kMaxPen = input.float(1.5, "× ATR is a break", minval = 0.0, step = 0.1, inline = "mp", group = G_S)
delayedOn = input.bool(false, "Allow delayed reclaim within", inline = "dr", group = G_S)
kReclaim = input.int(3, "bars", minval = 1, inline = "dr", group = G_S)
G_CH = "Confirmation chain (sweep → inverse FVG → target)"
chainOn = input.bool(true, "Track (for alerts)", inline = "cd", group = G_CH)
chainDraw = input.bool(false, "draw on chart", inline = "cd", group = G_CH)
kLeg = input.int(5, "FVG must form within (bars before sweep)", minval = 0, group = G_CH)
kIfvg = input.int(10, "Inversion within (bars)", minval = 0, group = G_CH)
kTarget = input.int(100, "Target timeout (bars)", minval = 1, group = G_CH)
fvgMin = input.float(0.0, "FVG min size (× ATR)", minval = 0.0, step = 0.05, group = G_CH)
invBuf = input.float(0.1, "Invalidation buffer (× ATR)", minval = 0.0, step = 0.05, group = G_CH)
G_A = "Alerts (bar close only)"
alReclaim = input.bool(true, "Sweep & reclaim", group = G_A)
alBreakHT = input.bool(true, "Break of previous day/week level", group = G_A)
alIfvg = input.bool(true, "Inverse FVG confirmed", group = G_A)
alTarget = input.bool(true, "Target reached", group = G_A)
// ─── types ─────────────────────────────────────────────────────────────────────
type Pool
int id
float level
int side
int src
int created
int pivotBar
int touches = 1
int members = 1
int state = 0
int endBar = -1
float expiryAge = 0.0
int sess = -1
type Pending
Pool pool
int bar
float maxpen
float ext
float penAtr
type Cand
Pool pool
int cls
float penAtr
float ext
int orig
type Chain
int eventId
int side
int sweepBar
float extreme
float buffer
float invLevel
int state = 1
int confBar = -1
float confClose = na
float confAtr = na
float target = na
int endBar = -1
line tline = na
type Tracker
float hi = na
float lo = na
bool valid = false
type Ctr
int pid = 0
int eid = 0
type Band
int side
float top
float bot
float w
int left
float core
float coreW
string name
string tip
int n
// ─── colour ────────────────────────────────────────────────────────────────────
bool isLight = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) > 382
f_g4(float x, color c0, color c1, color c2, color c3) =>
x < 1.0 / 3 ? color.from_gradient(x, 0.0, 1.0 / 3, c0, c1) : x < 2.0 / 3 ? color.from_gradient(x, 1.0 / 3, 2.0 / 3, c1, c2) : color.from_gradient(x, 2.0 / 3, 1.0, c2, c3)
f_g5(float x, color c0, color c1, color c2, color c3, color c4) =>
x < 0.25 ? color.from_gradient(x, 0.0, 0.25, c0, c1) : x < 0.5 ? color.from_gradient(x, 0.25, 0.5, c1, c2) : x < 0.75 ? color.from_gradient(x, 0.5, 0.75, c2, c3) : color.from_gradient(x, 0.75, 1.0, c3, c4)
// heat colour for intensity x in [0,1]; side only matters for Classic
f_heat(float xIn, int side) =>
float x = math.max(0.0, math.min(1.0, xIn))
switch palette
"Ember" => isLight ? f_g5(x, #9A8FE0, #A64CC4, #D63A66, #E2671B, #9A3A08) : f_g5(x, #3A2C8C, #8E3BC4, #E8457A, #FF8A3D, #FFE9B8)
"Liquidation" => f_g5(x, #7A4FD0, #4A7FD8, #22B5A8, #74DC6A, #FDE725)
"Fire" => f_g4(x, #5B6FC8, #D04C82, #F5952F, #FFF1CC)
"Ice" => f_g4(x, #4069C0, #2BA2D6, #55DCE4, #E6FBFF)
"Mono" => color.from_gradient(x, 0.0, 1.0, color.new(chart.fg_color, 75), chart.fg_color)
=> color.from_gradient(x, 0.0, 1.0, color.new(side == 1 ? colHi : colLo, 60), side == 1 ? colHi : colLo)
// text must stay readable on both themes: bright heat on dark charts, chart text colour on light ones
f_text(float x, int side) => isLight or palette == "Mono" ? color.new(chart.fg_color, 5) : f_heat(math.max(x, 0.75), side)
// ink that stays readable on a filled heat pill
f_ink(color c) => 0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c) > 140 ? #17121F : #FFFFFF
f_accent(int side) => palette == "Ember" ? f_heat(1.0, side) : isLight ? (palette == "Classic" ? (side == 1 ? colHi : colLo) : f_heat(0.55, side)) : f_heat(1.0, side)
labelSize = labelSizeIn == "Tiny" ? size.tiny : labelSizeIn == "Normal" ? size.normal : size.small
// ─── helpers ───────────────────────────────────────────────────────────────────
f_hm(string s, int at) => int(str.tonumber(str.substring(s, at, at + 2))) * 60 + int(str.tonumber(str.substring(s, at + 2, at + 4)))
f_in(int m, int st, int en) => st < en ? (m >= st and m < en) : (m >= st or m < en)
f_base(int src) => src == SRC_SW ? bSW : src == SRC_EQ ? bEQ : src == SRC_PD ? bPD : src == SRC_PW ? bPW : src == SRC_SS ? bSS : bOR
f_name(int src, int side, int sess, int members) =>
string hl = side == 1 ? "H" : "L"
switch src
SRC_PD => "PD" + hl
SRC_PW => "PW" + hl
SRC_EQ => "EQ" + hl + (members > 2 ? " ×" + str.tostring(members) : "")
SRC_SS => (sess == 0 ? "Asia " : sess == 1 ? "London " : "NY ") + hl
SRC_OR => "OR" + hl
=> "Swing " + hl
method tmult(Pool p) => math.min(1.0 + touchStep * (p.touches - 1), touchCap)
// Calendar levels (PD, PW, sessions, OR) keep full heat until the next period rolls them; only swing/EQ decay.
f_decays(int src) => src == SRC_SW or src == SRC_EQ
method weight(Pool p, int t) => f_base(p.src) * p.tmult() * (f_decays(p.src) ? math.pow(0.5, (t - p.created) / halfLife) : 1.0)
method refreshExpiry(Pool p) =>
float b = f_base(p.src) * p.tmult()
p.expiryAge := b <= minWeight ? 0.0 : not f_decays(p.src) ? 1e12 : halfLife * math.log(b / minWeight) / math.log(2.0)
p
// ─── per-bar series (computed on every bar so history is consistent) ──────────
float atr = ta.atr(atrLen)
int shiftMs = rollH * 3600000 - (rollH >= 12 ? 86400000 : 0)
int tsh = time - shiftMs
int tday = math.floor(timestamp("UTC", year(tsh, tzIn), month(tsh, tzIn), dayofmonth(tsh, tzIn), 0, 0) / 86400000.0)
int week = math.floor((tday + 3) / 7.0)
int mins = hour(time, tzIn) * 60 + minute(time, tzIn)
int orSt = f_hm(orStartIn, 0)
bool inA = f_in(mins, f_hm(sessAsia, 0), f_hm(sessAsia, 5))
bool inL = f_in(mins, f_hm(sessLondon, 0), f_hm(sessLondon, 5))
bool inN = f_in(mins, f_hm(sessNY, 0), f_hm(sessNY, 5))
bool inO = mins >= orSt and mins < orSt + orMinutes
f_pivHi(int L, int R) =>
bool ok = bar_index >= L + R
if ok
float hc = high[R]
for j = 1 to L
if not (hc > high[R + j])
ok := false
break
if ok
for j = 0 to R - 1
if not (hc >= high[j])
ok := false
break
ok
f_pivLo(int L, int R) =>
bool ok = bar_index >= L + R
if ok
float lc = low[R]
for j = 1 to L
if not (lc < low[R + j])
ok := false
break
if ok
for j = 0 to R - 1
if not (lc <= low[j])
ok := false
break
ok
bool pivHi = f_pivHi(pivL, pivR)
bool pivLo = f_pivLo(pivL, pivR)
// ─── state ─────────────────────────────────────────────────────────────────────
var array<Pool> pools = array.new<Pool>()
var array<Pending> pendings = array.new<Pending>()
var array<Chain> chains = array.new<Chain>()
var Ctr ctr = Ctr.new()
var Tracker trD = Tracker.new()
var Tracker trW = Tracker.new()
var Tracker trA = Tracker.new()
var Tracker trL = Tracker.new()
var Tracker trN = Tracker.new()
var Tracker trO = Tracker.new()
// sweep drawings, oldest first, trimmed to keepSweeps
var array<line> ghostLines = array.new<line>()
var array<box> sweepBoxes = array.new<box>()
var array<label> sweepTags = array.new<label>()
var array<label> chainTags = array.new<label>()
// the latest sweep (the "hero"); demoted to a quiet ✕ when the next one prints
var box heroBox = na
var label heroTag = na
var line heroGhost = na
var string heroName = ""
f_newPool(float lvl, int side, int src, int t, int pb, int sess) =>
Pool p = Pool.new(ctr.pid, lvl, side, src, t, pb, 1, 1, ST_ACTIVE, -1, 0.0, sess)
p.refreshExpiry()
ctr.pid += 1
pools.push(p)
p
f_commit(Tracker tr, int src, int sess, int t) =>
if tr.valid
for p in pools
if p.state == ST_ACTIVE and p.src == src and p.sess == sess
p.state := ST_ROLLED
p.endBar := t
f_newPool(tr.hi, 1, src, t, t, sess)
f_newPool(tr.lo, -1, src, t, t, sess)
true
method trackSess(Tracker tr, bool f, bool fPrev, bool isFirst) =>
if f
if isFirst or not fPrev
tr.hi := high
tr.lo := low
tr.valid := not isFirst
else
tr.hi := math.max(tr.hi, high)
tr.lo := math.min(tr.lo, low)
else
tr.valid := false
tr
method trackPeriod(Tracker tr, bool isNew, bool isFirst) =>
if isFirst or isNew
tr.hi := high
tr.lo := low
tr.valid := not isFirst
else
tr.hi := math.max(tr.hi, high)
tr.lo := math.min(tr.lo, low)
tr
f_target(int side, float c) =>
float best = na
for p in pools
if p.state == ST_ACTIVE and p.side == -side
if side == 1 and p.level < c and (na(best) or p.level > best)
best := p.level
else if side == -1 and p.level > c and (na(best) or p.level < best)
best := p.level
best
// returns true when the chain confirmed on this bar
method step(Chain ch, int t, float a) =>
bool confirmed = false
if ch.state < 10
bool beyond = ch.side == 1 ? high >= ch.extreme + ch.buffer : low <= ch.extreme - ch.buffer
if ch.state == CH_SWEPT
if na(ch.invLevel)
ch.state := CH_NOFVG
ch.endBar := t
else if t > ch.sweepBar and beyond
ch.state := CH_INVALID
ch.endBar := t
else if (ch.side == 1 ? close < ch.invLevel : close > ch.invLevel)
ch.state := CH_TARGET
ch.confBar := t
ch.confClose := close
ch.confAtr := a
ch.target := f_target(ch.side, close)
confirmed := true
else if t - ch.sweepBar >= kIfvg
ch.state := CH_NOCONF
ch.endBar := t
else if t > ch.confBar
if beyond
ch.state := CH_INVALID
ch.endBar := t
else if not na(ch.target) and (ch.side == 1 ? low <= ch.target : high >= ch.target)
ch.state := CH_HIT
ch.endBar := t
else if t - ch.confBar >= kTarget
ch.state := CH_TIMEOUT
ch.endBar := t
confirmed
f_legFvg(int side, float a) =>
float lvl = na
float minSize = fvgMin * a
for j = 0 to kLeg
if bar_index - j < 2
break
float gap = side == 1 ? low[j] - high[j + 2] : low[j + 2] - high[j]
if gap > 0 and gap >= minSize
lvl := side == 1 ? high[j + 2] : low[j + 2]
break
lvl
f_trimL(array<line> a, int n) =>
while a.size() > n
a.shift().delete()
true
f_trimB(array<box> a, int n) =>
while a.size() > n
a.shift().delete()
true
f_trimT(array<label> a, int n) =>
while a.size() > n
a.shift().delete()
true
// ─── per-bar outputs (parity export + alerts) ─────────────────────────────────
int evHiCls = 0
int evHiSrc = 0
float evHiLvl = na
int evLoCls = 0
int evLoSrc = 0
float evLoLvl = na
int chConfHi = 0
int chConfLo = 0
int nActive = na
bool aReclaim = false
bool aBreakHT = false
bool aIfvg = false
bool aTarget = false
// ═══════════════════════════════ engine ═══════════════════════════════════════
if barstate.isconfirmed and not na(atr)
int t = bar_index
bool isFirst = na(atr[1])
float a = atr
float thr = math.max(minTicks * syminfo.mintick, kPen * a)
float maxpen = kMaxPen * a
float tol = kEq * a
// ── 2. time pools ──
bool newDay = not isFirst and tday != tday[1]
bool newWeek = not isFirst and week != week[1]
if newDay and usePD
f_commit(trD, SRC_PD, -1, t)
if newWeek and usePW
f_commit(trW, SRC_PW, -1, t)
if not isFirst and inA[1] and not inA and useAsia
f_commit(trA, SRC_SS, 0, t)
if not isFirst and inL[1] and not inL and useLondon
f_commit(trL, SRC_SS, 1, t)
if not isFirst and inN[1] and not inN and useNYs
f_commit(trN, SRC_SS, 2, t)
if not isFirst and inO[1] and not inO and useOR
f_commit(trO, SRC_OR, -1, t)
trD.trackPeriod(newDay, isFirst)
trW.trackPeriod(newWeek, isFirst)
trA.trackSess(inA, inA[1], isFirst)
trL.trackSess(inL, inL[1], isFirst)
trN.trackSess(inN, inN[1], isFirst)
trO.trackSess(inO, inO[1], isFirst)
// ── 3. delayed pendings ──
array<Cand> candHi = array.new<Cand>()
array<Cand> candLo = array.new<Cand>()
array<Pending> still = array.new<Pending>()
for pd in pendings
Pool p = pd.pool
float run = 0.0
bool back = false
if p.side == 1
pd.ext := math.max(pd.ext, high)
run := high - p.level
back := close < p.level
else
pd.ext := math.min(pd.ext, low)
run := p.level - low
back := close > p.level
int cls = 0
if useMaxPen and run > pd.maxpen
cls := CLS_BREAK
else if back
cls := CLS_DELAYED
else if t - pd.bar >= kReclaim
cls := CLS_BREAK
if cls == 0
still.push(pd)
else if p.side == 1
candHi.push(Cand.new(p, cls, pd.penAtr, pd.ext, pd.bar))
else
candLo.push(Cand.new(p, cls, pd.penAtr, pd.ext, pd.bar))
pendings := still
// ── 4. sweeps / touches ──
for p in pools
if p.state == ST_ACTIVE
float pen = p.side == 1 ? high - p.level : p.level - low
if not (pen >= thr)
bool touch = p.side == 1 ? (high >= p.level - tol and high - p.level < thr) : (low <= p.level + tol and p.level - low < thr)
if touch
p.touches += 1
p.refreshExpiry()
else
int cls = CLS_BREAK
if useMaxPen and pen > maxpen
cls := CLS_BREAK
else if (p.side == 1 ? close < p.level : close > p.level)
cls := CLS_RECLAIM
else if delayedOn
cls := CLS_DELAYED
float ext = p.side == 1 ? high : low
if cls == CLS_DELAYED
p.state := ST_PENDING
pendings.push(Pending.new(p, t, maxpen, ext, pen / a))
else if p.side == 1
candHi.push(Cand.new(p, cls, pen / a, ext, t))
else
candLo.push(Cand.new(p, cls, pen / a, ext, t))
array<Chain> newChains = array.new<Chain>()
for side in array.from(1, -1)
array<Cand> lst = side == 1 ? candHi : candLo
if lst.size() > 0
array<float> wts = array.new<float>()
for cd in lst
wts.push(cd.pool.weight(t))
int k = 0
if lst.size() > 1
for i = 1 to lst.size() - 1
if wts.get(i) > wts.get(k) or (wts.get(i) == wts.get(k) and lst.get(i).pool.id > lst.get(k).pool.id)
k := i
float sw = 0.0
line kGhost = na
for [i, cd] in lst
sw += wts.get(i)
cd.pool.state := cd.cls == CLS_BREAK ? ST_BROKEN : ST_SWEPT
cd.pool.endBar := t
// ghost: the level that was taken (dashed) or broken (dotted), ending at this bar
bool brk = cd.cls == CLS_BREAK
if (brk and showBreaks) or (not brk and showGhosts)
line gl = line.new(math.max(cd.pool.pivotBar, t - 60), cd.pool.level, t, cd.pool.level, color = color.new(chart.fg_color, brk ? 82 : 74), style = brk ? line.style_dotted : line.style_dashed, width = 1)
ghostLines.push(gl)
if i == k
kGhost := gl
f_trimL(ghostLines, keepSweeps)
Cand kc = lst.get(k)
int evId = ctr.eid
ctr.eid += 1
if side == 1
evHiCls := kc.cls
evHiSrc := kc.pool.src
evHiLvl := kc.pool.level
else
evLoCls := kc.cls
evLoSrc := kc.pool.src
evLoLvl := kc.pool.level
bool isRec = kc.cls == CLS_RECLAIM or kc.cls == CLS_DELAYED
string nm = f_name(kc.pool.src, side, kc.pool.sess, kc.pool.members)
if showSweeps and isRec
color acc = f_accent(side)
float top = side == 1 ? kc.ext : kc.pool.level
float bot = side == 1 ? kc.pool.level : kc.ext
string tip = (kc.cls == CLS_DELAYED ? "Delayed sweep" : "Sweep") + " of " + nm + " " + str.tostring(kc.pool.level, format.mintick) + "\nWick " + str.tostring(kc.penAtr, "0.00") + " ATR beyond, closed back inside" + (lst.size() > 1 ? "\n+" + str.tostring(lst.size() - 1) + " more level(s) taken" : "")
if heroOn
// demote the previous hero: drop its box, fade its callout to ✕, dim its ghost
if not na(heroTag)
heroTag.set_text(sweepNames ? "✕ " + heroName : "✕")
heroTag.set_color(color.new(color.black, 100))
heroTag.set_textcolor(color.new(chart.fg_color, 55))
heroTag.set_size(size.small)
if not na(heroBox)
heroBox.delete()
if not na(heroGhost)
heroGhost.set_color(color.new(chart.fg_color, 74))
// the new hero: the only box drawn on a candle, plus a filled callout
heroBox := box.new(t - 1, top, t + 1, bot, border_color = acc, border_width = 1, bgcolor = color.new(acc, 72))
heroTag := label.new(t, kc.ext, "Swept " + nm + " · " + str.tostring(kc.pool.level, format.mintick), style = side == 1 ? label.style_label_down : label.style_label_up, color = acc, textcolor = f_ink(acc), size = labelSize, tooltip = tip)
heroName := nm
heroGhost := kGhost
if not na(kGhost)
kGhost.set_color(color.new(chart.fg_color, 45))
sweepTags.push(heroTag)
else
sweepBoxes.push(box.new(t - 1, top, t + 1, bot, border_color = color.new(acc, 10), border_width = 1, bgcolor = color.new(acc, 80)))
sweepTags.push(label.new(t, kc.ext, sweepNames ? "✕ " + nm : "✕", style = side == 1 ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = acc, size = size.small, tooltip = tip))
f_trimB(sweepBoxes, keepSweeps)
f_trimT(sweepTags, keepSweeps)
if kc.cls == CLS_RECLAIM
aReclaim := true
if chainOn
newChains.push(Chain.new(evId, side, t, kc.ext, invBuf * a, f_legFvg(side, a), CH_SWEPT, -1, na, na, na, -1))
if kc.cls == CLS_BREAK and (kc.pool.src == SRC_PD or kc.pool.src == SRC_PW)
aBreakHT := true
if alReclaim and kc.cls == CLS_RECLAIM
alert("LSM: " + nm + " swept and reclaimed at " + str.tostring(kc.pool.level, format.mintick) + " on " + syminfo.ticker, alert.freq_once_per_bar_close)
if alBreakHT and kc.cls == CLS_BREAK and (kc.pool.src == SRC_PD or kc.pool.src == SRC_PW)
alert("LSM: " + nm + " broken at " + str.tostring(kc.pool.level, format.mintick) + " on " + syminfo.ticker, alert.freq_once_per_bar_close)
array<Pool> keep = array.new<Pool>()
for p in pools
if p.state == ST_ACTIVE or p.state == ST_PENDING
keep.push(p)
pools := keep
// ── 5. chains ──
if chainOn
for ch in newChains
chains.push(ch)
array<Chain> alive = array.new<Chain>()
for ch in chains
if ch.state < 10
int prevState = ch.state
color acc = f_accent(ch.side)
if ch.step(t, a)
if ch.side == 1
chConfHi += 1
else
chConfLo += 1
aIfvg := true
if alIfvg
alert("LSM: inverse FVG confirmed after a " + (ch.side == 1 ? "high" : "low") + "-side sweep on " + syminfo.ticker, alert.freq_once_per_bar_close)
if chainDraw
chainTags.push(label.new(t, ch.side == 1 ? high : low, "IFVG", style = ch.side == 1 ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = color.new(acc, 25), size = size.tiny, tooltip = "Inverse FVG confirmed: the sweep leg's gap was closed through"))
if chainDraw and not na(ch.target)
ch.tline := line.new(t, ch.target, t + 1, ch.target, color = color.new(acc, 30), style = line.style_dotted, width = 2)
f_trimT(chainTags, keepSweeps * 2)
if not na(ch.tline)
ch.tline.set_x2(t)
if ch.state >= 10 and prevState == CH_TARGET
if ch.state == CH_HIT
aTarget := true
if alTarget
alert("LSM: chain target reached on " + syminfo.ticker, alert.freq_once_per_bar_close)
if chainDraw and not na(ch.target)
string mk = ch.state == CH_HIT ? "◆ target" : ch.state == CH_INVALID ? "invalid" : "expired"
chainTags.push(label.new(t, ch.target, mk, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(ch.state == CH_HIT ? acc : chart.fg_color, ch.state == CH_HIT ? 10 : 60), size = size.tiny))
f_trimT(chainTags, keepSweeps * 2)
if ch.state < 10
alive.push(ch)
chains := alive
// ── 7. decay expiry ──
for p in pools
if p.state == ST_ACTIVE and (t - p.created) > p.expiryAge
p.state := ST_EXPIRED
p.endBar := t
// ── 8. swings / EQ ──
if useSW
for side in array.from(1, -1)
bool piv = side == 1 ? pivHi : pivLo
if piv
int cb = t - pivR
float lvl = side == 1 ? high[pivR] : low[pivR]
Pool cand = na
if useEQ
float bestD = 1e300
for p in pools
if p.state == ST_ACTIVE and p.side == side and (p.src == SRC_SW or p.src == SRC_EQ) and cb - p.pivotBar <= maxEqSpan
float d = math.abs(p.level - lvl)
if d <= tol and d <= bestD
cand := p
bestD := d
if not na(cand)
cand.level := side == 1 ? math.max(cand.level, lvl) : math.min(cand.level, lvl)
cand.src := SRC_EQ
cand.created := t
cand.pivotBar := cb
cand.members += 1
cand.refreshExpiry()
else
f_newPool(lvl, side, SRC_SW, t, cb, -1)
// ── 9. cap ──
array<Pool> act = array.new<Pool>()
for p in pools
if p.state == ST_ACTIVE
act.push(p)
while act.size() > maxActive
int k = 0
float wk = act.get(0).weight(t)
for i = 1 to act.size() - 1
float wi = act.get(i).weight(t)
if wi < wk
k := i
wk := wi
Pool dp = act.remove(k)
dp.state := ST_DROPPED
dp.endBar := t
array<Pool> keep2 = array.new<Pool>()
for p in pools
if p.state == ST_ACTIVE or p.state == ST_PENDING
keep2.push(p)
pools := keep2
nActive := act.size()
// ═══════════════════════════════ heat map ═════════════════════════════════════
// Rebuilt on the last bar only: merge nearby pools into bands, keep the strongest
// N on each side near price, draw glow + body + core line + depth ladder + label.
var array<box> hmBoxes = array.new<box>()
var array<line> hmLines = array.new<line>()
var array<label> hmLabels = array.new<label>()
f_bandsForSide(int side, float tolM, float pad) =>
array<Band> out = array.new<Band>()
array<float> lv = array.new<float>()
array<Pool> ps = array.new<Pool>()
for p in pools
if p.state == ST_ACTIVE and p.side == side
lv.push(p.level)
ps.push(p)
if ps.size() > 0
array<int> ord = lv.sort_indices(order.ascending)
Band b = na
float last = na
for oi in ord
Pool p = ps.get(oi)
float w = p.weight(bar_index)
string row = f_name(p.src, p.side, p.sess, p.members) + " " + str.tostring(p.level, format.mintick) + " · heat " + str.tostring(w, "0.0") + (p.touches > 1 ? " · " + str.tostring(p.touches) + " touches" : "")
if na(b) or p.level - last > tolM
if not na(b)
out.push(b)
b := Band.new(side, p.level, p.level, 0.0, p.pivotBar, p.level, -1.0, "", "", 0)
b.top := math.max(b.top, p.level)
b.bot := math.min(b.bot, p.level)
b.w += w
b.left := math.min(b.left, p.pivotBar)
b.n += 1
b.tip := b.tip + (b.tip == "" ? "" : "\n") + row
if w > b.coreW
b.coreW := w
b.core := p.level
b.name := f_name(p.src, p.side, p.sess, p.members)
last := p.level
out.push(b)
for x in out
x.top += pad
x.bot -= pad
out
if barstate.islast and not na(atr)
for bx in hmBoxes
bx.delete()
for ln in hmLines
ln.delete()
for lb in hmLabels
lb.delete()
hmBoxes.clear()
hmLines.clear()
hmLabels.clear()
float tolM = mergeTolK * atr
float pad = bandPadK * atr
int xr = bar_index + rightPad
// choose the strongest bands near price on each side first, so the relative
// scale is set by what is actually on screen
array<Band> pick = array.new<Band>()
float wMax = 0.0
for side in array.from(1, -1)
array<Band> bands = f_bandsForSide(side, tolM, pad)
array<float> ws = array.new<float>()
for bd in bands
ws.push(bd.w)
array<int> byW = ws.sort_indices(order.descending)
int drawn = 0
for i in byW
if drawn >= bandsPerSide
break
Band bd = bands.get(i)
if bd.bot <= close + renderRange * atr and bd.top >= close - renderRange * atr
drawn += 1
pick.push(bd)
wMax := math.max(wMax, bd.w)
for bd in pick
int side = bd.side
float x = heatMode == "Relative" ? 0.15 + 0.85 * bd.w / math.max(wMax, 1e-9) : math.min(1.0, bd.w / weightScale)
color c = f_heat(x, side)
int xl = math.max(bd.left, bar_index - math.min(maxLookback, 4999))
if glowOn and glowK > 0
// feathered glow: three nested boxes, faint at the edge, denser toward the core
float g = glowK * atr * (0.5 + 0.5 * x)
float gk = isLight ? 0.8 : 1.0
hmBoxes.push(box.new(xl, bd.top + g, xr, bd.bot - g, border_width = 0, bgcolor = color.new(c, 100 - 100 * (0.06 * gk + 0.04 * x))))
hmBoxes.push(box.new(xl, bd.top + g * 0.6, xr, bd.bot - g * 0.6, border_width = 0, bgcolor = color.new(c, 100 - 100 * (0.08 * gk + 0.06 * x))))
hmBoxes.push(box.new(xl, bd.top + g * 0.28, xr, bd.bot - g * 0.28, border_width = 0, bgcolor = color.new(c, 100 - 100 * (0.14 * gk + 0.12 * x))))
hmBoxes.push(box.new(xl, bd.top, xr, bd.bot, border_width = 0, bgcolor = color.new(c, 80 - 30 * x)))
hmLines.push(line.new(xl, bd.core, xr, bd.core, color = color.new(c, 5), width = x > 0.8 ? 3 : 2))
int xe = xr
if ladderOn
// solid heat bar: length = heat
float lh = 0.2 * atr
xe := xr + 1 + math.max(2, int(math.round(x * ladderLen)))
hmBoxes.push(box.new(xr + 1, math.max(bd.top, bd.core + lh), xe, math.min(bd.bot, bd.core - lh), border_width = 0, bgcolor = c))
if labelsOn
string txt = bd.name + (bd.n > 1 ? " +" + str.tostring(bd.n - 1) : "") + (priceOn ? " " + str.tostring(bd.core, format.mintick) : "")
hmLabels.push(label.new(xe + 1, bd.core, txt, style = label.style_label_left, color = labelPill ? c : color.new(color.black, 100), textcolor = labelPill ? f_ink(c) : f_text(x, side), size = labelSize, tooltip = bd.tip))
// ─── heat legend ───────────────────────────────────────────────────────────────
var table legend = na
if barstate.islast and legendOn
if not na(legend)
legend.delete()
string pos = legendPos == "Top right" ? position.top_right : legendPos == "Bottom left" ? position.bottom_left : legendPos == "Top left" ? position.top_left : position.bottom_right
// small panel; transparent cell borders leave a hairline gap between swatches
legend := table.new(pos, 10, 2, bgcolor = color.new(chart.bg_color, 12), frame_color = color.new(chart.fg_color, 88), frame_width = 1, border_color = color.new(chart.bg_color, 100), border_width = 1)
color dim = color.new(chart.fg_color, 45)
legend.cell(0, 0, "LIQUIDITY HEAT", text_color = dim, text_size = size.tiny, text_halign = text.align_left)
legend.merge_cells(0, 0, 9, 0)
legend.cell(0, 1, "less", text_color = dim, text_size = size.tiny)
for i = 0 to 7
legend.cell(i + 1, 1, "", width = 1.2, height = 1.4, bgcolor = f_heat(i / 7.0, 1))
legend.cell(9, 1, "more", text_color = dim, text_size = size.tiny)
// ═══════════════════════════════ alerts + parity export ═══════════════════════
alertcondition(aReclaim, "Sweep & reclaim", "LSM: sweep & reclaim on {{ticker}}")
alertcondition(aBreakHT, "Break of previous day/week", "LSM: previous day/week level broken on {{ticker}}")
alertcondition(aIfvg, "Inverse FVG confirmed", "LSM: inverse FVG confirmed on {{ticker}}")
alertcondition(aTarget, "Target reached", "LSM: chain target reached on {{ticker}}")
plot(evHiCls, "LSM ev_hi_cls", display = display.data_window)
plot(evHiSrc, "LSM ev_hi_src", display = display.data_window)
plot(evHiLvl, "LSM ev_hi_level", display = display.data_window)
plot(evLoCls, "LSM ev_lo_cls", display = display.data_window)
plot(evLoSrc, "LSM ev_lo_src", display = display.data_window)
plot(evLoLvl, "LSM ev_lo_level", display = display.data_window)
plot(chConfHi, "LSM ch_conf_hi", display = display.data_window)
plot(chConfLo, "LSM ch_conf_lo", display = display.data_window)
plot(nActive, "LSM n_active", display = display.data_window)