M-Alpha-Liquidation - Liquidation Price and Warning Levels

MAlphaCore · study · 119 行 · 点赞 30 · 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·Liquidation — liquidation price and early warning levels for a leveraged position, drawn on the chart.
// Click on the chart to set the entry, choose side, leverage and margin mode. The script draws entry, two warning
// levels (share of the way from entry to liquidation) and the liquidation price, and shows how much of the way is used.
// Formula: liq = entry - side * margin_available / size / (1 - mmr * side), maintenance margin = half of the initial
// margin at the asset's max leverage (Hyperliquid rule) or a manual rate.
indicator("M·Alpha·Liquidation", shorttitle = "M·Alpha·Liq", overlay = true, max_lines_count = 20, max_labels_count = 20)
 
// ───────────────────────────── Inputs ─────────────────────────────
grPos      = "Position"
sideIn     = input.string("Long", "Side", options = ["Long", "Short"], group = grPos)
entryTime  = input.time(timestamp("2026-01-01 00:00"), "Entry (click on chart)", confirm = true, group = grPos, inline = "e")
entryPrice = input.price(0.0, "", confirm = true, group = grPos, inline = "e")
lev        = input.float(3.0, "Leverage", minval = 1, maxval = 200, step = 0.5, group = grPos)
modeIn     = input.string("Isolated", "Margin mode", options = ["Isolated", "Cross"], group = grPos)
sizeUsd    = input.float(1000.0, "Position size in USD (Cross only)", minval = 1, group = grPos)
accountUsd = input.float(1000.0, "Account value in USD (Cross only)", minval = 1, group = grPos, tooltip = "Total equity of the (sub)account that backs this position in cross mode.")
 
grMm       = "Maintenance margin"
mmModeIn   = input.string("From max leverage", "Maintenance margin", options = ["From max leverage", "Manual (%)"], group = grMm, tooltip = "From max leverage: half of the initial margin at the asset's max leverage, e.g. 40x max = 1.25 %.")
maxLev     = input.float(40.0, "Max leverage of the asset", minval = 1, maxval = 200, group = grMm)
mmManual   = input.float(0.5, "Manual maintenance margin (%)", minval = 0, maxval = 50, step = 0.05, group = grMm)
 
grWarn     = "Warnings"
warn1      = input.float(50.0, "Warning 1 at (% of the way to liquidation)", minval = 1, maxval = 99, group = grWarn)
warn2      = input.float(75.0, "Warning 2 at (% of the way to liquidation)", minval = 1, maxval = 99, group = grWarn)
 
