本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ═══════════════════════════════════════════════════════════════════════════
// Stop Cluster Heatmap [ApexFlow] - by ApexFlow
//
// DESCRIPTION
// Estimates where resting stop orders may be stacked and paints a density
// heatmap to the right of price. Candidate stop levels come from swing
// highs/lows (three pivot lengths), previous day/week highs and lows, round
// numbers and equal highs/lows. Each level carries a weight that decays with
// age and is removed once price trades through it. Levels are binned into
// price rows around the current close; the more weight in a row, the wider
// and more opaque its box.
//
// IMPORTANT: this is a MODEL built from price structure only. It is NOT
// order-book data and does not show real orders. Treat it as a visual aid.
//
// This script is original work by ApexFlow. It is educational and makes no
// claim about future price behaviour.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Stop Cluster Heatmap [ApexFlow]", shorttitle = "Stop Clusters [ApexFlow]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
// ───────────────────────────── Inputs ─────────────────────────────
GRP_SW = "Swing pivots"
GRP_PDW = "Previous day / week"
GRP_RN = "Round numbers"
GRP_EQ = "Equal highs / lows"
GRP_LF = "Level lifecycle"
GRP_HM = "Heatmap"
GRP_ST = "Style"
useP1 = input.bool(true, "Pivot set 1", group = GRP_SW, inline = "p1")
p1Len = input.int(5, "Length", minval = 1, group = GRP_SW, inline = "p1")
p1W = input.float(1.0, "Weight", minval = 0.0, step = 0.1, group = GRP_SW, inline = "p1")
useP2 = input.bool(true, "Pivot set 2", group = GRP_SW, inline = "p2")
p2Len = input.int(10, "Length", minval = 1, group = GRP_SW, inline = "p2")
p2W = input.float(1.5, "Weight", minval = 0.0, step = 0.1, group = GRP_SW, inline = "p2")
useP3 = input.bool(true, "Pivot set 3", group = GRP_SW, inline = "p3")
p3Len = input.int(20, "Length", minval = 1, group = GRP_SW, inline = "p3")
p3W = input.float(2.0, "Weight", minval = 0.0, step = 0.1, group = GRP_SW, inline = "p3")
bufMult = input.float(0.1, "Stop offset (ATR multiples)", minval = 0.0, step = 0.05, group = GRP_SW, tooltip = "Stops are assumed to sit slightly beyond the swing: above highs, below lows. This is the distance, in ATRs.")
usePD = input.bool(true, "Previous day high/low", group = GRP_PDW, inline = "pd")
wPD = input.float(2.5, "Weight", minval = 0.0, step = 0.1, group = GRP_PDW, inline = "pd")
usePW = input.bool(true, "Previous week high/low", group = GRP_PDW, inline = "pw", tooltip = "Uses the completed prior period via request.security with lookahead on and a one-bar offset, so values do not repaint.")
wPW = input.float(3.0, "Weight", minval = 0.0, step = 0.1, group = GRP_PDW, inline = "pw")
useRN = input.bool(true, "Round numbers", group = GRP_RN, inline = "rn")
wRN = input.float(1.0, "Weight", minval = 0.0, step = 0.1, group = GRP_RN, inline = "rn")
rnStepIn = input.float(0.0, "Round number step", minval = 0.0, group = GRP_RN, tooltip = "0 = automatic. Auto picks a nice step (1, 2, 2.5 or 5 times a power of ten) close to the daily ATR. The nearest 3 levels each side of price are used.")
eqOn = input.bool(true, "Equal level bonus", group = GRP_EQ, tooltip = "When a new pivot lands within the tolerance of an active level on the same side, that level gets a bonus instead of a duplicate being added.")
eqTol = input.float(0.1, "Equal level tolerance (ATR multiples)", minval = 0.0, step = 0.05, group = GRP_EQ)
eqBonus = input.float(1.5, "Bonus weight", minval = 0.0, step = 0.1, group = GRP_EQ)
lifeBars = input.int(500, "Level lifetime (bars)", minval = 10, group = GRP_LF, tooltip = "Effective weight = weight x max(floor, 1 - age / lifetime). Levels older than 2 x lifetime are dropped.")
decayFlr = input.float(0.25, "Minimum decay factor", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_LF)
maxLvls = input.int(150, "Max stored levels", minval = 20, maxval = 500, group = GRP_LF, tooltip = "Oldest levels are dropped first when the cap is reached.")
atrLen = input.int(14, "ATR length", minval = 1, group = GRP_LF)
winMult = input.float(12.0, "Window (ATR multiples)", minval = 1.0, step = 0.5, group = GRP_HM, tooltip = "The heatmap spans close +/- this many ATRs.")
rows = input.int(30, "Rows", minval = 10, maxval = 100, group = GRP_HM, tooltip = "Number of price bins in the window.")
offs = input.int(5, "Offset (bars right of last bar)", minval = 0, maxval = 100, group = GRP_HM)
maxW = input.int(40, "Max width (bars)", minval = 1, maxval = 100, group = GRP_HM, tooltip = "Width of the densest row. Other rows scale relative to it.")
topN = input.int(2, "Labelled clusters per side", minval = 0, maxval = 10, group = GRP_HM)
showLbl = input.bool(true, "Show cluster tags", group = GRP_HM)
showPrice = input.bool(false, "Show price on tags", group = GRP_HM, tooltip = "Adds the cluster price to each tag. Off by default for a cleaner chart.")
showDist = input.bool(true, "Show distance (ATR) on tags", group = GRP_HM, tooltip = "How far the cluster is from current price, in ATRs.")
showLns = input.bool(true, "Extend lines across chart", group = GRP_HM, tooltip = "Draws a line from each labelled cluster back across the chart, so you can see where past price reacted to that level.")
lnExt = input.string("Left only", "Line direction", options = ["Left only", "Both ways"], group = GRP_HM)
colBuy = input.color(#F23645, "Buy-side liquidity (above price)", group = GRP_ST)
colSell = input.color(#089981, "Sell-side liquidity (below price)", group = GRP_ST)
segs = input.int(10, "Gradient segments per row", minval = 1, maxval = 12, group = GRP_ST, tooltip = "Each row fades from solid at the spine to transparent at its tip. More segments give a smoother fade.")
rowGap = input.float(0.12, "Row spacing", minval = 0.0, maxval = 0.4, step = 0.02, group = GRP_ST, tooltip = "Gap between rows as a fraction of row height.")
showDash = input.bool(true, "Show dashboard", group = GRP_ST)
dashPos = input.string("Bottom Right", "Dashboard position", options = ["Bottom Right", "Bottom Left", "Top Right", "Top Left"], group = GRP_ST)
// ───────────────────────────── State ─────────────────────────────
// Parallel arrays: one entry per active stop level.
var array<float> lvlPrice = array.new<float>()
var array<float> lvlWeight = array.new<float>()
var array<int> lvlSide = array.new<int>() // 1 = buy-side (above), -1 = sell-side (below)
var array<int> lvlBirth = array.new<int>() // bar index of the swing
var array<box> boxes = array.new<box>()
var array<label> lbls = array.new<label>()
var array<line> lns = array.new<line>()
var float topBuyLo = na // lower edge of densest buy-side cluster (last confirmed bar)
var float topSellHi = na // upper edge of densest sell-side cluster (last confirmed bar)
var float topBuyMid = na
var float topSellMid = na
// ───────────────────────────── Functions ─────────────────────────────
// Remove one level from all parallel arrays.
removeLevel(int i) =>
array.remove(lvlPrice, i)
array.remove(lvlWeight, i)
array.remove(lvlSide, i)
array.remove(lvlBirth, i)
// Add a level, or strengthen an existing one (equal highs/lows or multi-scale pivot).
addLevel(float p, float w, int side, int birth, float tol, float bonus, bool useBonus) =>
int hit = -1
int n = array.size(lvlPrice)
if n > 0
for k = 0 to n - 1
int i = n - 1 - k
bool sameSwing = array.get(lvlBirth, i) == birth
if hit < 0 and array.get(lvlSide, i) == side and (sameSwing or useBonus) and math.abs(array.get(lvlPrice, i) - p) <= tol
hit := i
if hit >= 0
// Same swing found by another pivot length: add its weight. Different swing: equal-level bonus.
float inc = array.get(lvlBirth, hit) == birth ? w : bonus
array.set(lvlWeight, hit, array.get(lvlWeight, hit) + inc)
else
array.push(lvlPrice, p)
array.push(lvlWeight, w)
array.push(lvlSide, side)
array.push(lvlBirth, birth)
// Age-decayed weight.
effW(float w, int birth) =>
w * math.max(decayFlr, 1.0 - (bar_index - birth) / float(lifeBars))
// Nice round-number step: 1, 2, 2.5, 5 x 10^n closest to raw.
niceStep(float raw) =>
float r = nz(raw, 0.0)
float res = syminfo.mintick
if r > 0
float pw = math.pow(10.0, math.floor(math.log10(r)))
float m = r / pw
float f = m < 1.5 ? 1.0 : m < 2.25 ? 2.0 : m < 3.75 ? 2.5 : m < 7.5 ? 5.0 : 10.0
res := math.max(f * pw, syminfo.mintick)
res
// Add weight w for price p into its bin (ignored when outside the window).
addBin(array<float> d, float p, float w, float lo, float binH, int nRows) =>
if binH > 0 and not na(p) and not na(w)
int idx = int(math.floor((p - lo) / binH))
if idx >= 0 and idx < nRows
array.set(d, idx, array.get(d, idx) + w)
// Build the density array for the window [lo, lo + nRows * binH].
buildBins(float lo, float binH, int nRows, float px, float rStep, float pdh, float pdl, float pwh, float pwl) =>
array<float> d = array.new<float>(nRows, 0.0)
int n = array.size(lvlPrice)
if n > 0
for i = 0 to n - 1
addBin(d, array.get(lvlPrice, i), effW(array.get(lvlWeight, i), array.get(lvlBirth, i)), lo, binH, nRows)
if usePD
if not na(pdh) and pdh > px
addBin(d, pdh, wPD, lo, binH, nRows)
if not na(pdl) and pdl < px
addBin(d, pdl, wPD, lo, binH, nRows)
if usePW
if not na(pwh) and pwh > px
addBin(d, pwh, wPW, lo, binH, nRows)
if not na(pwl) and pwl < px
addBin(d, pwl, wPW, lo, binH, nRows)
if useRN and rStep > 0
for k = 1 to 3
addBin(d, (math.floor(px / rStep) + k) * rStep, wRN, lo, binH, nRows)
addBin(d, (math.ceil(px / rStep) - k) * rStep, wRN, lo, binH, nRows)
d
// Indexes of the n densest bins on one side of price (buy-side = bin centre at/above price).
pickTop(array<float> d, int nRows, bool wantBuy, float px, float lo, float binH, int n) =>
array<int> res = array.new<int>()
array<float> work = array.copy(d)
if n > 0
for k = 1 to n
int best = -1
float bv = 0.0
for i = 0 to nRows - 1
float c = lo + (i + 0.5) * binH
bool isBuy = c >= px
float v = array.get(work, i)
if isBuy == wantBuy and v > bv
bv := v
best := i
if best >= 0
array.push(res, best)
array.set(work, best, 0.0)
res
// Box width in bars, proportional to density.
binWidth(float dv, float maxD) =>
int(math.max(1.0, math.round(maxW * dv / maxD)))
// Delete every drawing created by the previous redraw.
clearDrawings() =>
int nb = array.size(boxes)
if nb > 0
for k = 0 to nb - 1
box.delete(array.get(boxes, nb - 1 - k))
array.clear(boxes)
int nl = array.size(lbls)
if nl > 0
for k = 0 to nl - 1
label.delete(array.get(lbls, nl - 1 - k))
array.clear(lbls)
int nn = array.size(lns)
if nn > 0
for k = 0 to nn - 1
line.delete(array.get(lns, nn - 1 - k))
array.clear(lns)
// Row colour for one side at a given relative density (0-1).
heatCol(bool isBuy, float ratio) =>
isBuy ? colBuy : colSell
// Grade for a relative density: A+ is the densest cluster on the map.
strengthTxt(float ratio) =>
ratio >= 0.85 ? "A+ Major" : ratio >= 0.6 ? "A Strong" : ratio >= 0.35 ? "B Moderate" : "C Light"
// Pill tags and optional dashed lines for the top clusters on one side.
drawTop(array<float> dens, bool wantBuy, float lo, float binH, float maxD, float px, float a) =>
array<int> top = pickTop(dens, rows, wantBuy, px, lo, binH, topN)
int nt = array.size(top)
if nt > 0
for k = 0 to nt - 1
int bi = array.get(top, k)
float dv = array.get(dens, bi)
float ratio = dv / maxD
float mid = lo + (bi + 0.5) * binH
color c = heatCol(wantBuy, ratio)
string dist = str.tostring(math.abs(mid - px) / a, "0.0") + " ATR"
if showLbl
string txt = (wantBuy ? "▲ Buy-side liquidity " : "▼ Sell-side liquidity ") + strengthTxt(ratio) + (showPrice ? " · " + str.tostring(mid, format.mintick) : "") + (showDist ? " · " + dist : "")
string tip = (wantBuy ? "Buy-side liquidity: modelled stops of short sellers resting above price. A run above here would trigger them." : "Sell-side liquidity: modelled stops of buyers resting below price. A run below here would trigger them.") + "\nGrade: " + strengthTxt(ratio) + " (A+ = densest cluster on the map, C = light)\nPrice: " + str.tostring(mid, format.mintick) + "\nDistance from price: " + dist
array.push(lbls, label.new(x = bar_index + offs + binWidth(dv, maxD) + 1, y = mid, text = txt, xloc = xloc.bar_index, color = color.new(c, ratio >= 0.6 ? 0 : 30), style = label.style_label_left, textcolor = color.white, size = size.small, tooltip = tip))
if showLns
array.push(lns, line.new(x1 = bar_index + offs - 1, y1 = mid, x2 = bar_index + offs, y2 = mid, xloc = xloc.bar_index, extend = lnExt == "Both ways" ? extend.both : extend.left, color = color.new(c, 35), style = line.style_dashed, width = 1))
// ───────────────────────────── Series (global scope) ─────────────────────────────
float atrV = ta.atr(atrLen)
float ph1 = ta.pivothigh(high, p1Len, p1Len)
float pl1 = ta.pivotlow(low, p1Len, p1Len)
float ph2 = ta.pivothigh(high, p2Len, p2Len)
float pl2 = ta.pivotlow(low, p2Len, p2Len)
float ph3 = ta.pivothigh(high, p3Len, p3Len)
float pl3 = ta.pivotlow(low, p3Len, p3Len)
// Completed prior-period values: [1] offset + lookahead_on is the non-repainting pattern.
float pdH = request.security(syminfo.tickerid, "D", high[1], lookahead = barmerge.lookahead_on)
float pdL = request.security(syminfo.tickerid, "D", low[1], lookahead = barmerge.lookahead_on)
float pwH = request.security(syminfo.tickerid, "W", high[1], lookahead = barmerge.lookahead_on)
float pwL = request.security(syminfo.tickerid, "W", low[1], lookahead = barmerge.lookahead_on)
float dAtr = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
float rnStep = rnStepIn > 0 ? rnStepIn : niceStep(nz(dAtr, nz(atrV)))
// "Entered cluster" conditions use the clusters computed on the previous confirmed bar.
bool entBuy = not na(topBuyLo) and high >= topBuyLo and high[1] < topBuyLo
bool entSell = not na(topSellHi) and low <= topSellHi and low[1] > topSellHi
// ───────────────────────────── Level maintenance (confirmed bars) ─────────────────────────────
if barstate.isconfirmed
// 1) Remove levels that were taken or are too old (loop backwards).
int nLv = array.size(lvlPrice)
if nLv > 0
for k = 0 to nLv - 1
int i = nLv - 1 - k
float lp = array.get(lvlPrice, i)
int sd = array.get(lvlSide, i)
int age = bar_index - array.get(lvlBirth, i)
bool taken = (sd == 1 and high > lp) or (sd == -1 and low < lp)
if taken or age > 2 * lifeBars
removeLevel(i)
// 2) Add newly confirmed pivots (stop assumed just beyond the swing).
float tolV = eqOn ? eqTol * nz(atrV) : 0.0
float bufV = bufMult * nz(atrV)
if useP1 and not na(ph1)
addLevel(ph1 + bufV, p1W, 1, bar_index - p1Len, tolV, eqBonus, eqOn)
if useP1 and not na(pl1)
addLevel(pl1 - bufV, p1W, -1, bar_index - p1Len, tolV, eqBonus, eqOn)
if useP2 and not na(ph2)
addLevel(ph2 + bufV, p2W, 1, bar_index - p2Len, tolV, eqBonus, eqOn)
if useP2 and not na(pl2)
addLevel(pl2 - bufV, p2W, -1, bar_index - p2Len, tolV, eqBonus, eqOn)
if useP3 and not na(ph3)
addLevel(ph3 + bufV, p3W, 1, bar_index - p3Len, tolV, eqBonus, eqOn)
if useP3 and not na(pl3)
addLevel(pl3 - bufV, p3W, -1, bar_index - p3Len, tolV, eqBonus, eqOn)
// 3) Enforce the cap: drop the oldest levels first.
while array.size(lvlPrice) > maxLvls
removeLevel(0)
// 4) Densest clusters on each side for the alert logic (same binning as the heatmap).
if not na(atrV) and atrV > 0
float aLo = close - winMult * atrV
float aBinH = 2.0 * winMult * atrV / rows
array<float> aDens = buildBins(aLo, aBinH, rows, close, rnStep, pdH, pdL, pwH, pwL)
array<int> aBuy = pickTop(aDens, rows, true, close, aLo, aBinH, 1)
array<int> aSell = pickTop(aDens, rows, false, close, aLo, aBinH, 1)
topBuyLo := array.size(aBuy) > 0 ? aLo + array.get(aBuy, 0) * aBinH : na
topBuyMid := array.size(aBuy) > 0 ? aLo + (array.get(aBuy, 0) + 0.5) * aBinH : na
topSellHi := array.size(aSell) > 0 ? aLo + (array.get(aSell, 0) + 1) * aBinH : na
topSellMid := array.size(aSell) > 0 ? aLo + (array.get(aSell, 0) + 0.5) * aBinH : na
// ───────────────────────────── Alerts ─────────────────────────────
alertcondition(entBuy, "Price entered top buy-side cluster", "Price entered the densest modelled buy-side stop cluster")
alertcondition(entSell, "Price entered top sell-side cluster", "Price entered the densest modelled sell-side stop cluster")
if barstate.isconfirmed and (entBuy or entSell)
string msg = syminfo.ticker + ": "
if entBuy
msg += "price entered top modelled buy-side stop cluster near " + str.tostring(topBuyMid, format.mintick) + ". "
if entSell
msg += "price entered top modelled sell-side stop cluster near " + str.tostring(topSellMid, format.mintick) + ". "
alert(msg + "(Model, not order-book data)", alert.freq_once_per_bar_close)
// ───────────────────────────── Heatmap rendering ─────────────────────────────
var table dash = table.new(dashPos == "Bottom Right" ? position.bottom_right : dashPos == "Bottom Left" ? position.bottom_left : dashPos == "Top Right" ? position.top_right : position.top_left, 4, 5, bgcolor = color.new(#0E1117, 6), frame_color = #2A2E39, frame_width = 1, border_color = color.new(#2A2E39, 40), border_width = 1)
var bool dashMerged = false
// One dashboard row for the densest cluster on a side.
dashRow(int r, bool isBuy, array<float> dens, float lo, float binH, float maxD, float px) =>
array<int> t = pickTop(dens, rows, isBuy, px, lo, binH, 1)
color c = heatCol(isBuy, 1.0)
table.cell(dash, 0, r, isBuy ? "▲ Buy-side liquidity" : "▼ Sell-side liquidity", text_color = c, text_size = size.small, text_halign = text.align_left)
if array.size(t) > 0
int bi = array.get(t, 0)
float mid = lo + (bi + 0.5) * binH
float ratio = array.get(dens, bi) / maxD
table.cell(dash, 1, r, str.tostring(mid, format.mintick), text_color = #D1D4DC, text_size = size.small)
table.cell(dash, 2, r, (isBuy ? "+" : "−") + str.tostring(math.abs(mid - px) / atrV, "0.0") + " ATR", text_color = #B2B5BE, text_size = size.small)
table.cell(dash, 3, r, strengthTxt(ratio), text_color = color.white, text_size = size.small, bgcolor = color.new(c, ratio >= 0.6 ? 10 : 45))
else
table.cell(dash, 1, r, "none in range", text_color = #787B86, text_size = size.small)
table.cell(dash, 2, r, "", text_size = size.small)
table.cell(dash, 3, r, "", text_size = size.small)
if barstate.islast
clearDrawings()
if not na(atrV) and atrV > 0
float rLo = close - winMult * atrV
float rBinH = 2.0 * winMult * atrV / rows
float rHi = rLo + rows * rBinH
array<float> dens = buildBins(rLo, rBinH, rows, close, rnStep, pdH, pdL, pwH, pwL)
float maxD = array.max(dens)
int x0 = bar_index + offs
// Spine and current-price marker.
array.push(lns, line.new(x0 - 1, rLo, x0 - 1, rHi, xloc = xloc.bar_index, color = color.new(#787B86, 55), style = line.style_solid, width = 1))
array.push(lns, line.new(x0 - 1, close, x0 + maxW, close, xloc = xloc.bar_index, color = color.new(#787B86, 30), style = line.style_dotted, width = 1))
if maxD > 0
for i = 0 to rows - 1
float dv = array.get(dens, i)
if dv > 0
float ratio = dv / maxD
float bBot = rLo + i * rBinH
float bTop = bBot + rBinH
float pad = rBinH * rowGap
bool buySide = (bBot + bTop) * 0.5 >= close
color bc = heatCol(buySide, ratio)
int w = binWidth(dv, maxD)
int nSeg = math.max(1, math.min(segs, w))
int segW = int(math.floor(w / nSeg))
float baseT = 60.0 - 55.0 * ratio
for j = 0 to nSeg - 1
int sl = x0 + j * segW
int sr = j == nSeg - 1 ? x0 + w : sl + segW
int t = int(math.round(baseT + (90.0 - baseT) * j / nSeg))
array.push(boxes, box.new(left = sl, top = bTop - pad, right = sr, bottom = bBot + pad, xloc = xloc.bar_index, border_color = color.new(bc, 100), border_width = 0, bgcolor = color.new(bc, t)))
drawTop(dens, true, rLo, rBinH, maxD, close, atrV)
drawTop(dens, false, rLo, rBinH, maxD, close, atrV)
if showDash
if not dashMerged
table.merge_cells(dash, 0, 0, 3, 0)
table.merge_cells(dash, 0, 4, 3, 4)
dashMerged := true
table.cell(dash, 0, 0, "STOP LIQUIDITY · " + syminfo.ticker, text_color = color.white, text_size = size.normal, text_halign = text.align_left)
table.cell(dash, 0, 1, "Side", text_color = #787B86, text_size = size.tiny, text_halign = text.align_left)
table.cell(dash, 1, 1, "Densest at", text_color = #787B86, text_size = size.tiny)
table.cell(dash, 2, 1, "Distance", text_color = #787B86, text_size = size.tiny)
table.cell(dash, 3, 1, "Grade", text_color = #787B86, text_size = size.tiny)
dashRow(2, true, dens, rLo, rBinH, maxD, close)
dashRow(3, false, dens, rLo, rBinH, maxD, close)
table.cell(dash, 0, 4, "A+ Major · A Strong · B Moderate · C Light | modelled, not order-book data", text_color = #787B86, text_size = size.tiny, text_halign = text.align_left)