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.
| Recipe | What it does | What it teaches |
|---|---|---|
| Open interest against price | Colors each bar by whether price and open interest rose or fell together | oi.close, oi.usd, four-way conditions, bgcolor |
| Funding extremes | Annualized funding with a z-score, marking unusually crowded longs or shorts | funding.rate, funding.interval_hours, ta.stdev |
| Liquidation levels near the price | The nearest long and short liquidation levels as lines, their distance in the legend, an alert when price gets close | liq.levels, barstate.islast, lines, legend items |
| Hyperliquid net longs and shorts | Positions opened minus closed by Hyperliquid takers, per bar and summed | hl.*, hl.coverage, a rolling sum |
| Data | Where it exists | Plan | Without it |
|---|---|---|---|
oi.close, oi.usd | perpetuals of venues that publish open interest | every plan (history: your order-flow window) | na; spot markets have none |
funding.rate | perpetuals | every plan | na on spot markets |
liq.levels | the liquidation model, plus observed positions on Hyperliquid, dYdX and Lighter | every plan (12 levels per side; 40 on Pro and Elite) | an empty array |
hl.* | Hyperliquid perpetual charts, minute timeframes up to 1 day | Plus, Pro, Elite | na 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
//@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
oi.closeis open interest in coins;oi.usdis the same in dollars, better for comparing coins.- The change is in percent over
lenbars; changes smaller thanminPctcount as flat, so noise does not color the pane. - Four named conditions keep the color logic readable: strong colors for positions opening, faint ones for positions closing.
- 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_usdinstead ofoi.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
//@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
funding.rateis a percent per funding interval;funding.interval_hoursis that interval (8 on most venues, 1 on Hyperliquid).nz(..., 8)gives the usual value where it is unknown.- 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.
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
//@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
liq.levels()is filled on the newest bar only, because it describes the model now; all work happens insideif (barstate.islast).- Each level has
price,side("long"below the price,"short"above),notionalandobserved. The loop keeps the nearest of each side above a size floor. statelines survive between runs; deleting and re-creating them on each update keeps exactly two on the chart.distBelowanddistAboveareletvalues declared at the top level, so the alert condition (which must be top level) can read what theifcomputed.legend.badgesays 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
statearray.
#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
//@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
hl.net_long_deltaandhl.net_short_deltaare in the base coin, per bar.hl.coverageis the share of the bar's taker volume whose trader's position was known. The rest is left out, never guessed; bars underminCoverageare hidden rather than shown with a misleading value.- Net shorts are drawn below zero so the two sides do not overlap.
math.sum(nz(x), len)is a rolling total over the lastlenbars.
#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
lenbars 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.