Liquidation Map: Where Leverage Goes Boom

ProofCharts · study · 320 行 · 点赞 19 · 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/
// © ProofCharts
//@version=6
indicator("Liquidation Map: Where Leverage Goes Boom", shorttitle = "Liquidation Map", overlay = true, max_bars_back = 1100, max_labels_count = 40, max_lines_count = 40, max_boxes_count = 120)
 
// Shows, in plain words, the price where a leveraged position would be liquidated (isolated margin estimate) and how
// often that would have happened on this chart. Pine cannot see real exchange liquidations. Not advice.
 
G_POS = "Your position"
G_HIST = "History check"
G_ADV = "Advanced (most people leave this as it is)"
 
iLev   = input.int(20, "Leverage", options = [2, 3, 5, 10, 20, 25, 50, 75, 100, 125], group = G_POS, tooltip = "Leverage = trading with borrowed money. 20x means you put in 1 dollar and borrow 19. Try a few values and watch how close the BOOM line gets.")
iSide  = input.string("Both", "Buy or sell", options = ["Buy (long)", "Sell (short)", "Both"], group = G_POS, tooltip = "Buy (long): you win when the price goes up. Sell (short): you win when the price goes down. Both = show both.")
iEntry = input.float(0.0, "Entry price (0 = current price)", minval = 0, group = G_POS, tooltip = "The price where you get in. Leave 0 to use the current price. Then the lines move with the price.")
iK     = input.int(500, "How many past candles to check", minval = 10, maxval = 1000, group = G_HIST, tooltip = "For each of these past candles, the script pretends a trade was opened at its close. Then it checks if that trade was wiped out.")
iH     = input.int(24, "Wiped out within how many candles", minval = 1, maxval = 50, group = G_HIST, tooltip = "A past trade counts as wiped out if the price reached its BOOM line within this many candles.")
G_ALL = "All leverage lines (different colours)"
iAll   = input.bool(true, "Show a BOOM line for every leverage", group = G_ALL, tooltip = "The BOOM line is the price where the money in your trade is gone. Turn this on to draw it for every leverage (borrowing level) ticked below.")
iL5    = input.bool(true, "5x", group = G_ALL, inline = "a")
iL10   = input.bool(true, "10x", group = G_ALL, inline = "a")
iL20   = input.bool(true, "20x", group = G_ALL, inline = "a")
iL25   = input.bool(true, "25x", group = G_ALL, inline = "a")
iL50   = input.bool(true, "50x", group = G_ALL, inline = "b")
iL75   = input.bool(true, "75x", group = G_ALL, inline = "b")
iL100  = input.bool(true, "100x", group = G_ALL, inline = "b")
iL125  = input.bool(true, "125x", group = G_ALL, inline = "b")
G_HEAT = "Guess of liquidation zones (heatmap)"
iHeat  = input.bool(true, "Show the heatmap", group = G_HEAT, tooltip = "A guess of where trades opened on recent candles would be wiped out (liquidated), at prices not reached yet. It uses this chart's prices and volume, not exchange data.")
iHK    = input.int(300, "Candles used", minval = 10, maxval = 1000, group = G_HEAT, tooltip = "How many recent candles the heatmap uses. Each one adds imagined buys and sells opened at its close.", active = iHeat)
iBins  = input.int(50, "Rows in the heatmap", minval = 10, maxval = 100, group = G_HEAT, tooltip = "How many rows the heatmap has. More rows = thinner rows.", active = iHeat)
iRange = input.float(25.0, "Heatmap reach above and below price (%)", minval = 1, maxval = 50, group = G_HEAT, tooltip = "How far above and below the current price the heatmap reaches. 25 = from 25% below to 25% above.", active = iHeat)
iVolW  = input.bool(true, "Weight by volume", group = G_HEAT, tooltip = "Volume = how much was traded. On: candles with more volume count more. Off: every candle counts the same.", active = iHeat)
iDebug = input.bool(false, "Show the number behind each row (for checking)", group = G_HEAT, tooltip = "Shows the number behind each heatmap row. Most people leave this off.", active = iHeat)
iMm    = input.float(0.5, "Exchange safety buffer (maintenance margin %)", minval = 0, maxval = 10, step = 0.1, group = G_ADV, tooltip = "Maintenance margin = the small part of the trade your exchange keeps as a safety buffer. 0.5% is common for small positions.")
 
