M-Alpha-Heatmap - Estimated Liquidation Zones

MAlphaCore · study · 254 行 · 点赞 15 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MAlphaCore
 
//@version=6
// M·Alpha·Heatmap — estimated liquidation zones (long liquidations below price, short liquidations above)
// Data: Binance open interest of the base coin (when available) plus volume; otherwise volume only.
// On every confirmed bar: estimate newly opened positions, compute the liquidation price for each selected
// leverage tier and accumulate it into price zones. A zone is removed once price reaches it.
indicator("M·Alpha·Heatmap", shorttitle = "M·Alpha·Heatmap", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ───────────────────────────── Data ─────────────────────────────
grData      = "Data"
useOi       = input.bool(true, "Use Binance open interest (when available)", group = grData)
volShare    = input.float(10.0, "Without open interest: share of volume treated as new positions (%)", minval = 0.1, maxval = 100, step = 0.5, group = grData)
longShareUp = input.float(60.0, "Long share on rising candles (%)", minval = 0, maxval = 100, step = 5, group = grData)
decayPct    = input.float(0.0, "Decay per bar (%)", minval = 0, maxval = 10, step = 0.1, group = grData, tooltip = "Older zones lose this share of weight on every bar. 0 = off.")
triggerMode = input.string("Wick", "Zone is triggered by", options = ["Wick", "Close"], group = grData)
zoneWidth   = input.float(0.25, "Zone width (% of price)", minval = 0.02, maxval = 2, step = 0.01, group = grData)
calcBars    = input.int(3000, "Calculate over the last bars", minval = 200, maxval = 20000, group = grData, tooltip = "More bars = more historical zones, but slower.")
 
grLev = "Leverage tiers (weight in %)"
w5    = input.float(15, "5×",   minval = 0, maxval = 100, group = grLev, inline = "a")
w10   = input.float(30, "10×",  minval = 0, maxval = 100, group = grLev, inline = "a")
w25   = input.float(25, "25×",  minval = 0, maxval = 100, group = grLev, inline = "b")
w50   = input.float(20, "50×",  minval = 0, maxval = 100, group = grLev, inline = "b")
w100  = input.float(10, "100×", minval = 0, maxval = 100, group = grLev, inline = "c")
 
// ───────────────────────────── Style ─────────────────────────────
grStyle    = "Style"
drawMode   = input.string("Lines", "Display", options = ["Cloud", "Lines", "Cloud + Lines"], group = grStyle)
zoneCount  = input.int(25, "Strongest zones per side", minval = 5, maxval = 240, group = grStyle)
minPct     = input.float(15.0, "Only zones from (% of strongest)", minval = 0, maxval = 90, step = 1, group = grStyle)
nearCount  = input.int(10, "Always show nearest zones per side", minval = 0, maxval = 50, group = grStyle, tooltip = "Zones closest to the current price are shown even when they are small compared with the strongest zones.")
colorMode  = input.string("One color per side", "Colors", options = ["One color per side", "Gradient cold → hot"], group = grStyle)
colLong    = input.color(#ffeb3b, "Long liquidations (below price)", group = grStyle)
colShort   = input.color(#b2b5be, "Short liquidations (above price)", group = grStyle)
colCold    = input.color(#1e2a44, "Gradient: cold", group = grStyle, inline = "g")
colHot     = input.color(#ffffff, "hot", group = grStyle, inline = "g")
transWeak  = input.int(90, "Transparency of weak zones", minval = 0, maxval = 100, group = grStyle)
transStrong = input.int(20, "Transparency of strong zones", minval = 0, maxval = 100, group = grStyle)
lineStyleIn = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = grStyle)
lineWidth  = input.int(1, "Line width", minval = 1, maxval = 5, group = grStyle)
showBorder = input.bool(false, "Border around clouds", group = grStyle)
extendRight = input.int(30, "Extend to the right (bars)", minval = 0, maxval = 500, group = grStyle)
lookBack   = input.int(1500, "Draw zones at most this far back (bars)", minval = 50, maxval = 4900, group = grStyle)
 
grLabel     = "Labels"
showAmount  = input.bool(true, "Show amounts", group = grLabel)
labelMode   = input.string("Nearest to price", "Which zones to label", options = ["Nearest to price", "Strongest", "All shown"], group = grLabel)
amountCount = input.int(10, "How many to label (per side)", minval = 0, maxval = 30, group = grLabel)
mergeGap    = input.float(0.3, "Merge labels closer than (% of price)", minval = 0, maxval = 5, step = 0.1, group = grLabel, tooltip = "Labels this close to each other are combined into one (amounts added up). 0 = never merge.")
textSizeIn  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grLabel)
colText     = input.color(#e8eaf0, "Text color", group = grLabel)
showLegend  = input.bool(true, "Show legend", group = grLabel)
legendPos   = input.string("Top right", "Legend position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grLabel)
 
// ───────────────────────────── Data source ─────────────────────────────
oiSymbol = "BINANCE:" + syminfo.basecurrency + "USDT.P_OI"
oiValue  = request.security(oiSymbol, timeframe.period, close, ignore_invalid_symbol = true)
hasOi    = useOi and not na(oiValue)
 
// New positions on this bar in USD
newUsd = hasOi ? math.max(nz(oiValue - oiValue[1]), 0.0) * close : nz(volume) * close * volShare / 100.0
 
// ───────────────────────────── Zone storage ─────────────────────────────
var step = math.log(1 + zoneWidth / 100.0)
keyOf(float p) => int(math.round(math.log(p) / step))
priceOf(int k) => math.exp(k * step)
 
var map<int, float> longZones  = map.new<int, float>()
var map<int, float> shortZones = map.new<int, float>()
var map<int, int>   longBorn   = map.new<int, int>()
var map<int, int>   shortBorn  = map.new<int, int>()
MAX_ZONES = 800
 
addZone(map<int, float> zones, map<int, int> born, float price, float amount) =>
    if price > 0 and amount > 0
        k = keyOf(price)
        zones.put(k, nz(zones.get(k)) + amount)
        if not born.contains(k)
            born.put(k, bar_index)
 
prune(map<int, float> zones, map<int, int> born) =>
    if zones.size() > MAX_ZONES
        ks = zones.keys()
        vs = zones.values()
        idx = array.sort_indices(vs, order.ascending)
        for i = 0 to zones.size() - MAX_ZONES - 1
            k = ks.get(idx.get(i))
            zones.remove(k)
            born.remove(k)
 
trigger(map<int, float> zones, map<int, int> born, bool isLong, float level) =>
    // Long liquidations sit below price: triggered when price falls to the zone; short liquidations the other way round
    ks = zones.keys()
    for k in ks
        p = priceOf(k)
        if (isLong and p >= level) or (not isLong and p <= level)
            zones.remove(k)
            born.remove(k)
 
if barstate.isconfirmed and bar_index > 1 and bar_index >= last_bar_index - calcBars
    lowLevel  = triggerMode == "Wick" ? low : close
    highLevel = triggerMode == "Wick" ? high : close
    trigger(longZones, longBorn, true, lowLevel)
    trigger(shortZones, shortBorn, false, highLevel)
    if decayPct > 0
        f = 1 - decayPct / 100.0
        for k in longZones.keys()
            longZones.put(k, longZones.get(k) * f)
        for k in shortZones.keys()
            shortZones.put(k, shortZones.get(k) * f)
    total = w5 + w10 + w25 + w50 + w100
    if newUsd > 0 and total > 0
        longShare = close >= open ? longShareUp / 100.0 : 1 - longShareUp / 100.0
        entry = hlc3
        levs    = array.from(5.0, 10.0, 25.0, 50.0, 100.0)
        weights = array.from(w5, w10, w25, w50, w100)
        for i = 0 to 4
            g = weights.get(i) / total
            if g > 0
                lev = levs.get(i)
                addZone(longZones, longBorn, entry * (1 - 0.95 / lev), newUsd * longShare * g)
                addZone(shortZones, shortBorn, entry * (1 + 0.95 / lev), newUsd * (1 - longShare) * g)
    prune(longZones, longBorn)
    prune(shortZones, shortBorn)
 
// ───────────────────────────── Drawing ─────────────────────────────
var array<box>   boxes  = array.new<box>()
var array<line>  lines  = array.new<line>()
var array<label> labels = array.new<label>()
 
lineStyle = lineStyleIn == "Solid" ? line.style_solid : lineStyleIn == "Dotted" ? line.style_dotted : line.style_dashed
textSize  = textSizeIn == "Tiny" ? size.tiny : textSizeIn == "Normal" ? size.normal : size.small
 
amountText(float v) =>
    v >= 1e9 ? str.tostring(v / 1e9, "#.##") + "B" : v >= 1e6 ? str.tostring(v / 1e6, "#.#") + "M" : v >= 1e3 ? str.tostring(v / 1e3, "#") + "K" : str.tostring(v, "#")
 
zoneColor(bool isLong, float strength) =>
    tr = transWeak - (transWeak - transStrong) * strength
    base = colorMode == "Gradient cold → hot" ? color.from_gradient(strength, 0, 1, colCold, colHot) : (isLong ? colLong : colShort)
    color.new(base, tr)
 
placeLabels(array<float> prices, array<float> values) =>
    // 1. choose which zones get a label
    pickP = array.new<float>()
    pickV = array.new<float>()
    m = prices.size()
    if labelMode == "All shown"
        for j = 0 to m - 1
            pickP.push(prices.get(j))
            pickV.push(values.get(j))
    else
        keyArr = array.new<float>()
        for j = 0 to m - 1
            keyArr.push(labelMode == "Nearest to price" ? math.abs(prices.get(j) - close) : -values.get(j))
        order_ = array.sort_indices(keyArr, order.ascending)
        for j = 0 to math.min(amountCount, m) - 1
            pickP.push(prices.get(order_.get(j)))
            pickV.push(values.get(order_.get(j)))
    // 2. sort by price and merge labels that are too close together
    if pickP.size() > 0
        byPrice = array.sort_indices(pickP, order.ascending)
        groupP = 0.0
        groupV = 0.0
        groupW = 0.0
        right = bar_index + extendRight
        for j = 0 to byPrice.size() - 1
            p = pickP.get(byPrice.get(j))
            v = pickV.get(byPrice.get(j))
            if groupV > 0 and (mergeGap <= 0 or (p - groupP / groupW) / p * 100 > mergeGap)
                labels.push(label.new(right, groupP / groupW, amountText(groupV), style = label.style_label_left, color = color.new(color.black, 100), textcolor = colText, size = textSize))
                groupP := 0.0
                groupV := 0.0
                groupW := 0.0
            groupP += p * v
            groupW += v
            groupV += v
        if groupV > 0
            labels.push(label.new(right, groupP / groupW, amountText(groupV), style = label.style_label_left, color = color.new(color.black, 100), textcolor = colText, size = textSize))
 
drawSide(map<int, float> zones, map<int, int> born, bool isLong, float maxValue) =>
    if zones.size() > 0 and maxValue > 0
        ks = zones.keys()
        vs = zones.values()
        idx = array.sort_indices(vs, order.descending)
        n = math.min(zoneCount, ks.size())
        // selection: the strongest zones plus the zones nearest to the current price
        pick = array.new<int>()
        isNear = array.new<bool>()
        for i = 0 to n - 1
            pick.push(idx.get(i))
            isNear.push(false)
        if nearCount > 0
            dist = array.new<float>()
            for k in ks
                dist.push(math.abs(priceOf(k) - close))
            byDist = array.sort_indices(dist, order.ascending)
            m = math.min(nearCount, ks.size())
            for j = 0 to m - 1
                d = byDist.get(j)
                pos = pick.indexof(d)
                if pos < 0
                    pick.push(d)
                    isNear.push(true)
                else
                    isNear.set(pos, true)
        shownPrice = array.new<float>()
        shownValue = array.new<float>()
        for i = 0 to pick.size() - 1
            k = ks.get(pick.get(i))
            v = vs.get(pick.get(i))
            near = isNear.get(i)
            // near zones stay readable even when they are small
            strength = near ? math.max(v / maxValue, 0.5) : v / maxValue
            if near or strength * 100 >= minPct
                bottom = priceOf(k) / (1 + zoneWidth / 200.0)
                top    = priceOf(k) * (1 + zoneWidth / 200.0)
                left   = math.max(nz(born.get(k), bar_index), bar_index - lookBack)
                right  = bar_index + extendRight
                c = zoneColor(isLong, strength)
                if drawMode != "Lines"
                    boxes.push(box.new(left, top, right, bottom, border_color = showBorder ? color.new(c, math.max(0, transStrong - 10)) : na, bgcolor = c))
                if drawMode != "Cloud"
                    lines.push(line.new(left, priceOf(k), right, priceOf(k), color = color.new(c, math.min(transStrong, 60)), style = lineStyle, width = lineWidth))
                shownPrice.push(priceOf(k))
                shownValue.push(v)
        if showAmount and amountCount > 0 and shownPrice.size() > 0
            placeLabels(shownPrice, shownValue)
 
if barstate.islast
    for b in boxes
        b.delete()
    for l in lines
        l.delete()
    for s in labels
        s.delete()
    boxes.clear()
    lines.clear()
    labels.clear()
    maxLong  = longZones.size() > 0 ? longZones.values().max() : 0.0
    maxShort = shortZones.size() > 0 ? shortZones.values().max() : 0.0
    maxAll = math.max(maxLong, maxShort)
    drawSide(longZones, longBorn, true, maxAll)
    drawSide(shortZones, shortBorn, false, maxAll)
 
// ───────────────────────────── Legend ─────────────────────────────
var table legend = table.new(legendPos == "Top left" ? position.top_left : legendPos == "Bottom right" ? position.bottom_right : legendPos == "Bottom left" ? position.bottom_left : position.top_right, 1, 3, bgcolor = color.new(#0f1218, 15), border_width = 0)
if barstate.islast and showLegend
    maxLong  = longZones.size() > 0 ? longZones.values().max() : 0.0
    maxShort = shortZones.size() > 0 ? shortZones.values().max() : 0.0
    table.cell(legend, 0, 0, "M·Alpha·Heatmap", text_color = colText, text_size = textSize)
    table.cell(legend, 0, 1, hasOi ? "Source: Binance open interest + volume" : "Estimate from volume only", text_color = hasOi ? colText : colShort, text_size = textSize)
    table.cell(legend, 0, 2, "Strongest zone: long $" + amountText(maxLong) + " · short $" + amountText(maxShort), text_color = colText, text_size = textSize)

← 返回列表