Skip to content
ChartDeck ChartScript docs Account Open the terminal

Recipes: liquidations and positioning

Four scripts on leverage and positioning - open interest against price, funding extremes, nearby liquidation levels and Hyperliquid net longs and shorts.

Price tells you where the market is; positioning tells you who is in it and how stretched they are. These recipes read ChartDeck's derivatives data: open interest, funding, the liquidation model and Hyperliquid's position-labelled trades. Each one says which plan and which markets it needs, and what it shows when the data is not there.

RecipeWhat it doesWhat it teaches
Open interest against priceColors each bar by whether price and open interest rose or fell togetheroi.close, oi.usd, four-way conditions, bgcolor
Funding extremesAnnualized funding with a z-score, marking unusually crowded longs or shortsfunding.rate, funding.interval_hours, ta.stdev
Liquidation levels near the priceThe nearest long and short liquidation levels as lines, their distance in the legend, an alert when price gets closeliq.levels, barstate.islast, lines, legend items
Hyperliquid net longs and shortsPositions opened minus closed by Hyperliquid takers, per bar and summedhl.*, hl.coverage, a rolling sum
DataWhere it existsPlanWithout it
oi.close, oi.usdperpetuals of venues that publish open interestevery plan (history: your order-flow window)na; spot markets have none
funding.rateperpetualsevery planna on spot markets
liq.levelsthe liquidation model, plus observed positions on Hyperliquid, dYdX and Lighterevery plan (12 levels per side; 40 on Pro and Elite)an empty array
hl.*Hyperliquid perpetual charts, minute timeframes up to 1 dayPlus, Pro, Elitena on other venues and plans

#Open interest against price

Open interest is the number of open contracts. Read together with price it says who is acting: price up with OI up means new longs are opening, price up with OI down means shorts are closing (a squeeze), and so on. This script colors the background by those four cases and plots the OI change.

Data: oi.close / oi.usd of the chart's market. Plan: every plan. Without the data: on a spot market or a venue without open interest the series is na, the background stays clear and the legend says why.

#The script

ChartScriptOpen in editor
//@chartscript 1
indicator("OI against price", { format: format.volume })
const len = input.int(4, "Change over (bars)", { minval: 1, maxval: 200 })
const minPct = input.float(0.2, "Ignore OI changes under (%)", { minval: 0, step: 0.05 })

const oiPct = (oi.close - oi.close[len]) / oi.close[len] * 100
const pxUp = close > close[len]
const oiUp = oiPct > minPct
const oiDown = oiPct < -minPct

// the four cases
const longsOpen = pxUp && oiUp
const shortsClose = pxUp && oiDown
const shortsOpen = !pxUp && oiUp
const longsClose = !pxUp && oiDown

plot(oi.usd, "Open interest (USD)", color.accent, 2)
plot(oiPct, "OI change %", oiPct >= 0 ? color.up : color.down, { display: display.data_window })
bgcolor(longsOpen ? color.new(color.up, 80) : shortsClose ? color.new(color.up, 92) : shortsOpen ? color.new(color.down, 80) : longsClose ? color.new(color.down, 92) : na,
    { title: "Who is acting" })

No picture: this example reads ChartDeck’s recorded market data (open interest, funding, liquidations, trade prints, footprints, the order book or volume at price), which the picture’s candles do not carry. Open it in the editor to see it on a live chart.

#How it works

  1. oi.close is open interest in coins; oi.usd is the same in dollars, better for comparing coins.
  2. The change is in percent over len bars; changes smaller than minPct count as flat, so noise does not color the pane.
  3. Four named conditions keep the color logic readable: strong colors for positions opening, faint ones for positions closing.
  4. The percent change goes to the Data Window only (display.data_window), so the pane shows one line.

#Customize it

  • All venues together (Pro): oi.agg_usd instead of oi.usd.
  • Binance's figure on any chart: oi.ref_usd.
  • Turn the four cases into alerts with alert.on(longsOpen && barstate.isconfirmed, ...).

#Run it

Any perpetual chart, 5-minute to 1-day. Open interest arrives as samples; on a 1-minute chart several bars can share one sample, so use a longer len there.

#Concepts used

ChartDeck data, background color, display.

#Funding extremes

Funding is what longs pay shorts (or the reverse) to keep a perpetual near spot. Very positive funding means longs are crowded and paying up; very negative, the shorts. This script annualizes funding so venues with 1-hour and 8-hour intervals compare, then marks readings far from their recent average.

Data: funding.rate and funding.interval_hours of the chart's market. Plan: every plan. Without the data: on a spot market the series is na; nothing is drawn.

#The script