// Price comparisons use the sign of the difference: exact at any price (crypto down to 1e-8), also where floats
// are compared with an absolute tolerance (PineTS: 1e-10). Crypto amendment 2026-10-24.
gt(float a, float b) => math.sign(a - b) > 0
ge(float a, float b) => math.sign(a - b) >= 0
float mm = iMm / 100
float entry = iEntry > 0 ? iEntry : close
bool atEntry = 1.0 / iLev <= mm
float longLiq = atEntry ? entry : entry * (1 - 1.0 / iLev + mm)
float shortLiq = atEntry ? entry : entry * (1 + 1.0 / iLev - mm)
float movePct = atEntry ? 0.0 : 100 * (1.0 / iLev - mm)
float atr = ta.atr(14)
float longCandles = math.sign(atr) > 0 ? (entry - longLiq) / atr : na
float shortCandles = math.sign(atr) > 0 ? (shortLiq - entry) / atr : na
 
// Share of past entries (at a closed candle's close) that would have been liquidated within iH candles.
wipedPct(int lev, bool isLong) =>
    int n = 0
    int w = 0
    for e = iH + 1 to iH + iK
        if e > bar_index
            break
        float ent = close[e]
        float liq = 1.0 / lev <= mm ? ent : isLong ? ent * (1 - 1.0 / lev + mm) : ent * (1 + 1.0 / lev - mm)
        bool hit = false
        for j = e - iH to e - 1
            if isLong ? ge(liq, low[j]) : ge(high[j], liq)
                hit := true
                break
        n += 1
        w += hit ? 1 : 0
    [n > 0 ? 100.0 * w / n : na, n]
 
float lw = na
float sw = na
float checked = na
float lw5 = na
float sw5 = na
float lw10 = na
float sw10 = na
float lw20 = na
float sw20 = na
float lw50 = na
float sw50 = na
float lw100 = na
float sw100 = na
if barstate.islast
    [a, n] = wipedPct(iLev, true)
    [b, _n] = wipedPct(iLev, false)
    lw := a
    sw := b
    checked := n
    [x1, _1] = wipedPct(5, true)
    [y1, _2] = wipedPct(5, false)
    [x2, _3] = wipedPct(10, true)
    [y2, _4] = wipedPct(10, false)
    [x3, _5] = wipedPct(20, true)
    [y3, _6] = wipedPct(20, false)
    [x4, _7] = wipedPct(50, true)
    [y4, _8] = wipedPct(50, false)
    [x5, _9] = wipedPct(100, true)
    [y5, _10] = wipedPct(100, false)
    lw5 := x1
    sw5 := y1
    lw10 := x2
    sw10 := y2
    lw20 := x3
    sw20 := y3
    lw50 := x4
    sw50 := y4
    lw100 := x5
    sw100 := y5
 
plot(longLiq, "Long liquidation", display = display.data_window)
plot(shortLiq, "Short liquidation", display = display.data_window)
plot(movePct, "Move to liquidation %", display = display.data_window)
plot(longCandles, "Long normal candles", display = display.data_window)
plot(shortCandles, "Short normal candles", display = display.data_window)
plot(lw, "Long wiped %", display = display.data_window)
plot(sw, "Short wiped %", display = display.data_window)
plot(checked, "Entries checked", display = display.data_window)
plot(lw5, "Long wiped % 5x", display = display.data_window)
plot(sw5, "Short wiped % 5x", display = display.data_window)
plot(lw10, "Long wiped % 10x", display = display.data_window)
plot(sw10, "Short wiped % 10x", display = display.data_window)
plot(lw20, "Long wiped % 20x", display = display.data_window)
plot(sw20, "Short wiped % 20x", display = display.data_window)
plot(lw50, "Long wiped % 50x", display = display.data_window)
plot(sw50, "Short wiped % 50x", display = display.data_window)
plot(lw100, "Long wiped % 100x", display = display.data_window)
plot(sw100, "Short wiped % 100x", display = display.data_window)
 