grStyle    = "Style"
colLong    = input.color(#ffeb3b, "Long", group = grStyle)
colShort   = input.color(#b2b5be, "Short", group = grStyle)
colWarn    = input.color(#e8eaf0, "Warning levels", group = grStyle)
colLiq     = input.color(#ffffff, "Liquidation", group = grStyle)
colText    = input.color(#e8eaf0, "Text color", group = grStyle)
textSizeIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grStyle)
tablePosIn = input.string("Top right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grStyle)
 
// ───────────────────────────── Calculation ─────────────────────────────
s     = sideIn == "Long" ? 1.0 : -1.0
mmr   = mmModeIn == "From max leverage" ? 1.0 / (2.0 * maxLev) : mmManual / 100.0
valid = entryPrice > 0
 
// margin available per coin of position size
qty         = modeIn == "Cross" ? sizeUsd / entryPrice : 1.0
notional    = entryPrice * qty
marginAvail = modeIn == "Cross" ? accountUsd - mmr * sizeUsd : notional / lev - mmr * notional
liqRaw      = entryPrice - s * (marginAvail / qty) / (1 - mmr * s)
hasLiq      = valid and liqRaw > 0 and (s > 0 ? liqRaw < entryPrice : liqRaw > entryPrice)
liq         = hasLiq ? liqRaw : na
w1          = hasLiq ? entryPrice + (liq - entryPrice) * warn1 / 100.0 : na
w2          = hasLiq ? entryPrice + (liq - entryPrice) * warn2 / 100.0 : na
 
// share of the way to liquidation used by the current price (0 % = at entry, 100 % = liquidated)
used = hasLiq ? math.max(0.0, (entryPrice - close) / (entryPrice - liq) * 100.0) : na
afterEntry = time >= entryTime
 
// ───────────────────────────── Alerts ─────────────────────────────
reached(float level) => s > 0 ? low <= level : high >= level
r1 = reached(w1)
r2 = reached(w2)
rL = reached(liq)
hit1 = hasLiq and afterEntry and r1 and not r1[1]
hit2 = hasLiq and afterEntry and r2 and not r2[1]
hitL = hasLiq and afterEntry and rL and not rL[1]
alertcondition(hit1, "Warning 1 reached", "M·Alpha·Liquidation: warning 1 reached on {{ticker}}")
alertcondition(hit2, "Warning 2 reached", "M·Alpha·Liquidation: warning 2 reached on {{ticker}}")
alertcondition(hitL, "Liquidation price reached", "M·Alpha·Liquidation: liquidation price reached on {{ticker}}")
 
// ───────────────────────────── Drawing ─────────────────────────────
textSize = textSizeIn == "Tiny" ? size.tiny : textSizeIn == "Normal" ? size.normal : size.small
tablePos = tablePosIn == "Top left" ? position.top_left : tablePosIn == "Bottom right" ? position.bottom_right : tablePosIn == "Bottom left" ? position.bottom_left : position.top_right
colSide  = s > 0 ? colLong : colShort
fmt(float p) => str.tostring(p, format.mintick)
distPct(float p) => (p / entryPrice - 1) * 100.0
 
var array<line>  lines  = array.new<line>()
var array<label> labels = array.new<label>()
var table t = table.new(tablePos, 2, 6, bgcolor = color.new(#0f1218, 15), border_width = 0)
 
// lines start at the entry, but never further back than 200 bars so they also render on short previews
x1 = math.max(entryTime, nz(time[200], entryTime))
 
level(float p, color c, int width, string st, string txt) =>
    lines.push(line.new(x1, p, time, p, xloc = xloc.bar_time, extend = extend.right, color = c, width = width, style = st))
    labels.push(label.new(bar_index + 3, p, txt, style = label.style_label_lower_left, color = color.new(color.black, 100), textcolor = c, size = textSize))
 
if barstate.islast
    for l in lines
        l.delete()
    for b in labels
        b.delete()
    lines.clear()
    labels.clear()
    if valid
        level(entryPrice, colSide, 2, line.style_solid, sideIn + " " + str.tostring(lev, "#.#") + "× · entry " + fmt(entryPrice))
        labels.push(label.new(entryTime, entryPrice, sideIn, xloc = xloc.bar_time, style = s > 0 ? label.style_label_up : label.style_label_down, color = colSide, textcolor = color.black, size = textSize))
    if hasLiq
        level(w1, colWarn, 1, line.style_dashed, "Warning " + str.tostring(warn1, "#") + " % · " + fmt(w1))
        level(w2, colWarn, 1, line.style_dashed, "Warning " + str.tostring(warn2, "#") + " % · " + fmt(w2))
        level(liq, colLiq, 2, line.style_solid, "Liquidation " + fmt(liq) + " (" + str.tostring(distPct(liq), "#.##") + " %)")
 
    table.cell(t, 0, 0, "M·Alpha·Liquidation", text_color = colText, text_size = textSize)
    table.cell(t, 1, 0, "", text_size = textSize)
    if not valid
        table.cell(t, 0, 1, "Set the entry: open the settings and click on the chart", text_color = colShort, text_size = textSize)
    else
        table.cell(t, 0, 1, "Position", text_color = colText, text_size = textSize)
        table.cell(t, 1, 1, sideIn + " " + str.tostring(lev, "#.#") + "× " + modeIn, text_color = colSide, text_size = textSize)
        table.cell(t, 0, 2, "Entry", text_color = colText, text_size = textSize)
        table.cell(t, 1, 2, fmt(entryPrice), text_color = colText, text_size = textSize)
        table.cell(t, 0, 3, "Liquidation", text_color = colText, text_size = textSize)
        table.cell(t, 1, 3, hasLiq ? fmt(liq) + " (" + str.tostring(distPct(liq), "#.##") + " %)" : "none (margin covers the full move)", text_color = colLiq, text_size = textSize)
        table.cell(t, 0, 4, "Way to liquidation used", text_color = colText, text_size = textSize)
        table.cell(t, 1, 4, hasLiq ? str.tostring(used, "#.#") + " %" : "–", text_color = hasLiq and used >= warn1 ? colLiq : colText, text_size = textSize)
        status = not hasLiq ? "No liquidation" : used >= 100 ? "Liquidation price reached" : used >= warn2 ? "Warning 2" : used >= warn1 ? "Warning 1" : "OK"
        table.cell(t, 0, 5, "Status", text_color = colText, text_size = textSize)
        table.cell(t, 1, 5, status, text_color = status == "OK" ? colLong : colLiq, text_size = textSize)

← 返回列表