ChartScriptOpen in editor
//@chartscript 1
indicator("Funding extremes", { format: format.percent })
const len = input.int(90, "Average over (bars)", { minval: 10 })
const zLimit = input.float(2.0, "Extreme beyond this many deviations", { minval: 0.5, step: 0.25 })

// % per funding interval -> % per year, whatever the venue's interval
const hours = nz(funding.interval_hours, 8)
const apr = funding.rate * (24 / hours) * 365

const avg = ta.sma(apr, len)
const dev = ta.stdev(apr, len)
const z = dev > 0 ? (apr - avg) / dev : na
const crowdedLongs = z > zLimit
const crowdedShorts = z < -zLimit

plot(apr, "Funding, % a year", apr >= 0 ? color.up : color.down, { style: plot.style_columns })
plot(avg, "Average", color.muted, 1)
plot(z, "z-score", color.accent, { display: display.data_window })
plotshape(crowdedLongs, "Longs crowded", shape.triangledown, location.top, color.down, { size: size.tiny })
plotshape(crowdedShorts, "Shorts crowded", shape.triangleup, location.bottom, color.up, { size: size.tiny })
hline(0, "Zero", color.muted)
alert.on(crowdedLongs && !crowdedLongs[1], "Longs crowded", "{{ticker}}: funding is unusually high")
alert.on(crowdedShorts && !crowdedShorts[1], "Shorts crowded", "{{ticker}}: funding is unusually negative")

No picture: this example reads ChartDeck’s recorded market data (open interest, funding, liquidations, trade prints, footprints, the order book or volume at price), which the picture’s candles do not carry. Open it in the editor to see it on a live chart.

#How it works

  1. funding.rate is a percent per funding interval; funding.interval_hours is that interval (8 on most venues, 1 on Hyperliquid). nz(..., 8) gives the usual value where it is unknown.
  2. The z-score says how many standard deviations today's funding is from its own recent average: a relative test that works on any coin.
  3. crowdedLongs && !crowdedLongs[1] fires the alert once, when the condition starts, not on every bar it lasts.

#Customize it

  • The whole market's view (Pro): funding.agg_weighted, weighted by open interest, already in % per 8 hours.
  • Only settlement bars: wrap the marks in funding.settled.
  • Combine with the OI recipe above: crowded longs and open interest still rising.

#Run it

Any perpetual chart, 1-hour or 4-hour works best (funding changes slowly). Rates differ between venues; compare like with like.

#Concepts used

ChartDeck data, ta.stdev, levels, alerts.

#Liquidation levels near the price

The liquidation model estimates where leveraged positions would be forced out. Price often reaches for the nearest large cluster. This script finds the nearest long level below and short level above, draws them, writes their distance in the legend and has an alert for price coming within a few percent.

Data: liq.levels, the model plus observed positions where an exchange publishes them. Plan: every plan (12 levels per side; 40 on Pro and Elite). Without the data: the array is empty, no line is drawn and the legend says "no levels".

#The script

ChartScriptOpen in editor
//@chartscript 1
indicator("Nearest liquidation levels", { overlay: true })
const minUsd = input.float(1000000, "Ignore levels under (USD)", { minval: 0 })
const nearPct = input.float(1.0, "Alert within (%)", { minval: 0.1, step: 0.1 })

state below: line = na
state above: line = na
let distBelow: float = na
let distAbove: float = na

// liq.levels describes NOW: it is filled on the newest bar only
if (barstate.islast) {
    let bestBelow: float = na
    let bestAbove: float = na
    for (const lv of liq.levels()) {
        if (lv.notional >= minUsd) {
            if (lv.side == "long" && lv.price < close && (na(bestBelow) || lv.price > bestBelow)) {
                bestBelow = lv.price
            }
            if (lv.side == "short" && lv.price > close && (na(bestAbove) || lv.price < bestAbove)) {
                bestAbove = lv.price
            }
        }
    }
    line.delete(below)
    line.delete(above)
    if (!na(bestBelow)) {
        below = line.new(bar_index - 20, bestBelow, bar_index, bestBelow, { extend: extend.right, color: color.up, width: 2, style: line.style_dashed })
        distBelow = (close - bestBelow) / close * 100
    }
    if (!na(bestAbove)) {
        above = line.new(bar_index - 20, bestAbove, bar_index, bestAbove, { extend: extend.right, color: color.down, width: 2, style: line.style_dashed })
        distAbove = (bestAbove - close) / close * 100
    }
    legend.info(na(distBelow) && na(distAbove) ? "no levels" : "longs " + (na(distBelow) ? "-" : str.tostring(distBelow, "#.##") + "% below")
        + ", shorts " + (na(distAbove) ? "-" : str.tostring(distAbove, "#.##") + "% above"))
    legend.badge(liq.is_model() ? "Model estimate" : "Observed", "Liquidation levels are an estimate, not exchange data, unless marked observed.")
}