// ---------- Every leverage at once: one colour per leverage, from yellow (far) to purple (close) ----------
var array<int> allLev = array.from(5, 10, 20, 25, 50, 75, 100, 125)
var array<color> allCol = array.from(#facc15, #f59e0b, #f97316, #ef4444, #e11d48, #db2777, #c026d3, #7c3aed)
array<bool> allOn = array.from(iL5, iL10, iL20, iL25, iL50, iL75, iL100, iL125)
var array<line> buyLines = array.new_line()
var array<line> sellLines = array.new_line()
var array<label> buyLabels = array.new_label()
var array<label> sellLabels = array.new_label()
if barstate.isfirst
    for i = 0 to 7
        color c = array.get(allCol, i)
        array.push(buyLines, line.new(na, na, na, na, extend = extend.right, color = c, style = line.style_solid, width = 1))
        array.push(sellLines, line.new(na, na, na, na, extend = extend.right, color = c, style = line.style_dotted, width = 1))
        array.push(buyLabels, label.new(na, na, "", style = label.style_label_left, color = c, textcolor = color.black, size = size.tiny))
        array.push(sellLabels, label.new(na, na, "", style = label.style_label_left, color = c, textcolor = color.black, size = size.tiny))
liqBuy(int lev) => 1.0 / lev <= mm ? entry : entry * (1 - 1.0 / lev + mm)
liqSell(int lev) => 1.0 / lev <= mm ? entry : entry * (1 + 1.0 / lev - mm)
plot(liqBuy(5), "Buy BOOM 5x", display = display.data_window)
plot(liqBuy(10), "Buy BOOM 10x", display = display.data_window)
plot(liqBuy(20), "Buy BOOM 20x", display = display.data_window)
plot(liqBuy(25), "Buy BOOM 25x", display = display.data_window)
plot(liqBuy(50), "Buy BOOM 50x", display = display.data_window)
plot(liqBuy(75), "Buy BOOM 75x", display = display.data_window)
plot(liqBuy(100), "Buy BOOM 100x", display = display.data_window)
plot(liqBuy(125), "Buy BOOM 125x", display = display.data_window)
plot(liqSell(5), "Sell BOOM 5x", display = display.data_window)
plot(liqSell(10), "Sell BOOM 10x", display = display.data_window)
plot(liqSell(20), "Sell BOOM 20x", display = display.data_window)
plot(liqSell(25), "Sell BOOM 25x", display = display.data_window)
plot(liqSell(50), "Sell BOOM 50x", display = display.data_window)
plot(liqSell(75), "Sell BOOM 75x", display = display.data_window)
plot(liqSell(100), "Sell BOOM 100x", display = display.data_window)
plot(liqSell(125), "Sell BOOM 125x", display = display.data_window)
if barstate.islast
    for i = 0 to 7
        int lev = array.get(allLev, i)
        bool on = iAll and array.get(allOn, i)
        float yb = on and iSide != "Sell (short)" ? liqBuy(lev) : na
        float ys = on and iSide != "Buy (long)" ? liqSell(lev) : na
        string mv = str.tostring(1.0 / lev <= mm ? 0.0 : 100 * (1.0 / lev - mm), "#.##") + "%"
        line.set_xy1(array.get(buyLines, i), bar_index - 40, yb)
        line.set_xy2(array.get(buyLines, i), bar_index, yb)
        line.set_xy1(array.get(sellLines, i), bar_index - 40, ys)
        line.set_xy2(array.get(sellLines, i), bar_index, ys)
        label.set_xy(array.get(buyLabels, i), bar_index + 12, yb)
        label.set_text(array.get(buyLabels, i), na(yb) ? "" : str.tostring(lev) + "x buy 💥 " + str.tostring(yb, format.mintick) + " (-" + mv + ")")
        label.set_xy(array.get(sellLabels, i), bar_index + 12, ys)
        label.set_text(array.get(sellLabels, i), na(ys) ? "" : str.tostring(lev) + "x sell 💥 " + str.tostring(ys, format.mintick) + " (+" + mv + ")")
 
// ---------- Estimated liquidation heatmap (snapshot on the last bar) ----------
var array<box> heatBoxes = array.new_box()
// Breaks a text into lines of at most n characters, at spaces only (no word is changed), so the panel fits the chart
// of a phone held upright (compliance/phone_fit.py; owner's Android screenshot 2026-11-03: wide panels were cut off).
wrapText(string s, int n) =>
    string out = ""
    int len = -1
    for w in str.split(s, " ")
        int wl = str.length(w)
        if len < 0
            out := w
            len := wl
        else if len + 1 + wl > n
            out := out + "\n" + w
            len := wl
        else
            out := out + " " + w
            len := len + 1 + wl
    out
var table dbg = table.new(position.bottom_left, 2, 101)
float heatTotal = na
float hotBelow = na
float hotAbove = na
float hotBelowShare = na
float hotAboveShare = na
if barstate.islast and iHeat
    float lo = close * (1 - iRange / 100)
    float hi = close * (1 + iRange / 100)
    float stepH = (hi - lo) / iBins
    array<float> w = array.new_float(iBins, 0.0)
    float runMin = low
    float runMax = high
    int nE = math.min(iHK, bar_index)
    for e = 1 to nE
        float ent = close[e]
        float vol = iVolW ? nz(volume[e], 1.0) : 1.0
        for i = 0 to 7
            if array.get(allOn, i)
                int lev = array.get(allLev, i)
                float ll = 1.0 / lev <= mm ? ent : ent * (1 - 1.0 / lev + mm)
                float sl = 1.0 / lev <= mm ? ent : ent * (1 + 1.0 / lev - mm)
                if gt(runMin, ll) and ge(ll, lo) and gt(hi, ll)
                    int bi = int(math.floor((ll - lo) / stepH))
                    array.set(w, bi, array.get(w, bi) + vol)
                if gt(sl, runMax) and ge(sl, lo) and gt(hi, sl)
                    int bj = int(math.floor((sl - lo) / stepH))
                    array.set(w, bj, array.get(w, bj) + vol)
        runMin := math.min(runMin, low[e])
        runMax := math.max(runMax, high[e])
    float tot = array.sum(w)
    float wMax = array.max(w)
    float bestB = 0.0
    float bestA = 0.0
    int iB = -1
    int iA = -1
    for b in heatBoxes
        box.delete(b)
    array.clear(heatBoxes)
    for i = 0 to iBins - 1
        float wi = array.get(w, i)
        float mid = lo + (i + 0.5) * stepH
        if wi > 0
            if gt(close, mid) and wi > bestB
                bestB := wi
                iB := i
            if gt(mid, close) and wi > bestA
                bestA := wi
                iA := i
            float heat = wMax > 0 ? wi / wMax : 0
            color hc = color.from_gradient(heat, 0, 1, color.new(#3b0764, 75), color.new(#facc15, 25))
            array.push(heatBoxes, box.new(bar_index - math.min(iHK, bar_index), lo + (i + 1) * stepH, bar_index + 8, lo + i * stepH, border_color = na, bgcolor = hc))
        if iDebug
            table.cell(dbg, 0, i, str.tostring(i), text_size = size.tiny)
            table.cell(dbg, 1, i, str.tostring(wi), text_size = size.tiny)
    heatTotal := tot
    hotBelow := iB >= 0 ? lo + (iB + 0.5) * stepH : na
    hotAbove := iA >= 0 ? lo + (iA + 0.5) * stepH : na
    hotBelowShare := iB >= 0 and tot > 0 ? 100 * bestB / tot : na
    hotAboveShare := iA >= 0 and tot > 0 ? 100 * bestA / tot : na
plot(heatTotal, "Heat total weight", display = display.data_window)
plot(hotBelow, "Hottest below", display = display.data_window)
plot(hotAbove, "Hottest above", display = display.data_window)
plot(hotBelowShare, "Hottest below share %", display = display.data_window)
plot(hotAboveShare, "Hottest above share %", display = display.data_window)
 
// ---------- What you see ----------
color cBoom = #ef4444
color cShort = #f59e0b
color cTxt = #e2e8f0
color cMuted = #94a3b8
bool showLong = iSide != "Sell (short)"
bool showShort = iSide != "Buy (long)"
var line lnL = line.new(na, na, na, na, extend = extend.right, color = cBoom, style = line.style_dashed, width = 2)
var line lnS = line.new(na, na, na, na, extend = extend.right, color = cShort, style = line.style_dashed, width = 2)
var label lbL = label.new(na, na, "", style = label.style_label_left, color = cBoom, textcolor = color.white, size = size.normal)
var label lbS = label.new(na, na, "", style = label.style_label_left, color = cShort, textcolor = color.black, size = size.normal)
var box zoneL = box.new(na, na, na, na, bgcolor = color.new(cBoom, 85), border_color = na)
var box zoneS = box.new(na, na, na, na, bgcolor = color.new(cShort, 88), border_color = na)
var table t = table.new(position.top_right, 4, 10, bgcolor = color.new(#0f172a, 5), frame_color = color.new(cMuted, 70), frame_width = 1)
 
if barstate.isfirst
    table.merge_cells(t, 0, 0, 3, 0)
    table.merge_cells(t, 0, 1, 3, 1)
    table.merge_cells(t, 0, 2, 3, 2)
    table.merge_cells(t, 0, 9, 3, 9)
 
num(float x) => str.tostring(x, format.mintick)
pct(float x) => na(x) ? "-" : str.tostring(x, "#.#") + "%"
cand(float x) => na(x) ? "" : " ≈ " + str.tostring(x, "#.#") + " normal candles"
 
if barstate.islast
    float yL = showLong ? longLiq : na
    float yS = showShort ? shortLiq : na
    line.set_xy1(lnL, bar_index, yL)
    line.set_xy2(lnL, bar_index + 1, yL)
    line.set_xy1(lnS, bar_index, yS)
    line.set_xy2(lnS, bar_index + 1, yS)
    label.set_xy(lbL, bar_index + 3, yL)
    label.set_text(lbL, na(yL) ? "" : "💥 BOOM line for a " + str.tostring(iLev) + "x BUY\nPrice falls to " + num(longLiq) + " = your money is gone\nOnly -" + str.tostring(movePct, "#.##") + "%" + cand(longCandles))
    label.set_xy(lbS, bar_index + 3, yS)
    label.set_text(lbS, na(yS) ? "" : "💥 BOOM line for a " + str.tostring(iLev) + "x SELL\nPrice rises to " + num(shortLiq) + " = your money is gone\nOnly +" + str.tostring(movePct, "#.##") + "%" + cand(shortCandles))
    box.set_lefttop(zoneL, bar_index - 30, showLong ? entry : na)
    box.set_rightbottom(zoneL, bar_index + 2, yL)
    box.set_lefttop(zoneS, bar_index - 30, yS)
    box.set_rightbottom(zoneS, bar_index + 2, showShort ? entry : na)
    table.cell(t, 0, 0, wrapText("LIQUIDATION, SIMPLY", 20), text_color = color.white, bgcolor = color.new(cBoom, 10), text_size = size.normal)
    table.cell(t, 0, 1, wrapText("Leverage is like a balloon: more air, faster pop. " + str.tostring(iLev) + "x = you put in 1 and borrow " + str.tostring(iLev - 1) + ".", 30), text_color = cTxt, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 0, 2, wrapText("On this chart a " + str.tostring(iLev) + "x buy from a past candle went boom within " + str.tostring(iH) + " candles " + pct(lw) + " of the time (sell: " + pct(sw) + ").", 30), text_color = cTxt, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 0, 3, wrapText("Leverage", 9), text_color = cMuted, text_size = size.small)
    table.cell(t, 1, 3, wrapText("Move to boom", 9), text_color = cMuted, text_size = size.small)
    table.cell(t, 2, 3, wrapText("Buy went boom", 9), text_color = cMuted, text_size = size.small)
    table.cell(t, 3, 3, wrapText("Sell went boom", 9), text_color = cMuted, text_size = size.small)
    array<int> levs = array.from(5, 10, 20, 50, 100)
    array<float> lws = array.from(lw5, lw10, lw20, lw50, lw100)
    array<float> sws = array.from(sw5, sw10, sw20, sw50, sw100)
    for i = 0 to 4
        int L = array.get(levs, i)
        float mv = 1.0 / L <= mm ? 0.0 : 100 * (1.0 / L - mm)
        color rowc = L == iLev ? color.new(cBoom, 70) : na
        table.cell(t, 0, 4 + i, str.tostring(L) + "x", text_color = color.white, bgcolor = rowc, text_size = size.small)
        table.cell(t, 1, 4 + i, str.tostring(mv, "#.##") + "%", text_color = cTxt, bgcolor = rowc, text_size = size.small)
        table.cell(t, 2, 4 + i, pct(array.get(lws, i)), text_color = cTxt, bgcolor = rowc, text_size = size.small)
        table.cell(t, 3, 4 + i, pct(array.get(sws, i)), text_color = cTxt, bgcolor = rowc, text_size = size.small)
    table.cell(t, 0, 9, wrapText("An estimate: only the money in this trade can be lost (isolated margin). Real exchanges also add fees, funding and stricter rules for big trades. Not advice.", 36), text_color = cMuted, text_size = size.tiny, text_halign = text.align_left)

← 返回列表