本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Alpine Quant
//@version=6
indicator("Alpine Quant · OI Pressure", shorttitle = "AQ OI Pressure", overlay = false, precision = 2, max_labels_count = 500)
// =====================================================================
// OI Pressure — Open Interest × directional volume
// Pane: columns = OI change per bar, color = buy/sell imbalance of futures volume
// Chart: scenario markers, estimated liquidations, Short squeeze / Long flush markers
// Table: current bar, pressure over the last N bars, live statistics on this chart
// OI: <exchange>:<ticker>_OI · Flow: intrabar close vs open (approximation, not taker flow)
// Spot: flow of the spot symbol + futures/spot basis
// =====================================================================
// ---------- Data sources ----------
string G_SRC = "Data sources"
string oiSymInput = input.string("", "OI symbol (empty = auto)", tooltip = "Empty: <exchange>:<ticker>_OI. For BYBIT:BTCUSDT.P this becomes BYBIT:BTCUSDT.P_OI. If the symbol returns no data, the table shows a warning.", group = G_SRC)
string oiUnitInput = input.string("", "OI units (label, empty = auto)", tooltip = "Empty: base coin of the chart symbol (BTC, ETH, ...) on Bybit and Binance; «(exchange units)» on other exchanges, where OI may be quoted in contracts or USD.", group = G_SRC)
string ltfInput = input.timeframe("", "Intrabar timeframe («Chart» = auto)", tooltip = "«Chart» (empty) = auto: chart ≤ 15m → 1m, ≤ 1h → 5m, ≤ 4h → 15m, ≤ 1D → 1h, above → 4h. Must be lower than the chart timeframe. The number of intrabars TradingView loads is limited (the limit depends on your plan), so a smaller intrabar timeframe means shorter history for flow, markers and statistics.", group = G_SRC)
string spotSymInput = input.string("", "Spot symbol (empty = auto)", tooltip = "Empty: BINANCE:<base coin>USDT, e.g. ETHUSDT.P → BINANCE:ETHUSDT. Enter a symbol manually if the auto symbol does not exist (e.g. 1000PEPEUSDT.P → BINANCE:PEPEUSDT; a 10/100/1000… price multiplier is detected automatically) or to use another exchange, e.g. BYBIT:ETHUSDT.", group = G_SRC)
// ---------- ΔOI pane ----------
enum DeltaMode
pct = "ΔOI, %"
units = "ΔOI, OI units"
string G_OI = "ΔOI pane"
DeltaMode deltaModeInput = input.enum(DeltaMode.pct, "Columns", group = G_OI)
int ampLenInput = input.int(20, "Average |ΔOI| length", minval = 1, group = G_OI)
bool showAmpInput = input.bool(true, "± average |ΔOI| lines", group = G_OI)
bool showThrInput = input.bool(true, "± scenario threshold dots (% mode only)", group = G_OI)
// ---------- Column coloring ----------
string G_COL = "Column color (flow imbalance)"
float neutralInput = input.float(0.10, "Neutral: |imbalance| <", minval = 0.0, maxval = 1.0, step = 0.01, group = G_COL)
float fullInput = input.float(0.60, "Strong: |imbalance| ≥", minval = 0.01, maxval = 1.0, step = 0.01, group = G_COL)
color bullColInput = input.color(#2EBD85, "Buying", group = G_COL)
color bearColInput = input.color(#F6465D, "Selling", group = G_COL)
color neutColInput = input.color(#787B86, "Neutral", group = G_COL)
color naColInput = input.color(#8D6E63, "No flow data", group = G_COL)
// ---------- Scenario thresholds ----------
string G_SC = "Scenario thresholds"
float minOiPctInput = input.float(0.5, "Min |ΔOI|, %", minval = 0.01, step = 0.05, group = G_SC)
float minImbInput = input.float(0.20, "Min |imbalance| (0–1)", minval = 0.01, maxval = 1.0, step = 0.01, group = G_SC)
int volLenInput = input.int(20, "Volume SMA length", minval = 1, group = G_SC)
float minVolRInput = input.float(1.0, "Min volume / volume SMA", minval = 0.01, step = 0.05, group = G_SC)
int atrLenInput = input.int(14, "ATR length", minval = 1, group = G_SC)
float flatKInput = input.float(0.25, "Flat bar: |close − open| ≤ k × ATR, k", minval = 0.0, step = 0.05, group = G_SC)
float minSigInput = input.float(1.5, "Min significance", minval = 0.0, step = 0.1, tooltip = "min(|ΔOI%| / threshold, |imbalance| / threshold, (volume/SMA) / threshold). 1.0 = every threshold is just met; 1.5 = every threshold exceeded by 50%.", group = G_SC)
float strongSigInput = input.float(2.5, "Strong marker: significance ≥", minval = 0.0, step = 0.1, tooltip = "Markers ▲▼ are drawn larger when significance reaches this value.", group = G_SC)
// ---------- Spot ----------
string G_SP = "Spot confirmation"
float spotMinInput = input.float(0.10, "Min |spot imbalance| to confirm", minval = 0.0, maxval = 1.0, step = 0.01, group = G_SP)
bool spotFilterInput = input.bool(false, "Show markers only when spot confirms", group = G_SP)
// ---------- Liquidations (estimate) ----------
string G_LQ = "Probable liquidations (estimate from OI, volume and range)"
bool liqOnInput = input.bool(true, "Show", group = G_LQ)
float liqOiKInput = input.float(1.8, "OI drop ≥ k × average |ΔOI|, k", minval = 0.1, step = 0.1, group = G_LQ)
float liqVolInput = input.float(1.8, "Volume ≥ x × volume SMA, x", minval = 0.1, step = 0.1, group = G_LQ)
float liqRngInput = input.float(1.3, "Bar range ≥ x × ATR, x", minval = 0.1, step = 0.1, group = G_LQ)
// ---------- Display ----------
enum MarkStyle
icons = "Colored markers"
words = "Text labels (repeats suppressed)"
hidden = "Off"
enum ViewMode
key = "Key events"
all = "All scenarios"
liq = "Liquidations only"
enum TSize
tiny = "Tiny"
small = "Small"
normal = "Normal"
large = "Large"
huge = "Huge"
enum TPos
tr = "Top right"
tl = "Top left"
mr = "Middle right"
br = "Bottom right"
bl = "Bottom left"
string G_V = "Display"
ViewMode viewInput = input.enum(ViewMode.key, "What to show on the chart", tooltip = "Key events: ▲▼ new positions, ✕ probable liquidations, SQZ / FLUSH. All scenarios: plus ● closing and ◆ absorption. Liquidations only: ✕, SQZ, FLUSH.", group = G_V)
bool showTableInput = input.bool(true, "Table", group = G_V)
TSize tSizeInput = input.enum(TSize.normal, "Table text size", group = G_V)
TPos tPosInput = input.enum(TPos.tr, "Table position", group = G_V)
int pressLenInput = input.int(20, "Pressure: last N bars", minval = 2, maxval = 500, group = G_V)
bool showLegendInput = input.bool(false, "Table: show legend", group = G_V)
bool tableClosedInput = input.bool(true, "Table uses last closed bar", group = G_V)
MarkStyle markStyleInput = input.enum(MarkStyle.icons, "Markers on price chart", group = G_V)
int relabelInput = input.int(10, "Text: same label at most every N bars", minval = 1, group = G_V)
string G_MC = "Marker colors"
color c1Input = input.color(#2962FF, "1 ▲ OI up + buying", group = G_MC)
color c2Input = input.color(#80D8FF, "2 ● Short covering", group = G_MC)
color c3Input = input.color(#FF6D00, "3 ▼ OI up + selling", group = G_MC)
color c4Input = input.color(#FFD600, "4 ● Long unwinding", group = G_MC)
color c5Input = input.color(#E040FB, "5 ◆ Buying absorbed", group = G_MC)
color c6Input = input.color(#76FF03, "6 ◆ Selling absorbed", group = G_MC)
color cLqInput = input.color(#FFFFFF, "✕ Probable liquidations", group = G_MC)
color cSqInput = input.color(#00E5FF, "SQZ Short squeeze", group = G_MC)
color cFlInput = input.color(#FFAB00, "FLUSH Long flush", group = G_MC)
string G_ST = "Live statistics (this chart)"
bool statOnInput = input.bool(true, "Show statistics row", group = G_ST)
int statWinInput = input.int(20, "Extreme held for N bars", minval = 2, maxval = 200, tooltip = "After a strong bar is engulfed by the next bar in the opposite direction: did price stay below the high of the two bars (for a green strong bar) for N bars?", group = G_ST)
// =====================================================================
// DATA: OI
// =====================================================================
string oiTicker = oiSymInput == "" ? syminfo.prefix + ":" + syminfo.ticker + "_OI" : oiSymInput
// Auto spot symbol and OI unit from the base coin of the chart symbol
string baseCoin = syminfo.basecurrency
string spotSym = spotSymInput != "" ? spotSymInput : baseCoin != "" ? "BINANCE:" + baseCoin + "USDT" : "BINANCE:" + str.replace(syminfo.ticker, ".P", "")
// OI is quoted in coins on Bybit and Binance; other exchanges may use contracts or USD
bool coinOi = syminfo.prefix == "BYBIT" or syminfo.prefix == "BINANCE"
string oiUnit = oiUnitInput != "" ? oiUnitInput : coinOi and baseCoin != "" ? baseCoin : "(exchange units)"
[oiReqClose, oiReqTime] = request.security(oiTicker, timeframe.period, [close, time], ignore_invalid_symbol = true)
bool oiFresh = not na(oiReqClose) and oiReqTime == time
float oi = oiFresh ? oiReqClose : na
float oiPrev = oi[1]
float dOi = oi - oiPrev
float oiPct = na(oi) or na(oiPrev) or oiPrev == 0 ? na : 100.0 * dOi / oiPrev
// ta.sma skips na values
float ampPct = ta.sma(math.abs(oiPct), ampLenInput)
// =====================================================================
// DATA: intrabar flow (futures and spot)
// =====================================================================
int chartSec = timeframe.in_seconds()
string ltf = ltfInput != "" ? ltfInput : chartSec <= 900 ? "1" : chartSec <= 3600 ? "5" : chartSec <= 14400 ? "15" : chartSec <= 86400 ? "60" : "240"
if timeframe.in_seconds(ltf) >= chartSec
runtime.error("Intrabar timeframe (" + ltf + ") must be lower than the chart timeframe.")
// Intrabar: close > open = buy, close < open = sell,
// equal = compare with the previous intrabar close (or keep its side).
// A var inside a function keeps separate state for each call site.
f_flow(array<float> os, array<float> cs, array<float> vs) =>
var float lastC = na
var int lastS = 0
float u = na
float d = na
int n = na(cs) ? 0 : array.size(cs)
if n > 0
u := 0.0
d := 0.0
for i = 0 to n - 1
float o = array.get(os, i)
float c = array.get(cs, i)
float v = array.get(vs, i)
if not (na(o) or na(c))
int side = c > o ? 1 : c < o ? -1 : na(lastC) ? 0 : c > lastC ? 1 : c < lastC ? -1 : lastS
if side == 1
u += nz(v)
else if side == -1
d += nz(v)
lastC := c
if side != 0
lastS := side
[u, d]
f_imb(float b, float s) =>
float tot = b + s
na(tot) or tot <= 0 ? na : (b - s) / tot
[pO, pC, pV] = request.security_lower_tf(syminfo.tickerid, ltf, [open, close, volume])
[buyVol, sellVol] = f_flow(pO, pC, pV)
float imb = f_imb(buyVol, sellVol)
[sO, sC, sV] = request.security_lower_tf(spotSym, ltf, [open, close, volume], ignore_invalid_symbol = true)
[sBuy, sSell] = f_flow(sO, sC, sV)
float spotImb = f_imb(sBuy, sSell)
int sN = na(sC) ? 0 : array.size(sC)
float spotClose = sN > 0 ? array.get(sC, sN - 1) : na
// Price multiplier contracts (1000PEPE vs PEPE): scale spot by the nearest power of 10 when prices differ > 300×
float pxRatio = na(spotClose) or spotClose <= 0 or close <= 0 ? na : close / spotClose
float spotMult = na(pxRatio) or (pxRatio <= 300 and pxRatio >= 1.0 / 300) ? 1.0 : math.pow(10, math.round(math.log10(pxRatio)))
float spotRef = na(spotClose) ? na : spotClose * spotMult
float basisRaw = na(spotRef) or spotRef == 0 ? na : 100.0 * (close - spotRef) / spotRef
// |basis| > 10% means the spot symbol has a different price scale (e.g. 1000-multiplier contract) or is the wrong coin
float basis = na(basisRaw) or math.abs(basisRaw) > 10 ? na : basisRaw
// =====================================================================
// DATA: chart volume and ATR
// =====================================================================
float volSma = ta.sma(volume, volLenInput)
float volRatio = na(volSma) or volSma <= 0 ? na : volume / volSma
float atr = ta.atr(atrLenInput)
float chg = close - open
// =====================================================================
// SCENARIOS
// 1 price↑ OI↑ buying 2 price↑ OI↓ buying 3 price↓ OI↑ selling
// 4 price↓ OI↓ selling 5 flat OI↑ buying 6 flat OI↑ selling
// =====================================================================
bool dataOk = not (na(chg) or na(atr) or na(oiPct) or na(imb) or na(volRatio))
float sigVal = dataOk ? math.min(math.abs(oiPct) / minOiPctInput, math.abs(imb) / minImbInput, volRatio / minVolRInput) : na
f_scenario(float c, float a, float oPct, float im, float vr, float sg) =>
int result = 0
if not (na(c) or na(a) or na(oPct) or na(im) or na(vr) or na(sg))
float thr = flatKInput * a
bool up = c > thr
bool dn = c < -thr
bool flat = not up and not dn
bool oiUp = oPct >= minOiPctInput
bool oiDn = oPct <= -minOiPctInput
bool buy = im >= minImbInput
bool sell = im <= -minImbInput
if vr >= minVolRInput and sg >= minSigInput
result := up and oiUp and buy ? 1 : up and oiDn and buy ? 2 : dn and oiUp and sell ? 3 : dn and oiDn and sell ? 4 : flat and oiUp and buy ? 5 : flat and oiUp and sell ? 6 : 0
result
int scen = f_scenario(chg, atr, oiPct, imb, volRatio, sigVal)
// Spot confirms when its flow points the same way as the futures flow of the scenario
f_spotOk(int s, float sim) =>
bool buySide = s == 1 or s == 2 or s == 5
s == 0 or na(sim) ? false : buySide ? sim >= spotMinInput : sim <= -spotMinInput
bool spotOk = f_spotOk(scen, spotImb)
int scenShow = spotFilterInput and not spotOk ? 0 : scen
// =====================================================================
// PROBABLE LIQUIDATIONS (estimate — Pine has no real liquidation data)
// 7 = longs (down bar), 8 = shorts (up bar)
// =====================================================================
int liq = 0
if liqOnInput and not (na(oiPct) or na(ampPct) or na(volRatio) or na(atr)) and ampPct > 0 and atr > 0
if oiPct <= -liqOiKInput * ampPct and volRatio >= liqVolInput and high - low >= liqRngInput * atr
liq := close < open ? 7 : close > open ? 8 : 0
// Combinations on one bar: forced closing confirmed by flow
// 9 = short squeeze (up bar: shorts closing + probable short liquidations)
// 10 = long flush (down bar: longs closing + probable long liquidations)
int combo = scenShow == 2 and liq == 8 ? 9 : scenShow == 4 and liq == 7 ? 10 : 0
bool strongSig = not na(sigVal) and sigVal >= strongSigInput
bool vAll = viewInput == ViewMode.all
bool vKey = viewInput == ViewMode.key
// =====================================================================
// TEXTS
// =====================================================================
f_scenLabel(int s) =>
switch s
1 => "OI up + buying"
2 => "Possible short covering"
3 => "OI up + selling"
4 => "Possible long unwinding"
5 => "Possible buying absorbed"
6 => "Possible selling absorbed"
7 => "Probable long liquidations"
8 => "Probable short liquidations"
9 => "Short squeeze"
10 => "Long flush"
=> ""
f_scenInterp(int s) =>
switch s
1 => "Price rising while\nnew positions open"
2 => "Shorts may be closing"
3 => "New positions open\nwhile price falls"
4 => "Longs may be closing"
5 => "Buying may be absorbed"
6 => "Selling may be absorbed"
=> ""
f_scenDev(int s) =>
switch s
1 => "Continuation up\nor reversal"
2 => "Continuation up\nor fading"
3 => "Continuation down\nor bounce"
4 => "Continuation down\nor bounce"
5 => "Breakout up\nor rejection down"
6 => "Breakdown\nor rejection up"
=> ""
f_signed(float x, string fmt) =>
na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x, fmt)
// =====================================================================
// ΔOI PANE
// =====================================================================
f_barColor(float im) =>
color c = naColInput
if not na(im)
float a = math.abs(im)
if a < neutralInput
c := color.new(neutColInput, 40)
else
float span = math.max(fullInput - neutralInput, 0.0001)
float inten = math.min((a - neutralInput) / span, 1.0)
c := color.new(im > 0 ? bullColInput : bearColInput, 80 - 80 * inten)
c
bool usePct = deltaModeInput == DeltaMode.pct
float dVal = usePct ? oiPct : dOi
float ampMa = ta.sma(math.abs(dVal), ampLenInput)
hline(0, "Zero", color = color.new(color.gray, 50), linestyle = hline.style_solid)
plot(dVal, "ΔOI (columns)", color = f_barColor(imb), style = plot.style_columns, histbase = 0)
plot(showAmpInput ? ampMa : na, "+ average |ΔOI|", color = #5AC8FA, linewidth = 1)
plot(showAmpInput ? -ampMa : na, "− average |ΔOI|", color = #5AC8FA, linewidth = 1)
plot(showThrInput and usePct ? minOiPctInput : na, "+ ΔOI threshold", color = color.new(color.gray, 30), style = plot.style_circles, linewidth = 1)
plot(showThrInput and usePct ? -minOiPctInput : na, "− ΔOI threshold", color = color.new(color.gray, 30), style = plot.style_circles, linewidth = 1)
// Data window only
plot(oi, "OI (absolute)", color = color.gray, display = display.data_window)
plot(oiPct, "ΔOI, %", color = color.gray, display = display.data_window)
plot(imb, "Futures imbalance (−1..+1)", color = color.gray, display = display.data_window)
plot(spotImb, "Spot imbalance (−1..+1)", color = color.gray, display = display.data_window)
plot(basis, "Futures/spot basis, %", color = color.gray, display = display.data_window)
plot(volRatio, "Volume / volume SMA", color = color.gray, display = display.data_window)
plot(scen, "Scenario code (0–6)", color = color.gray, display = display.data_window)
plot(liq, "Liquidation code (0/7/8)", color = color.gray, display = display.data_window)
// =====================================================================
// MARKERS ON PRICE CHART (closed bars only, every signal)
// =====================================================================
bool conf = barstate.isconfirmed
bool icons = markStyleInput == MarkStyle.icons
bool show13 = icons and conf and (vAll or vKey)
plotshape(show13 and scenShow == 1 and not strongSig, "Marker 1: OI up + buying", shape.triangleup, location.belowbar, c1Input, size = size.small, force_overlay = true)
plotshape(show13 and scenShow == 1 and strongSig, "Marker 1 strong", shape.triangleup, location.belowbar, c1Input, size = size.normal, force_overlay = true)
plotshape(show13 and scenShow == 3 and not strongSig, "Marker 3: OI up + selling", shape.triangledown, location.abovebar, c3Input, size = size.small, force_overlay = true)
plotshape(show13 and scenShow == 3 and strongSig, "Marker 3 strong", shape.triangledown, location.abovebar, c3Input, size = size.normal, force_overlay = true)
plotshape(icons and conf and vAll and scenShow == 2 and combo == 0, "Marker 2: short covering", shape.circle, location.belowbar, c2Input, size = size.tiny, force_overlay = true)
plotshape(icons and conf and vAll and scenShow == 4 and combo == 0, "Marker 4: long unwinding", shape.circle, location.abovebar, c4Input, size = size.tiny, force_overlay = true)
plotshape(icons and conf and vAll and scenShow == 5, "Marker 5: buying absorbed", shape.diamond, location.abovebar, c5Input, size = size.small, force_overlay = true)
plotshape(icons and conf and vAll and scenShow == 6, "Marker 6: selling absorbed", shape.diamond, location.belowbar, c6Input, size = size.small, force_overlay = true)
plotshape(icons and conf and liq == 7 and combo == 0, "Marker: long liquidations", shape.xcross, location.belowbar, cLqInput, size = size.small, force_overlay = true)
plotshape(icons and conf and liq == 8 and combo == 0, "Marker: short liquidations", shape.xcross, location.abovebar, cLqInput, size = size.small, force_overlay = true)
plotshape(icons and conf and combo == 9, "Marker: short squeeze", shape.labeldown, location.abovebar, cSqInput, size = size.small, text = "SQZ", textcolor = color.black, force_overlay = true)
plotshape(icons and conf and combo == 10, "Marker: long flush", shape.labelup, location.belowbar, cFlInput, size = size.small, text = "FLUSH", textcolor = color.black, force_overlay = true)
// Text mode (repeats suppressed)
var int lastLblBar = na
var int lastLblScen = 0
if markStyleInput == MarkStyle.words and conf
bool visS = scenShow != 0 and combo == 0 and (vAll or (vKey and (scenShow == 1 or scenShow == 3)))
if visS and scenShow != scenShow[1]
if scenShow != lastLblScen or na(lastLblBar) or bar_index - lastLblBar >= relabelInput
bool buySide = scenShow == 1 or scenShow == 2 or scenShow == 6
string tip = "ΔOI: " + f_signed(oiPct, "#.##") + "%\nFutures: " + f_signed(imb * 100, "#.#") + "%\nSpot: " + f_signed(spotImb * 100, "#.#") + "%\nVolume/SMA: " + str.tostring(volRatio, "#.##")
label.new(bar_index, buySide ? low : high, f_scenLabel(scenShow), style = buySide ? label.style_label_up : label.style_label_down, color = color.new(buySide ? bullColInput : bearColInput, 20), textcolor = color.white, size = size.small, tooltip = tip, force_overlay = true)
lastLblBar := bar_index
lastLblScen := scenShow
if combo != 0
label.new(bar_index, combo == 10 ? low : high, f_scenLabel(combo), style = combo == 10 ? label.style_label_up : label.style_label_down, color = combo == 10 ? cFlInput : cSqInput, textcolor = color.black, size = size.small, force_overlay = true)
else if liq != 0
label.new(bar_index, liq == 7 ? low : high, f_scenLabel(liq), style = liq == 7 ? label.style_label_up : label.style_label_down, color = color.new(#424242, 0), textcolor = cLqInput, size = size.small, force_overlay = true)
// =====================================================================
// PRESSURE over the last N bars
// =====================================================================
float nL = math.sum(scenShow == 1 ? 1.0 : 0.0, pressLenInput)
float nS = math.sum(scenShow == 3 ? 1.0 : 0.0, pressLenInput)
float nX = math.sum(scenShow == 2 or scenShow == 4 ? 1.0 : 0.0, pressLenInput)
float nQ = math.sum(liq != 0 ? 1.0 : 0.0, pressLenInput)
float oiN = na(oi) or na(oi[pressLenInput]) or oi[pressLenInput] == 0 ? na : 100.0 * (oi / oi[pressLenInput] - 1)
// The verdict must agree with the net OI change over the window:
// deleveraging only if OI fell, build-up only if OI rose.
f_press(float l, float sh, float x, float q, float oc) =>
string v = "Quiet — no clear pressure"
if na(l) or na(sh) or na(x) or na(q) or na(oc)
v := "Not enough data"
else if x + q > l + sh and x + q >= 3
v := oc < 0 ? "Deleveraging — positions closing" : "Mixed — closings flagged, but OI did not fall"
else if oc > 0 and l >= 2 and l >= 2 * sh
v := "Long build-up"
else if oc > 0 and sh >= 2 and sh >= 2 * l
v := "Short build-up"
else if oc > 0 and l + sh >= 2
v := "Two-sided build-up"
else if l + sh >= 2
v := "Mixed — openings flagged, but OI did not rise"
v
// =====================================================================
// LIVE STATISTICS: strong bar engulfed by the next bar in the opposite direction.
// Event = the strong bar is a Short squeeze / Long flush; control = strong bar without probable liquidations.
// Held = price did not go beyond the extreme of the two bars within N bars.
// =====================================================================
float body = close - open
bool strongBar = not na(atr) and atr > 0 and math.abs(body) >= atr
bool engulf = not na(body[1]) and body[1] != 0 and body != 0 and math.sign(body) == -math.sign(body[1]) and math.abs(body) > math.abs(body[1])
bool liqKnown = not na(oiPct[1]) and not na(ampPct[1]) and ampPct[1] > 0 and not na(volRatio[1])
int evType = conf and engulf and strongBar[1] and liqKnown ? (combo[1] != 0 ? 1 : liq[1] == 0 ? 2 : 0) : 0
var array<int> stBar = array.new_int()
var array<float> stExt = array.new_float()
var array<int> stDir = array.new_int()
var array<int> stTyp = array.new_int()
var int nEv = 0
var int hEv = 0
var int nCtl = 0
var int hCtl = 0
if conf
int i = array.size(stBar) - 1
while i >= 0
int dr = array.get(stDir, i)
float ex = array.get(stExt, i)
bool broke = dr == 1 ? high > ex : low < ex
if broke or bar_index - array.get(stBar, i) >= statWinInput
if array.get(stTyp, i) == 1
nEv += 1
hEv += broke ? 0 : 1
else
nCtl += 1
hCtl += broke ? 0 : 1
array.remove(stBar, i)
array.remove(stExt, i)
array.remove(stDir, i)
array.remove(stTyp, i)
i -= 1
if evType != 0
int d1 = body[1] > 0 ? 1 : -1
array.push(stBar, bar_index)
array.push(stExt, d1 == 1 ? math.max(high, high[1]) : math.min(low, low[1]))
array.push(stDir, d1)
array.push(stTyp, evType)
f_pct(int h, int n) =>
n > 0 ? str.tostring(100.0 * h / n, "#") + "%" : "—"
f_sz(TSize t) =>
t == TSize.tiny ? size.tiny : t == TSize.small ? size.small : t == TSize.normal ? size.normal : t == TSize.large ? size.large : size.huge
f_szDown(TSize t) =>
t == TSize.huge ? size.large : t == TSize.large ? size.normal : t == TSize.normal ? size.small : size.tiny
f_pos(TPos p) =>
p == TPos.tl ? position.top_left : p == TPos.mr ? position.middle_right : p == TPos.br ? position.bottom_right : p == TPos.bl ? position.bottom_left : position.top_right
// =====================================================================
// TABLE
// =====================================================================
var int allBars = 0
allBars += 1
var int oiBars = 0
var int fpBars = 0
var int spBars = 0
if oiFresh
oiBars += 1
if not na(imb)
fpBars += 1
if not na(spotImb)
spBars += 1
// Alpine Quant table style
color TXT = #E6EDF3
color HDR = #1C2530
color ACC = #5AC8FA
var table tbl = table.new(f_pos(tPosInput), 5, showLegendInput ? 13 : 6, bgcolor = color.new(#0F1419, 10), border_color = #2A3441, border_width = 1, force_overlay = true)
if barstate.isfirst
table.merge_cells(tbl, 0, 0, 4, 0)
table.merge_cells(tbl, 0, 3, 4, 3)
table.merge_cells(tbl, 0, 4, 4, 4)
table.merge_cells(tbl, 0, 5, 4, 5)
if showLegendInput
table.merge_cells(tbl, 0, 6, 4, 6)
table.merge_cells(tbl, 0, 8, 4, 8)
table.merge_cells(tbl, 0, 9, 4, 9)
table.merge_cells(tbl, 0, 12, 4, 12)
if showTableInput and barstate.islast
int k = tableClosedInput and not barstate.isconfirmed ? 1 : 0
float c = chg[k]
float a = atr[k]
float op = oiPct[k]
float oiv = oi[k]
float im = imb[k]
float sim = spotImb[k]
float bs = basis[k]
float vr = volRatio[k]
int s = scen[k]
int lq = liq[k]
int cb = combo[k]
bool spk = spotOk[k]
bool ok = dataOk[k]
// Price
string priceTxt = "no ATR data"
if not na(a) and a > 0 and not na(c)
string pDir = c > flatKInput * a ? "Rising" : c < -flatKInput * a ? "Falling" : "Flat"
priceTxt := pDir + "\n" + f_signed(c / a, "#.##") + " ATR"
// OI
string oiTxt = "no OI data"
if not na(op)
string oDir = op >= minOiPctInput ? "Rising" : op <= -minOiPctInput ? "Falling" : "No significant\nchange"
oiTxt := oDir + " " + f_signed(op, "#.##") + "%\n" + str.tostring(oiv, format.volume) + " " + oiUnit
else if not na(oiv)
oiTxt := "no ΔOI\n" + str.tostring(oiv, format.volume) + " " + oiUnit
// Flow
string flowTxt = "no intrabar data"
if not na(im)
string fDir = im >= minImbInput ? "buying" : im <= -minImbInput ? "selling" : "neutral"
string sDir = na(sim) ? "n/a" : sim >= spotMinInput ? "buying " + f_signed(sim * 100, "#") + "%" : sim <= -spotMinInput ? "selling " + f_signed(sim * 100, "#") + "%" : "neutral " + f_signed(sim * 100, "#") + "%"
flowTxt := "Futures: " + fDir + " " + f_signed(im * 100, "#") + "%\nSpot: " + sDir + "\nBasis: " + f_signed(bs, "#.###") + "% · vol/SMA " + (na(vr) ? "n/a" : str.tostring(vr, "#.##"))
// Situation and outlook
string sitTxt = ""
string devTxt = "—"
color sitCol = TXT
if not ok
sitTxt := "Not enough data"
sitCol := color.orange
else if s == 0
sitTxt := "No clear scenario"
else
bool sBuySide = s == 1 or s == 2 or s == 5
string spTxt = na(sim) ? "Spot: no data" : sBuySide ? (spk ? "Spot also buying" : "Spot not buying") : (spk ? "Spot also selling" : "Spot not selling")
sitTxt := f_scenInterp(s) + "\n" + spTxt
devTxt := f_scenDev(s)
sitCol := s == 1 ? c1Input : s == 2 ? c2Input : s == 3 ? c3Input : s == 4 ? c4Input : s == 5 ? c5Input : c6Input
if cb != 0
sitTxt += "\n" + (cb == 9 ? "SQZ " : "FLUSH ") + f_scenLabel(cb)
else if lq != 0
sitTxt += "\n✕ " + f_scenLabel(lq)
// Data warnings (always visible)
string warnTxt = ""
if oiBars == 0
warnTxt += "⚠ " + oiTicker + " returns no data "
if fpBars == 0
warnTxt += "⚠ Intrabars " + ltf + " unavailable "
if spBars == 0
warnTxt += "⚠ Spot " + spotSym + " returns no data — set the spot symbol manually"
else if not na(basisRaw[k]) and math.abs(basisRaw[k]) > 10
warnTxt += "⚠ Spot " + spotSym + " price differs > 10% — check the spot symbol"
bool flowCut = fpBars > 0 and fpBars < 0.95 * allBars
string statusTxt = warnTxt != "" ? warnTxt : (k == 1 ? "Last closed bar" : "Current bar") + (flowCut ? " · flow, markers and stats cover the last " + str.tostring(fpBars) + " of " + str.tostring(allBars) + " bars (intrabar limit)" : "")
string SZ = f_sz(tSizeInput)
string SZd = f_szDown(tSizeInput)
table.cell(tbl, 0, 0, "ALPINE QUANT · OI PRESSURE", text_color = ACC, bgcolor = HDR, text_size = SZ)
table.cell(tbl, 0, 1, "Price", text_color = color.new(TXT, 30), bgcolor = HDR, text_size = SZd)
table.cell(tbl, 1, 1, "Open interest", text_color = color.new(TXT, 30), bgcolor = HDR, text_size = SZd)
table.cell(tbl, 2, 1, "Directional volume (est.)", text_color = color.new(TXT, 30), bgcolor = HDR, text_size = SZd)
table.cell(tbl, 3, 1, "Situation", text_color = color.new(TXT, 30), bgcolor = HDR, text_size = SZd)
table.cell(tbl, 4, 1, "Possible outcome", text_color = color.new(TXT, 30), bgcolor = HDR, text_size = SZd)
table.cell(tbl, 0, 2, priceTxt, text_color = TXT, text_size = SZ, tooltip = "Price change of the bar in ATR units")
table.cell(tbl, 1, 2, oiTxt, text_color = na(op) ? color.orange : TXT, text_size = SZ, tooltip = "Open interest change of the bar")
table.cell(tbl, 2, 2, flowTxt, text_color = na(im) ? color.orange : TXT, text_size = SZ, text_halign = text.align_left, tooltip = "Directional volume estimated from intrabars (close vs open). An approximation, not exchange taker flow.")
table.cell(tbl, 3, 2, sitTxt, text_color = sitCol, text_size = SZ, tooltip = "Interpretation of price × OI × flow. A hypothesis, not a signal.")
table.cell(tbl, 4, 2, devTxt, text_color = TXT, text_size = SZ, tooltip = "Both typical outcomes of the scenario")
// Pressure row
float pl = nL[k]
float ps = nS[k]
float px = nX[k]
float pq = nQ[k]
string pv = f_press(pl, ps, px, pq, oiN[k])
color pc = str.startswith(pv, "Long") ? c1Input : str.startswith(pv, "Short") ? c3Input : str.startswith(pv, "Delev") ? cLqInput : color.new(TXT, 20)
string pTxt = "PRESSURE, last " + str.tostring(pressLenInput) + " bars: " + pv + " · ΔOI " + f_signed(oiN[k], "#.##") + "% · ▲" + str.tostring(pl, "#") + " ▼" + str.tostring(ps, "#") + " ●" + str.tostring(px, "#") + " ✕" + str.tostring(pq, "#")
table.cell(tbl, 0, 3, pTxt, text_color = pc, text_size = SZ, tooltip = "▲ OI up + buying, ▼ OI up + selling, ● positions closing, ✕ probable liquidations. Build-up = new positions dominate and OI rose over the window; deleveraging = closing and liquidations dominate and OI fell over the window. Mixed = markers and net OI change disagree. Otherwise: quiet.")
// Statistics row
string evPart = nEv >= 10 ? f_pct(hEv, nEv) + " (" + str.tostring(nEv) + " cases)" : "too few on this chart (" + str.tostring(nEv) + ") · external research: ~64%"
string ctPart = nCtl >= 10 ? f_pct(hCtl, nCtl) + " (" + str.tostring(nCtl) + ")" : "too few on this chart (" + str.tostring(nCtl) + ") · external research: ~51%"
string stTxt = statOnInput ? "STATS on this chart · strong bar engulfed by next bar → extreme held " + str.tostring(statWinInput) + " bars: after SQZ / FLUSH " + evPart + " · ordinary " + ctPart : ""
table.cell(tbl, 0, 4, stTxt, text_color = color.new(TXT, 15), text_size = SZd, tooltip = "Counted on the history of this chart with the current settings. Research by Alpine Quant (1h, 48 Bybit perpetuals, 2023–2026): after a squeeze/flush engulfed by the next bar the extreme held 20 bars in ~64% of cases vs ~51% for ordinary engulfing. A tendency for exits, not an entry signal.")
table.cell(tbl, 0, 5, statusTxt, text_color = warnTxt != "" ? color.orange : color.new(TXT, 40), bgcolor = HDR, text_size = SZd)
if showLegendInput
string nP = str.tostring(neutralInput * 100, "#") + "%"
string fP = str.tostring(fullInput * 100, "#") + "%"
string unitTxt = usePct ? "%" : oiUnit
string legTitle = "Lower pane: column = ΔOI per bar (" + unitTxt + "), up — OI grew, down — OI fell.\nColor — futures volume imbalance (brighter = stronger):"
string legLines = "Blue lines ± — average |ΔOI| over " + str.tostring(ampLenInput) + " bars. A column beyond the line is a larger than usual change." + (showThrInput and usePct ? "\nGray dots ± — scenario threshold (" + str.tostring(minOiPctInput) + "%)." : "") + "\nBrown column — no flow data."
bool lg = markStyleInput == MarkStyle.icons
table.cell(tbl, 0, 6, legTitle, text_color = TXT, bgcolor = HDR, text_size = SZd, text_halign = text.align_left)
table.cell(tbl, 0, 7, "Strong buying\n≥ " + fP, text_color = TXT, bgcolor = bullColInput, text_size = SZd)
table.cell(tbl, 1, 7, "Weak buying\n" + nP + "–" + fP, text_color = TXT, bgcolor = color.new(bullColInput, 50), text_size = SZd)
table.cell(tbl, 2, 7, "Neutral\n< " + nP, text_color = TXT, bgcolor = color.new(neutColInput, 40), text_size = SZd)
table.cell(tbl, 3, 7, "Weak selling\n" + nP + "–" + fP, text_color = TXT, bgcolor = color.new(bearColInput, 50), text_size = SZd)
table.cell(tbl, 4, 7, "Strong selling\n≥ " + fP, text_color = TXT, bgcolor = bearColInput, text_size = SZd)
table.cell(tbl, 0, 8, legLines, text_color = TXT, text_size = SZd, text_halign = text.align_left)
table.cell(tbl, 0, 9, lg ? "Markers on price chart (every closed bar with a scenario):" : "", text_color = TXT, bgcolor = HDR, text_size = SZd, text_halign = text.align_left)
table.cell(tbl, 0, 10, lg ? "▲ OI up\n+ buying" : "", text_color = c1Input, text_size = SZd)
table.cell(tbl, 1, 10, lg ? "● Short\ncovering" : "", text_color = c2Input, text_size = SZd)
table.cell(tbl, 2, 10, lg ? "▼ OI up\n+ selling" : "", text_color = c3Input, text_size = SZd)
table.cell(tbl, 3, 10, lg ? "● Long\nunwinding" : "", text_color = c4Input, text_size = SZd)
table.cell(tbl, 4, 10, lg ? "◆ Buying\nabsorbed (above)" : "", text_color = c5Input, text_size = SZd)
table.cell(tbl, 0, 11, lg ? "◆ Selling\nabsorbed (below)" : "", text_color = c6Input, text_size = SZd)
table.cell(tbl, 1, 11, lg ? "✕ below: probable\nlong liquidations" : "", text_color = cLqInput, text_size = SZd)
table.cell(tbl, 2, 11, lg ? "✕ above: probable\nshort liquidations" : "", text_color = cLqInput, text_size = SZd)
table.cell(tbl, 3, 11, lg ? "SQZ short squeeze\n(above)" : "", text_color = cSqInput, text_size = SZd)
table.cell(tbl, 4, 11, lg ? "FLUSH long flush\n(below)" : "", text_color = cFlInput, text_size = SZd)
table.cell(tbl, 0, 12, lg ? (spotFilterInput ? "Only spot-confirmed signals shown." : "All signals shown (spot filter off).") + " View: " + (vAll ? "all scenarios" : vKey ? "key events" : "liquidations only") + ". Larger ▲▼ — significance ≥ " + str.tostring(strongSigInput) + "." : "", text_color = TXT, text_size = SZd, text_halign = text.align_left)
// =====================================================================
// ALERTS
// =====================================================================
alertcondition(conf and scenShow != 0, "Any scenario", "OI Pressure: scenario on {{ticker}} {{interval}}")
alertcondition(conf and liq == 7, "Probable long liquidations", "OI Pressure: probable long liquidations on {{ticker}} {{interval}}")
alertcondition(conf and liq == 8, "Probable short liquidations", "OI Pressure: probable short liquidations on {{ticker}} {{interval}}")
alertcondition(conf and combo == 9, "Short squeeze", "OI Pressure: short squeeze on {{ticker}} {{interval}}")
alertcondition(conf and combo == 10, "Long flush", "OI Pressure: long flush on {{ticker}} {{interval}}")