const near = (!na(distBelow) && distBelow <= nearPct) || (!na(distAbove) && distAbove <= nearPct)
alert.on(near, "Near a liquidation level", "{{ticker}} is within reach of a liquidation level ({{close}})")

No picture: this example reads ChartDeck’s recorded market data (open interest, funding, liquidations, trade prints, footprints, the order book or volume at price), which the picture’s candles do not carry. Open it in the editor to see it on a live chart.

#How it works

  1. liq.levels() is filled on the newest bar only, because it describes the model now; all work happens inside if (barstate.islast).
  2. Each level has price, side ("long" below the price, "short" above), notional and observed. The loop keeps the nearest of each side above a size floor.
  3. state lines survive between runs; deleting and re-creating them on each update keeps exactly two on the chart.
  4. distBelow and distAbove are let values declared at the top level, so the alert condition (which must be top level) can read what the if computed.
  5. legend.badge says plainly that the levels are a model estimate.

#Customize it

  • Only observed positions: add lv.observed && to the tests.
  • One side only: liq.levels("long").
  • Show every level above the floor instead of the nearest: push a line for each into a state array.

#Run it

Any perpetual chart. The levels follow the Liquidation panel's settings on that chart (window, pinned venue, observed layers). Script alerts run on ChartDeck's servers with the 7-day window over all venues.

#Concepts used

Liquidation data, drawings, legend items, alerts.

#Hyperliquid net longs and shorts

Hyperliquid publishes every trader's positions, so ChartDeck can label each trade by what the taker's position did: a long opened, a long closed, a short opened or a short closed. The net longs delta is longs opened minus longs closed; the net shorts delta the same for shorts. Rising net longs into a rally is fresh conviction; a rally on net shorts falling is mostly short covering.

Data: hl.*, Hyperliquid perpetual charts at minute timeframes up to 1 day. Plan: Plus, Pro and Elite. Without the data: on another venue or plan every hl value is na; the pane stays empty and the legend says why.

#The script

ChartScriptOpen in editor
//@chartscript 1
indicator("HL net longs and shorts", { format: format.volume })
const len = input.int(24, "Rolling sum over (bars)", { minval: 1, maxval: 500 })
const minCoverage = input.float(50, "Hide bars with coverage under (%)", { minval: 0, maxval: 100 })

// only bars where enough of the volume could be labelled
const ok = !na(hl.coverage) && hl.coverage >= minCoverage
const netLongs = ok ? hl.net_long_delta : na
const netShorts = ok ? hl.net_short_delta : na

plot(netLongs, "Net longs delta", netLongs >= 0 ? color.up : color.new(color.up, 60), { style: plot.style_columns })
plot(na(netShorts) ? na : -netShorts, "Net shorts delta (drawn below zero)", netShorts >= 0 ? color.down : color.new(color.down, 60), { style: plot.style_columns })
plot(math.sum(nz(netLongs), len), "Net longs, rolling", color.up, 2)
plot(-math.sum(nz(netShorts), len), "Net shorts, rolling (below zero)", color.down, 2)
plot(hl.coverage, "Coverage %", color.muted, { display: display.data_window })
hline(0, "Zero", color.muted)
if (barstate.islast && !na(hl.coverage)) {
    legend.info("coverage " + str.tostring(hl.coverage, "#") + "%")
}

No picture: this example reads ChartDeck’s recorded market data (open interest, funding, liquidations, trade prints, footprints, the order book or volume at price), which the picture’s candles do not carry. Open it in the editor to see it on a live chart.

#How it works

  1. hl.net_long_delta and hl.net_short_delta are in the base coin, per bar.
  2. hl.coverage is the share of the bar's taker volume whose trader's position was known. The rest is left out, never guessed; bars under minCoverage are hidden rather than shown with a misleading value.
  3. Net shorts are drawn below zero so the two sides do not overlap.
  4. math.sum(nz(x), len) is a rolling total over the last len bars.

#Customize it

  • The four parts on their own: hl.long_open, hl.long_close, hl.short_open, hl.short_close.
  • A positioning score: math.sum(nz(netLongs) - nz(netShorts), len).
  • Mark divergences: price higher than len bars ago while the rolling net longs fell.

#Run it

A Hyperliquid perpetual chart (for example BTC on Hyperliquid), 1-minute to 1-hour, on Plus or higher. The newest minutes can still rise in coverage as late reads arrive.

#Concepts used

ChartDeck data, math.sum, legend items.

Next

The ChartScript documentation is in English for now; translations will follow.