Indicator · Pine Script v6 · Own pane

Order Flow Bar Statistics [QuantAlgo]

by theonetrade· code credited to QuantAlgo

Order Flow Bar Statistics [QuantAlgo] calculates and displays detailed per-bar order flow metrics in a separate chart pane.

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code645
Settings40inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

645 lines of Pine Script v6 from assets/indicator/bit-exact/order_flow_bar_statistics_quantalgo_kByFhbit.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

order_flow_bar_statistics_quantalgo_kByFhbit.pine
// This script is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © QuantAlgo

//@version=6
indicator('Order Flow Bar Statistics [QuantAlgo]', overlay = false, max_labels_count = 500, explicit_plot_zorder = true)

//              ╔════════════════════════════════╗
//              ║      USER-DEFINED SETTINGS     ║
//              ╚════════════════════════════════╝

var string volume_settings   = '════════ Volume & Delta ════════'
var string liq_settings      = '════════ Liquidations ════════'
var string interest_settings = '═════ Open Interest & Positioning ═════'
var string funding_settings  = '════════ Funding & Price ════════'
var string source_settings   = '════════ Data Source ════════'
var string number_settings   = '════════ Number Format ════════'
var string layout_settings   = '════════ Layout ════════'
var string visual_settings   = '════════ Visual Settings ════════'

tooltip_buy_vol     = 'Aggressive buy volume: the share of the bar that traded into the offer, where the buyer crossed the spread to get filled. This comes from volume footprint data, so it reflects which side initiated each trade rather than being inferred from the bar range. Reading footprint data requires a Premium or Ultimate plan. On charts carrying a lot of history it can also lead to a memory limit error in Bar Replay, since footprint data loads across the full chart and cannot be capped by bar count.\n\nHow to read it: rising buy volume alongside rising price is participation confirming the move. Heavy buy volume against a price that will not advance is absorption, buyers are being met by resting supply, and that often precedes a stall.\n\nIf cells read as unavailable, bid/ask data is not being served for those bars. Delta Engine under Data Source controls what happens in that case.'
tooltip_sell_vol    = 'Aggressive sell volume: the share of the bar that traded into the bid, where the seller crossed the spread to get filled.\n\nHow to read it: buy and sell volume always sum to total volume, so read them as a pair. A bar split close to evenly is a balanced auction. A lopsided split shows one side doing the work, and the direction of price against that split tells you whether they are being rewarded or absorbed.\n\nIf cells read as unavailable, bid/ask data is not being served for those bars.'
tooltip_total_vol   = 'Total traded volume for the bar, read directly from the charted contract.\n\nHow to read it: volume is conviction. A breakout on expanding volume carries weight, the same move on thin volume is far easier to reverse. Turn on Tint Total By Delta under Visual Settings and this row is colored by which side dominated, so magnitude and direction read together in one cell.\n\nBlank cells mean the symbol reports no volume at all, which is uncommon outside index and synthetic tickers.'
tooltip_delta_vol   = 'Net delta: aggressive buy volume minus aggressive sell volume. Positive means buyers lifted more than sellers hit.\n\nHow to read it: divergence between delta and price is the tell worth waiting for. Price making a new high while delta shrinks means the push is being sold into. A large delta that fails to move price means the aggressor is being absorbed by resting orders, which frequently marks the turn.\n\nBlank cells mean the buy and sell split was unavailable for that bar, so the subtraction has no inputs.'
tooltip_pct_delta   = 'Delta as a percentage of classified volume, so bars of very different size stay directly comparable.\n\nHow to read it: this normalizes conviction. Forty percent on a quiet bar is a more one-sided tape than a larger raw delta on a heavy bar. Clusters of same-sign readings across consecutive bars mark sustained pressure rather than a single aggressive print.\n\nBlank cells mean the buy and sell split was unavailable for that bar.'

tooltip_liq_naming  = 'Sets which side a liquidation row is named after. The two conventions are mirror images, because a long being closed out fires a market sell and a short being closed out fires a market buy.\n\nLiquidated position side: a long being wiped out counts as a BUY liquidation, since buyers were the side liquidated. This is how most order-flow desks read it and is the default.\n\nResulting order side: the same event counts as a SELL, since a market sell hit the book.\n\nThe underlying data is identical either way. Only the labels swap.'
tooltip_buy_liq     = 'Forced closure of long positions, sized in contract units. Under the default naming, buyers are the side being liquidated.\n\nHow to read it: liquidations are leverage being flushed, and they arrive as forced market selling. Clusters print at local lows and frequently mark exhaustion, because once the leveraged longs are gone there is nobody left to force out. Size matters far more than frequency, one large liquidation moves price more than many small ones.\n\nValues may arrive in base or quote currency depending on the venue, so read magnitudes against the past behavior of this symbol rather than comparing them across exchanges. A 0 means the feed is live and nothing was liquidated in that bar. Cells reading unavailable mean this data is not available for the charted ticker.'
tooltip_sell_liq    = 'Forced closure of short positions, sized in contract units. Under the default naming, sellers are the side being liquidated.\n\nHow to read it: this is squeeze fuel. Short liquidations arrive as forced market buying, so a cascade here accelerates upside moves and often produces the vertical segment of a rally. Pair it with open interest, a squeeze that drops open interest is covering rather than fresh buying, and tends to fade.\n\nA 0 means the feed is live and nothing was liquidated. Unavailable means this data is not available for the charted ticker.'
tooltip_total_liq   = 'Combined liquidation volume for the bar, both sides together.\n\nHow to read it: this is a pure stress gauge for when magnitude matters more than direction. Spikes mark the moments the market forced positions out, which are the bars worth revisiting when you review a session. Read it against the delta liquidation row to see which side wore the damage.\n\nA 0 means the feed is live and nothing was liquidated. Unavailable means this data is not available for the charted ticker.'
tooltip_delta_liq   = 'Net liquidation pressure: buy liquidations minus sell liquidations.\n\nHow to read it: when both sides are firing at once, this isolates who is actually being hurt. A large positive reading is longs being flushed, negative is shorts being squeezed. A sign flip mid-trend often marks the handover from one side capitulating to the other.\n\nA 0 means the feed is live and the two sides cancelled out. Unavailable means this data is not available for the charted ticker.'

tooltip_oi          = 'Bar-over-bar change in open interest, the total number of contracts outstanding.\n\nHow to read it: this separates new money from unwinding, and it is the single most useful row to pair with price. Price up with open interest up is fresh longs. Price up with open interest down is shorts covering, which is less durable. Price down with open interest up is fresh shorts. Price down with open interest down is longs closing out.\n\nCells reading unavailable mean this data is not available for the charted ticker.'
tooltip_net_long    = 'Net long participation for the bar, derived from delta and the change in open interest together.\n\nHow to read it: delta alone tells you who was aggressive, open interest alone tells you whether positions grew. Combining them separates aggressive buying that opened new longs from aggressive buying that merely closed shorts. A strongly positive reading is fresh long exposure entering.\n\nThis row needs both delta and open interest. If either is unavailable for the symbol the row reads unavailable rather than defaulting to zero, since a missing input is not the same as a zero result.'
tooltip_net_short   = 'Net short participation for the bar, derived from delta and the change in open interest together.\n\nHow to read it: net long plus net short always reconciles to delta, and net long minus net short reconciles to the open interest change, so the pair ties back to both inputs and can be checked against the rows above. Read the two together, both positive means both sides added exposure into the bar.\n\nThis row needs both delta and open interest. If either is unavailable the row reads unavailable rather than zero.'

tooltip_funding     = 'The funding rate in force during the bar, shown as a percentage. Funding is the periodic payment between longs and shorts that keeps a perpetual contract tethered to spot.\n\nHow to read it: positive funding means longs are paying shorts, so the crowd sits long and pays to stay there. Persistently elevated funding is a crowded trade and raises the odds of a long squeeze. Negative funding flips the payment and often marks pessimistic positioning near lows. Funding settles on the exchange interval, usually every eight hours, so the row holds flat between settlements by design.\n\nCells reading unavailable mean this data is not available for the charted ticker.'
tooltip_close       = 'The closing price of the charted contract for each bar, read straight from the chart.\n\nHow to read it: this keeps the table self-contained. You can scan a full bar of order flow with its price in the same row of cells, without moving your eye back to the candles above. The cell is colored by the bar-over-bar change, so the row doubles as a compact price direction strip running beneath the statistics.'
tooltip_fr_scale    = 'Unit conversion applied to the funding feed.\n\nDecimal to percent: the feed publishes a decimal fraction, so 0.0001 displays as 0.0100%. This is correct for the major perpetual venues and is the right choice for virtually every symbol.\n\nAuto: sorts every bar in the history into a magnitude bucket and applies whichever scale fits the majority, so one unusual bar cannot skew the whole chart.\n\nAlready percent and Basis points cover venues that publish on a different unit. If the funding row looks off by a factor of 100 or 10000, this is the setting to change.'
tooltip_fr_heat     = 'Controls what the funding cell color is measured against.\n\nLevel: colors each cell by the funding rate itself. When funding sits pinned at one value the row becomes a flat saturated band, and that flatness is the signal, it tells you at a glance that funding has been one-sided across the whole window.\n\nDeviation from average: colors against the rolling average instead, which surfaces the individual bars where funding ran rich or cheap relative to its recent norm. Use this when funding rarely moves and you want the exceptions to stand out.'

tooltip_display     = 'Coin reports volume, delta, liquidations and open interest in base units of the contract, which is how the exchange publishes them.\n\nQuote currency multiplies those rows by price to give notional value in whatever the contract settles in, so readings are comparable across assets and across time as price moves. Useful when watching several symbols side by side, or when comparing current activity against a period where price was far lower. A dollar sign is added when the symbol settles in a dollar unit.\n\nFunding stays a percentage and the closing price stays a price under both settings.'
tooltip_heat_len    = 'Lookback used to scale cell intensity. Each cell is shaded against the largest absolute value its own row produced across this window, so color always reads relative to recent conditions rather than a fixed scale that would go dark on quiet symbols.\n\nHow to choose it: shorter windows make the table reactive, so ordinary bars still show color and you can read rhythm. Longer windows reserve full saturation for genuine outliers, so the table stays dark until something unusual happens. 50 suits intraday work, 200 or more suits scanning for extremes.'
tooltip_ticks_row   = 'Price granularity the bid/ask engine uses when dissecting each bar internally, measured in ticks per price level.\n\nThis table reads bar totals only, never individual price levels, so this setting has no effect on any number you see. It is a performance control. A small value makes the engine build dozens of price levels per bar; a large value builds one or two and does the same job here. Leave it high.'
tooltip_engine      = 'Sets where the buy and sell split comes from.\n\nThe indicator reads volume footprint data, which requires a Premium or Ultimate plan. That data loads before any setting is read, so the requirement applies to the whole script regardless of the mode selected here.\n\nBid/ask engine: reads TradingView bid and ask data to show which side initiated each trade. Bars it cannot serve read as unavailable.\n\nBid/ask engine with estimate: the same, but bars the engine cannot serve fall back to a range-based approximation so the row stays continuous. Estimated cells are flagged with a tilde on the row tag.\n\nEstimate from bar range: approximates the split from where each bar closed within its range. Useful on symbols or periods where bid and ask data is thin.\n\nOff: leaves the four delta rows out entirely. Use this if you want a clean ten-row table of liquidations, open interest, funding and volume.'
tooltip_net_mode    = 'Sets how net long and net short are derived.\n\nDelta and OI split: net long is half the sum of delta and the open interest change, net short is half the difference. Both rows carry a value every bar and always reconcile back to delta and open interest, which makes them checkable against the rows above.\n\nPrice and OI quadrant: assigns the whole bar to a single side based on whether price and open interest rose or fell together. Reads more cleanly on trending charts, at the cost of leaving one of the two rows empty each bar.'
tooltip_swap        = 'Swaps the two raw liquidation feeds before anything else is applied. Only needed on the rare venue that publishes them inverted, which you would spot as liquidation clusters appearing on the wrong side of a sharp move.\n\nThis is separate from Liquidation Naming, which relabels the rows without touching the underlying data.'

tooltip_abbrev      = 'Abbreviates thousands and millions so cells stay narrow enough to scan at a glance.\n\nThis is not rounding. The abbreviated figure carries its decimals through, so 73950.12 reads 73.95K rather than 74K, and you keep the precision while gaining the space. Switch it off to print every figure in full, which suits wide panes and fewer columns.'
tooltip_decimals    = 'Precision applied to every printed figure.\n\nAuto keeps two decimals at or above 1 and six below it, then drops trailing zeros. A whole number stays whole, a fractional one keeps its digits, and small liquidation sizes stay readable instead of collapsing to 0.\n\nA fixed count overrides that when you want every cell aligned to identical precision, which reads more evenly in screenshots.'
tooltip_na_text     = 'Text printed when a feed does not exist for the symbol, or has no data for that bar.\n\nA genuine zero still prints as 0, so an empty reading and a missing reading are never confused with each other. Hover the row tag of any row showing this text for the specific reason it is unavailable.'

tooltip_show_names  = 'Shows the row name tags down the right side of the table.\n\nEach tag carries a tooltip explaining what that row measures, how to interpret it, and what it means if the cells are blank. Rows without data are dimmed and marked so you can see at a glance which statistics the current symbol supports.'
tooltip_name_style  = 'Short keeps the tag column narrow, which matters when the pane is short or you are running many rows. Full spells every row name out, which reads better in screenshots and when sharing setups with someone who has not used the table before.'
tooltip_name_gap    = 'Distance between the right edge of the last cell and the row name tags, measured in bars. Zero sits the tags flush against the table. Increase it if the tags crowd the final column of figures.'
tooltip_show_values = 'Prints the numeric value inside each cell on recent bars.\n\nTurn it off for a pure heat map. Color spans the full chart history, so with numbers off you can zoom out and read weeks or months of order flow as a single pattern, which is the fastest way to spot regime changes in funding, open interest and liquidation activity.'
tooltip_max_cols    = 'Upper bound on how many recent bars carry printed figures.\n\nColor spans the full chart history regardless. Text is drawn with label objects and the platform caps those at 500 per script, shared across every enabled row, so the real ceiling is 500 minus one tag per row divided by the row count. With every row enabled that is 34 columns, and raising this beyond 34 has no effect. Switch rows off to buy more columns, at seven rows the ceiling is 70.\n\nLabels are the most memory-hungry object a script can create, so keep this only as high as you actually read.'

tooltip_colors      = 'Pre-configured color schemes for the heat cells. Custom allows full control using the two color inputs below. Classic uses traditional green and red. Aqua provides ocean-inspired tones. Cosmic offers futuristic cyan and purple. Cyber features warm orange against cool cyan. Neon delivers high-contrast yellow and magenta for maximum visibility.\n\nText color inside every cell is calculated automatically from the cell shade, so figures stay legible on any scheme you pick.'
tooltip_bullish     = 'Color applied to positive readings, at full saturation for the strongest value in the lookback window. Only applies when Color Preset is set to Custom.'
tooltip_bearish     = 'Color applied to negative readings, at full saturation for the strongest value in the lookback window. Only applies when Color Preset is set to Custom.'
tooltip_zero        = 'Color applied to cells at or near zero. Every cell is painted on every bar, so this is what an inactive row looks like rather than an empty gap, which keeps the table reading as a solid grid.'
tooltip_gamma       = 'Curve applied to cell intensity.\n\nValues below 1 lift the mid-range so moderate activity still shows color and the table reads as a continuous gradient. Values above 1 suppress the mid-range so only genuine extremes light up and everything else stays dark. Lower it for rhythm, raise it for outlier hunting.'
tooltip_text_size   = 'Size of the printed figures inside each cell. Reduce it when running many rows in a short pane, or when you have raised Max Numbered Bars and the columns have narrowed.'
tooltip_tint_total  = 'Colors the total volume row by the sign of delta rather than by magnitude alone, so a heavy bar immediately reads as buyer or seller dominated and you get two pieces of information from one cell.'
tooltip_pane_bg     = 'Background color of the indicator pane behind the table.'
tooltip_name_bg     = 'Background color of the row name tags. Tags for rows without data are automatically dimmed toward the pane background, and their text color is calculated to stay legible against whichever shade you pick.'

show_buy_vol   = input.bool(true, 'Buy Volume',   group = volume_settings, tooltip = tooltip_buy_vol)
show_sell_vol  = input.bool(true, 'Sell Volume',  group = volume_settings, tooltip = tooltip_sell_vol)
show_total_vol = input.bool(true, 'Total Volume', group = volume_settings, tooltip = tooltip_total_vol)
show_delta_vol = input.bool(true, 'Delta Volume', group = volume_settings, tooltip = tooltip_delta_vol)
show_pct_delta = input.bool(true, 'Percent Delta', group = volume_settings, tooltip = tooltip_pct_delta)

liq_naming     = input.string('Liquidated position side', 'Liquidation Naming', options = ['Liquidated position side', 'Resulting order side'], group = liq_settings, tooltip = tooltip_liq_naming)
show_buy_liq   = input.bool(true, 'Buy Liquidations',   group = liq_settings, tooltip = tooltip_buy_liq)
show_sell_liq  = input.bool(true, 'Sell Liquidations',  group = liq_settings, tooltip = tooltip_sell_liq)
show_total_liq = input.bool(true, 'Total Liquidations', group = liq_settings, tooltip = tooltip_total_liq)
show_delta_liq = input.bool(true, 'Delta Liquidations', group = liq_settings, tooltip = tooltip_delta_liq)

show_oi        = input.bool(true, 'Open Interest', group = interest_settings, tooltip = tooltip_oi)
show_net_long  = input.bool(true, 'Net Long',      group = interest_settings, tooltip = tooltip_net_long)
show_net_short = input.bool(true, 'Net Short',     group = interest_settings, tooltip = tooltip_net_short)
net_mode       = input.string('Delta and OI split', 'Positioning Method', options = ['Delta and OI split', 'Price and OI quadrant'], group = interest_settings, tooltip = tooltip_net_mode)

show_funding   = input.bool(true, 'Funding Rate', group = funding_settings, tooltip = tooltip_funding)
show_close     = input.bool(true, 'Close Price',  group = funding_settings, tooltip = tooltip_close)
fr_scale       = input.string('Decimal to percent', 'Funding Scale', options = ['Decimal to percent', 'Auto', 'Already percent', 'Basis points'], group = funding_settings, tooltip = tooltip_fr_scale)
fr_heat_mode   = input.string('Level', 'Funding Heat', options = ['Level', 'Deviation from average'], group = funding_settings, tooltip = tooltip_fr_heat)

display_mode   = input.string('Coin', 'Display Mode', options = ['Coin', 'Quote currency'], group = source_settings, tooltip = tooltip_display)
heat_length    = input.int(50, 'Heat Lookback', minval = 5, maxval = 500, group = source_settings, tooltip = tooltip_heat_len)
ticks_per_row  = input.int(5000, 'Footprint Row Size', minval = 1, group = source_settings, tooltip = tooltip_ticks_row)
delta_engine   = input.string('Bid/ask engine', 'Delta Engine', options = ['Bid/ask engine', 'Bid/ask engine with estimate', 'Estimate from bar range', 'Off'], group = source_settings, tooltip = tooltip_engine)
swap_feeds     = input.bool(false, 'Swap Liquidation Feeds', group = source_settings, tooltip = tooltip_swap)

abbreviate     = input.bool(true, 'Abbreviate Thousands', group = number_settings, tooltip = tooltip_abbrev)
decimal_mode   = input.string('Auto', 'Decimals', options = ['Auto', '0', '1', '2', '3', '4', '6'], group = number_settings, tooltip = tooltip_decimals)
na_text        = input.string('N/A', 'Missing Data Text', group = number_settings, tooltip = tooltip_na_text)

show_names     = input.bool(true, 'Show Row Names', group = layout_settings, tooltip = tooltip_show_names)
name_style     = input.string('Full', 'Row Name Style', options = ['Short', 'Full'], group = layout_settings, tooltip = tooltip_name_style)
name_gap       = input.float(0.15, 'Row Name Gap', minval = 0.0, maxval = 4.0, step = 0.05, group = layout_settings, tooltip = tooltip_name_gap)
show_values    = input.bool(true, 'Show Numbers', group = layout_settings, tooltip = tooltip_show_values)
max_columns    = input.int(30, 'Max Numbered Bars', minval = 1, maxval = 100, group = layout_settings, tooltip = tooltip_max_cols)

color_preset   = input.string('Custom', 'Color Preset', options = ['Custom', 'Classic', 'Aqua', 'Cosmic', 'Cyber', 'Neon'], group = visual_settings, tooltip = tooltip_colors)
bullish_input  = input.color(#00ffaa, 'Bullish Color', group = visual_settings, tooltip = tooltip_bullish)
bearish_input  = input.color(#ff0000, 'Bearish Color', group = visual_settings, tooltip = tooltip_bearish)
zero_color     = input.color(#141414, 'Zero Color', group = visual_settings, tooltip = tooltip_zero)
heat_gamma     = input.float(0.55, 'Intensity Gamma', minval = 0.2, maxval = 1.5, step = 0.05, group = visual_settings, tooltip = tooltip_gamma)
text_size_in   = input.string('Small', 'Cell Text Size', options = ['Tiny', 'Small', 'Normal'], group = visual_settings, tooltip = tooltip_text_size)
tint_by_delta  = input.bool(true, 'Tint Total By Delta', group = visual_settings, tooltip = tooltip_tint_total)
pane_bg        = input.color(#000000, 'Pane Background', group = visual_settings, tooltip = tooltip_pane_bg)
name_bg        = input.color(#2a2a2a, 'Row Name Background', group = visual_settings, tooltip = tooltip_name_bg)

[bullish_color, bearish_color] = switch color_preset
    'Classic' => [#00ff00, #ff0000]
    'Aqua'    => [#00d4ff, #ff8c00]
    'Cosmic'  => [#49ffce, #9932cc]
    'Cyber'   => [#00cccc, #ff6600]
    'Neon'    => [#ffff00, #ff00ff]
    => [bullish_input, bearish_input]

as_quote    = display_mode == 'Quote currency'
name_by_pos = liq_naming == 'Liquidated position side'
short_names = name_style == 'Short'
name_bg_off = color.from_gradient(0.6, 0.0, 1.0, name_bg, pane_bg)

//              ╔════════════════════════════════╗
//              ║        CORE CALCULATION        ║
//              ╚════════════════════════════════╝

cell_size() =>
    switch text_size_in
        'Small'  => size.small
        'Normal' => size.normal
        =>          size.tiny

decimal_pattern(float magnitude) =>
    int places = switch decimal_mode
        '0' => 0
        '1' => 1
        '2' => 2
        '3' => 3
        '4' => 4
        '6' => 6
        =>     magnitude >= 1.0 ? 2 : 6
    switch places
        0 => '0'
        1 => '0.#'
        2 => '0.##'
        3 => '0.###'
        4 => '0.####'
        =>   '0.######'

format_value(float value, bool as_quote) =>
    string out = na_text
    if not na(value)
        float  magnitude = math.abs(value)
        string sign      = value < 0 ? '-' : ''
        string unit      = as_quote and str.startswith(syminfo.currency, 'USD') ? '$' : ''
        if magnitude == 0.0
            out := '0'
        else if abbreviate and magnitude >= 1000000.0
            float scaled = magnitude / 1000000.0
            out := sign + unit + str.tostring(scaled, decimal_pattern(scaled)) + 'M'
        else if abbreviate and magnitude >= 1000.0
            float scaled = magnitude / 1000.0
            out := sign + unit + str.tostring(scaled, decimal_pattern(scaled)) + 'K'
        else
            out := sign + unit + str.tostring(magnitude, decimal_pattern(magnitude))
    out

format_percent(float value) =>
    na(value) ? na_text : str.tostring(value, decimal_pattern(math.abs(value))) + '%'

format_price(float value) =>
    na(value) ? na_text : str.tostring(value, format.mintick)

format_rate(float value, float multiplier) =>
    na(value) ? na_text : str.tostring(value * multiplier, '0.0000') + '%'

heat(float source_value, float extreme, float sign_by) =>
    float reading   = nz(source_value)
    float reference = nz(extreme)
    float magnitude = reference <= 0.0 ? 0.0 : math.min(1.0, math.pow(math.abs(reading) / reference, heat_gamma))
    color.from_gradient(magnitude, 0.0, 1.0, zero_color, nz(sign_by) >= 0.0 ? bullish_color : bearish_color)

srgb_channel(float channel) =>
    float unit = channel / 255.0
    unit <= 0.03928 ? unit / 12.92 : math.pow((unit + 0.055) / 1.055, 2.4)

relative_luminance(color shade) =>
    0.2126 * srgb_channel(color.r(shade)) + 0.7152 * srgb_channel(color.g(shade)) + 0.0722 * srgb_channel(color.b(shade))

readable_text(color background) =>
    float luminance   = relative_luminance(background)
    float versus_dark  = (luminance + 0.05) / 0.05
    float versus_light = 1.05 / (luminance + 0.05)
    versus_dark >= versus_light ? color.black : color.white

muted_text(color background) =>
    color.new(readable_text(background), 35)

highest_abs(float source_value, int length) =>
    ta.highest(math.abs(nz(source_value)), length)

rising(float source_value) =>
    not na(source_value) and not na(source_value[1]) and source_value > source_value[1]

falling(float source_value) =>
    not na(source_value) and not na(source_value[1]) and source_value < source_value[1]

turns_positive(float source_value) =>
    not na(source_value) and not na(source_value[1]) and source_value > 0 and source_value[1] <= 0

turns_negative(float source_value) =>
    not na(source_value) and not na(source_value[1]) and source_value < 0 and source_value[1] >= 0

feed_id = syminfo.prefix + ':' + syminfo.ticker
lq_buy_id       = feed_id + '_LQBUY'
lq_sell_id      = feed_id + '_LQSELL'
oi_id           = feed_id + '_OI'
fr_id           = feed_id + '_FR'

bool query_engine = delta_engine == 'Bid/ask engine' or delta_engine == 'Bid/ask engine with estimate'
bool allow_estimate = delta_engine == 'Bid/ask engine with estimate' or delta_engine == 'Estimate from bar range'

footprint bar_print = na
if query_engine
    bar_print := request.footprint(ticks_per_row)
bool print_ok = not na(bar_print)

var bool print_ever = false
if print_ok
    print_ever := true

bool delta_live = print_ever or allow_estimate

float bar_span      = high - low
float estimate_buy  = bar_span == 0.0 ? nz(volume) * 0.5 : nz(volume) * (close - low)  / bar_span
float estimate_sell = bar_span == 0.0 ? nz(volume) * 0.5 : nz(volume) * (high - close) / bar_span

float buy_volume  = na
float sell_volume = na
if print_ok
    buy_volume  := bar_print.buy_volume()
    sell_volume := bar_print.sell_volume()
else if allow_estimate
    buy_volume  := estimate_buy
    sell_volume := estimate_sell

float total_volume = volume
float delta_volume = buy_volume - sell_volume
float classified   = buy_volume + sell_volume
float percent_delta = na(classified) or classified == 0.0 ? na : 100.0 * delta_volume / classified

float shown_buy   = as_quote ? buy_volume  * close : buy_volume
float shown_sell  = as_quote ? sell_volume * close : sell_volume
float shown_total = as_quote ? total_volume * close : total_volume
float shown_delta = as_quote ? delta_volume * close : delta_volume

bool need_liq  = show_buy_liq or show_sell_liq or show_total_liq or show_delta_liq
bool need_oi   = show_oi or show_net_long or show_net_short

float lq_buy_raw  = na
float lq_sell_raw = na
float oi_series    = na
float fr_raw      = na

if need_liq
    lq_buy_raw  := request.security(lq_buy_id,  timeframe.period, volume, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
    lq_sell_raw := request.security(lq_sell_id, timeframe.period, volume, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
if need_oi
    oi_series := request.security(oi_id, timeframe.period, close, ignore_invalid_symbol = true)
if show_funding
    fr_raw := request.security(fr_id, timeframe.period, close, ignore_invalid_symbol = true)

var bool liq_ok  = false
var bool oi_ok   = false
var bool fr_ok   = false
if not na(lq_buy_raw) or not na(lq_sell_raw)
    liq_ok := true
if not na(oi_series)
    oi_ok := true
if not na(fr_raw)
    fr_ok := true

float order_buy  = swap_feeds ? nz(lq_sell_raw) : nz(lq_buy_raw)
float order_sell = swap_feeds ? nz(lq_buy_raw)  : nz(lq_sell_raw)

float buy_liq   = liq_ok ? (name_by_pos ? order_sell : order_buy) : na
float sell_liq  = liq_ok ? (name_by_pos ? order_buy  : order_sell) : na
float total_liq = liq_ok ? buy_liq + sell_liq : na
float delta_liq = liq_ok ? buy_liq - sell_liq : na

float oi_change = oi_ok ? nz(ta.change(oi_series)) : na
float shown_oi  = as_quote ? oi_change * close : oi_change

bool  net_ok    = oi_ok and not na(delta_volume)
bool  net_live  = oi_ok and delta_live
float net_long  = na
float net_short = na
if net_ok
    if net_mode == 'Price and OI quadrant'
        float price_change = close - close[1]
        net_long  := 0.0
        net_short := 0.0
        if price_change > 0.0 and oi_change > 0.0
            net_long := oi_change
        else if price_change < 0.0 and oi_change < 0.0
            net_long := oi_change
        else if price_change < 0.0 and oi_change > 0.0
            net_short := oi_change
        else if price_change > 0.0 and oi_change < 0.0
            net_short := oi_change
    else
        net_long  := (delta_volume + oi_change) / 2.0
        net_short := (delta_volume - oi_change) / 2.0
float shown_long  = as_quote ? net_long  * close : net_long
float shown_short = as_quote ? net_short * close : net_short

float close_price  = close
float close_change = nz(ta.change(close_price))

var int rate_tiny = 0
var int rate_dec  = 0
var int rate_pct  = 0
if not na(fr_raw) and fr_raw != 0.0
    float rate_size = math.abs(fr_raw)
    if rate_size < 0.00005
        rate_tiny += 1
    else if rate_size < 0.05
        rate_dec += 1
    else
        rate_pct += 1
float rate_auto = rate_dec >= rate_tiny and rate_dec >= rate_pct ? 100.0 : rate_tiny >= rate_pct ? 10000.0 : 1.0

float rate_multiplier = switch fr_scale
    'Already percent' => 1.0
    'Basis points'    => 10000.0
    'Auto'            => rate_auto
    =>                   100.0

float rate_average = ta.sma(nz(fr_raw), heat_length)
float rate_heat    = not fr_ok ? na : fr_heat_mode == 'Level' ? fr_raw : fr_raw - nz(rate_average)

float hi_buy       = highest_abs(shown_buy,     heat_length)
float hi_sell      = highest_abs(shown_sell,    heat_length)
float hi_total     = highest_abs(shown_total,   heat_length)
float hi_delta     = highest_abs(shown_delta,   heat_length)
float hi_percent   = highest_abs(percent_delta, heat_length)
float hi_buy_liq   = highest_abs(buy_liq,       heat_length)
float hi_sell_liq  = highest_abs(sell_liq,      heat_length)
float hi_total_liq = highest_abs(total_liq,     heat_length)
float hi_delta_liq = highest_abs(delta_liq,     heat_length)
float hi_oi        = highest_abs(shown_oi,      heat_length)
float hi_long      = highest_abs(shown_long,    heat_length)
float hi_short     = highest_abs(shown_short,   heat_length)
float hi_rate      = highest_abs(rate_heat,     heat_length)
float hi_close      = highest_abs(close_change,   heat_length)

color tint_buy       = heat(shown_buy,     hi_buy,       1.0)
color tint_sell      = heat(shown_sell,    hi_sell,      -1.0)
color tint_total     = heat(shown_total,   hi_total,     tint_by_delta ? shown_delta : 1.0)
color tint_delta     = heat(shown_delta,   hi_delta,     shown_delta)
color tint_percent   = heat(percent_delta, hi_percent,   percent_delta)
color tint_buy_liq   = heat(buy_liq,       hi_buy_liq,   1.0)
color tint_sell_liq  = heat(sell_liq,      hi_sell_liq,  -1.0)
color tint_total_liq = heat(total_liq,     hi_total_liq, 1.0)
color tint_delta_liq = heat(delta_liq,     hi_delta_liq, delta_liq)
color tint_oi        = heat(shown_oi,      hi_oi,        shown_oi)
color tint_long      = heat(shown_long,    hi_long,      shown_long)
color tint_short     = heat(shown_short,   hi_short,     -shown_short)
color tint_rate      = heat(rate_heat,     hi_rate,      rate_heat)
color tint_close      = heat(close_change,   hi_close,      close_change)

int row_count =
     (show_buy_vol ? 1 : 0) + (show_sell_vol ? 1 : 0) + (show_total_vol ? 1 : 0) + (show_delta_vol ? 1 : 0) + (show_pct_delta ? 1 : 0) +
     (show_buy_liq ? 1 : 0) + (show_sell_liq ? 1 : 0) + (show_total_liq ? 1 : 0) + (show_delta_liq ? 1 : 0) +
     (show_oi ? 1 : 0) + (show_net_long ? 1 : 0) + (show_net_short ? 1 : 0) +
     (show_funding ? 1 : 0) + (show_close ? 1 : 0)

float top_01 = row_count
float top_02 = top_01 - (show_buy_vol   ? 1 : 0)
float top_03 = top_02 - (show_sell_vol  ? 1 : 0)
float top_04 = top_03 - (show_total_vol ? 1 : 0)
float top_05 = top_04 - (show_delta_vol ? 1 : 0)
float top_06 = top_05 - (show_pct_delta ? 1 : 0)
float top_07 = top_06 - (show_buy_liq   ? 1 : 0)
float top_08 = top_07 - (show_sell_liq  ? 1 : 0)
float top_09 = top_08 - (show_total_liq ? 1 : 0)
float top_10 = top_09 - (show_delta_liq ? 1 : 0)
float top_11 = top_10 - (show_oi        ? 1 : 0)
float top_12 = top_11 - (show_net_long  ? 1 : 0)
float top_13 = top_12 - (show_net_short ? 1 : 0)
float top_14 = top_13 - (show_funding   ? 1 : 0)

int reserved_labels = show_names ? row_count : 0
int column_cap      = row_count > 0 ? int((500 - reserved_labels) / row_count) : 1
int numbered_bars   = math.max(1, math.min(column_cap, max_columns))

//              ╔════════════════════════════════╗
//              ║         VISUALIZATION          ║
//              ╚════════════════════════════════╝

bgcolor(pane_bg, title = 'Pane Background')

plot(show_buy_vol   ? top_01 : na, 'Buy Volume',         color = tint_buy,       style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_sell_vol  ? top_02 : na, 'Sell Volume',        color = tint_sell,      style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_total_vol ? top_03 : na, 'Total Volume',       color = tint_total,     style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_delta_vol ? top_04 : na, 'Delta Volume',       color = tint_delta,     style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_pct_delta ? top_05 : na, 'Percent Delta',      color = tint_percent,   style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_buy_liq   ? top_06 : na, 'Buy Liquidations',   color = tint_buy_liq,   style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_sell_liq  ? top_07 : na, 'Sell Liquidations',  color = tint_sell_liq,  style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_total_liq ? top_08 : na, 'Total Liquidations', color = tint_total_liq, style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_delta_liq ? top_09 : na, 'Delta Liquidations', color = tint_delta_liq, style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_oi        ? top_10 : na, 'Open Interest',      color = tint_oi,        style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_net_long  ? top_11 : na, 'Net Long',           color = tint_long,      style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_net_short ? top_12 : na, 'Net Short',          color = tint_short,     style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_funding   ? top_13 : na, 'Funding Rate',       color = tint_rate,      style = plot.style_columns, histbase = 0, display = display.pane, editable = false)
plot(show_close      ? top_14 : na, 'Close Price',        color = tint_close,      style = plot.style_columns, histbase = 0, display = display.pane, editable = false)

plot(0.0,                    'Scale Floor',   color = color.new(color.black, 100), display = display.pane, editable = false)
plot(math.max(row_count, 1), 'Scale Ceiling', color = color.new(color.black, 100), display = display.pane, editable = false)

var array<int>    column_bar = array.new<int>()
var array<string> cell_text  = array.new<string>()
var array<color>  cell_tint  = array.new<color>()

bool in_window = show_values and row_count > 0 and last_bar_index - bar_index < numbered_bars

if in_window
    int logged = column_bar.size() > 0 ? column_bar.get(column_bar.size() - 1) : -1
    if bar_index != logged
        column_bar.push(bar_index)
        for slot = 0 to row_count - 1
            cell_text.push('')
            cell_tint.push(zero_color)
        while column_bar.size() > numbered_bars
            column_bar.shift()
            for slot = 0 to row_count - 1
                cell_text.shift()
                cell_tint.shift()
    int cursor = cell_text.size() - row_count
    if show_buy_vol
        cell_text.set(cursor, format_value(shown_buy, as_quote)), cell_tint.set(cursor, tint_buy), cursor += 1
    if show_sell_vol
        cell_text.set(cursor, format_value(shown_sell, as_quote)), cell_tint.set(cursor, tint_sell), cursor += 1
    if show_total_vol
        cell_text.set(cursor, format_value(shown_total, as_quote)), cell_tint.set(cursor, tint_total), cursor += 1
    if show_delta_vol
        cell_text.set(cursor, format_value(shown_delta, as_quote)), cell_tint.set(cursor, tint_delta), cursor += 1
    if show_pct_delta
        cell_text.set(cursor, format_percent(percent_delta)), cell_tint.set(cursor, tint_percent), cursor += 1
    if show_buy_liq
        cell_text.set(cursor, format_value(buy_liq, false)), cell_tint.set(cursor, tint_buy_liq), cursor += 1
    if show_sell_liq
        cell_text.set(cursor, format_value(sell_liq, false)), cell_tint.set(cursor, tint_sell_liq), cursor += 1
    if show_total_liq
        cell_text.set(cursor, format_value(total_liq, false)), cell_tint.set(cursor, tint_total_liq), cursor += 1
    if show_delta_liq
        cell_text.set(cursor, format_value(delta_liq, false)), cell_tint.set(cursor, tint_delta_liq), cursor += 1
    if show_oi
        cell_text.set(cursor, format_value(shown_oi, as_quote)), cell_tint.set(cursor, tint_oi), cursor += 1
    if show_net_long
        cell_text.set(cursor, format_value(shown_long, as_quote)), cell_tint.set(cursor, tint_long), cursor += 1
    if show_net_short
        cell_text.set(cursor, format_value(shown_short, as_quote)), cell_tint.set(cursor, tint_short), cursor += 1
    if show_funding
        cell_text.set(cursor, format_rate(fr_raw, rate_multiplier)), cell_tint.set(cursor, tint_rate), cursor += 1
    if show_close
        cell_text.set(cursor, format_price(close_price)), cell_tint.set(cursor, tint_close), cursor += 1

var array<label> cell_pool = array.new<label>()

if barstate.islast
    if show_values and row_count > 0 and column_bar.size() > 0
        int pool_size = column_bar.size() * row_count
        if cell_pool.size() != pool_size
            for old_cell in cell_pool
                label.delete(old_cell)
            cell_pool.clear()
            for slot = 0 to pool_size - 1
                cell_pool.push(label.new(bar_index, 0.0, '', xloc = xloc.bar_index, style = label.style_none, size = cell_size()))
        for column = 0 to column_bar.size() - 1
            int anchor = column_bar.get(column)
            for row = 0 to row_count - 1
                int    slot    = column * row_count + row
                label  cell    = cell_pool.get(slot)
                string reading = cell_text.get(slot)
                color  shade   = cell_tint.get(slot)
                label.set_xy(cell, anchor, row_count - row - 0.5)
                label.set_text(cell, reading)
                label.set_textcolor(cell, reading == na_text ? muted_text(shade) : readable_text(shade))
    else
        for old_cell in cell_pool
            label.delete(old_cell)
        cell_pool.clear()

var array<label>  name_pool = array.new<label>()
var array<string> row_names = array.new<string>()
var array<string> row_tips  = array.new<string>()
var array<bool>   row_live  = array.new<bool>()

if barstate.islast
    if show_names and row_count > 0
        string tip_print = print_ever ? 'Aggressor side read from bid/ask data, showing which side crossed the spread on each trade. Buy plus sell always reconciles to total volume.' + (allow_estimate ? ' Bars the engine cannot serve fall back to a range-based approximation, marked with a tilde on this tag.' : ' Bars marked ' + na_text + ' have no bid/ask data for that period.') : allow_estimate ? 'Approximated from where each bar closed within its range, marked with a tilde on this tag. The direction is the more dependable part of the reading, the magnitude is indicative. Set Delta Engine to Bid/ask engine to read TradingView bid and ask data instead.' : 'Delta rows are switched off. Set Delta Engine under Data Source to Bid/ask engine to read TradingView bid and ask data, or to Estimate from bar range to approximate the split.'
        string tip_volume = 'Total traded volume for the bar, read directly from the charted contract. Available on every symbol that reports volume.'
        string tip_liq   = liq_ok ? 'Forced position closures, split by the side that was liquidated. A 0 means the feed is live and nothing was liquidated in that bar, which is different from ' + na_text + '.' : 'Liquidation data is not available for this ticker.'
        string tip_oi    = oi_ok ? 'Bar-over-bar change in the total contracts outstanding. Rising means new positions opened, falling means positions closed or were forced out. Read it against price to tell fresh money from unwinding.' : 'Open interest data is not available for this ticker.'
        string tip_net   = net_live ? 'Net long plus net short reconciles to delta, and net long minus net short reconciles to the open interest change, so the pair always ties back to both inputs and can be checked against the rows above.' : 'Needs both delta and open interest. One of the two is unavailable on this symbol, so the row cannot be calculated. That is not the same as a zero result.'
        string tip_rate  = fr_ok ? 'Funding rate in force during the bar. Positive means longs pay shorts and the crowd sits long. It settles on the exchange interval, usually every eight hours, so the row holds flat between settlements by design.' : 'Funding data is not available for this ticker.'
        string tip_close = 'Closing price of the charted contract for each bar, colored by the bar-over-bar change so the row reads as a price direction strip beneath the statistics.'

        string approx = print_ever or not allow_estimate ? '' : ' ~'

        row_names.clear()
        row_tips.clear()
        row_live.clear()

        if show_buy_vol
            row_names.push((short_names ? 'Buy vol' : 'Buy Volume') + approx), row_tips.push(tip_print), row_live.push(delta_live)
        if show_sell_vol
            row_names.push((short_names ? 'Sell vol' : 'Sell Volume') + approx), row_tips.push(tip_print), row_live.push(delta_live)
        if show_total_vol
            row_names.push(short_names ? 'Total vol' : 'Total Volume'), row_tips.push(tip_volume), row_live.push(not na(volume))
        if show_delta_vol
            row_names.push((short_names ? 'Delta vol' : 'Delta Volume') + approx), row_tips.push(tip_print), row_live.push(delta_live)
        if show_pct_delta
            row_names.push((short_names ? '% Delta' : 'Percent Delta') + approx), row_tips.push(tip_print), row_live.push(delta_live)
        if show_buy_liq
            row_names.push(short_names ? 'Buy liq' : 'Buy Liquidations'), row_tips.push(tip_liq), row_live.push(liq_ok)
        if show_sell_liq
            row_names.push(short_names ? 'Sell liq' : 'Sell Liquidations'), row_tips.push(tip_liq), row_live.push(liq_ok)
        if show_total_liq
            row_names.push(short_names ? 'Total liq' : 'Total Liquidations'), row_tips.push(tip_liq), row_live.push(liq_ok)
        if show_delta_liq
            row_names.push(short_names ? 'Delta liq' : 'Delta Liquidations'), row_tips.push(tip_liq), row_live.push(liq_ok)
        if show_oi
            row_names.push(short_names ? 'OI Δ' : 'Open Interest'), row_tips.push(tip_oi), row_live.push(oi_ok)
        if show_net_long
            row_names.push(short_names ? 'Net L' : 'Net Long'), row_tips.push(tip_net), row_live.push(net_live)
        if show_net_short
            row_names.push(short_names ? 'Net S' : 'Net Short'), row_tips.push(tip_net), row_live.push(net_live)
        if show_funding
            row_names.push(short_names ? 'Funding' : 'Funding Rate'), row_tips.push(tip_rate), row_live.push(fr_ok)
        if show_close
            row_names.push(short_names ? 'Close' : 'Close Price'), row_tips.push(tip_close), row_live.push(true)

        int name_anchor = time + int(timeframe.in_seconds() * 1000.0 * (0.5 + name_gap))
        if name_pool.size() != row_names.size()
            for old_name in name_pool
                label.delete(old_name)
            name_pool.clear()
            for slot = 0 to row_names.size() - 1
                name_pool.push(label.new(name_anchor, 0.0, '', xloc = xloc.bar_time, style = label.style_label_left, size = size.small))
        for slot = 0 to row_names.size() - 1
            label tag  = name_pool.get(slot)
            bool  live = row_live.get(slot)
            color face = live ? name_bg : name_bg_off
            label.set_xy(tag, name_anchor, row_count - slot - 0.5)
            label.set_text(tag, '  ' + row_names.get(slot) + (live ? '' : '  ' + na_text) + '  ')
            label.set_color(tag, face)
            label.set_textcolor(tag, live ? readable_text(face) : muted_text(face))
            label.set_tooltip(tag, row_names.get(slot) + '\n\n' + row_tips.get(slot))
    else
        for old_name in name_pool
            label.delete(old_name)
        name_pool.clear()


//              ╔════════════════════════════════╗
//              ║             ALERTS             ║
//              ╚════════════════════════════════╝

buy_volume_up                = rising(shown_buy)
buy_volume_down              = falling(shown_buy)
sell_volume_up               = rising(shown_sell)
sell_volume_down             = falling(shown_sell)
total_volume_up              = rising(shown_total)
total_volume_down            = falling(shown_total)
delta_volume_positive        = turns_positive(shown_delta)
delta_volume_negative        = turns_negative(shown_delta)
percent_delta_up             = rising(percent_delta)
percent_delta_down           = falling(percent_delta)
buy_liquidations_up          = rising(buy_liq)
buy_liquidations_down        = falling(buy_liq)
sell_liquidations_up         = rising(sell_liq)
sell_liquidations_down       = falling(sell_liq)
total_liquidations_up        = rising(total_liq)
total_liquidations_down      = falling(total_liq)
delta_liquidations_positive  = turns_positive(delta_liq)
delta_liquidations_negative  = turns_negative(delta_liq)
open_interest_positive       = turns_positive(shown_oi)
open_interest_negative       = turns_negative(shown_oi)
net_long_positive            = turns_positive(shown_long)
net_long_negative            = turns_negative(shown_long)
net_short_positive           = turns_positive(shown_short)
net_short_negative           = turns_negative(shown_short)
funding_rate_up              = rising(fr_raw)
funding_rate_down            = falling(fr_raw)
close_price_up               = rising(close_price)
close_price_down             = falling(close_price)

alertcondition(buy_volume_up,               title = 'Buy Volume Rising', message = 'Bar Statistics: buy volume rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(buy_volume_down,             title = 'Buy Volume Falling', message = 'Bar Statistics: buy volume fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(sell_volume_up,              title = 'Sell Volume Rising', message = 'Bar Statistics: sell volume rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(sell_volume_down,            title = 'Sell Volume Falling', message = 'Bar Statistics: sell volume fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(total_volume_up,             title = 'Total Volume Rising', message = 'Bar Statistics: total volume rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(total_volume_down,           title = 'Total Volume Falling', message = 'Bar Statistics: total volume fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(delta_volume_positive,       title = 'Delta Volume Turns Positive', message = 'Bar Statistics: delta volume turned positive, buyers took control on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(delta_volume_negative,       title = 'Delta Volume Turns Negative', message = 'Bar Statistics: delta volume turned negative, sellers took control on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(percent_delta_up,            title = 'Percent Delta Rising', message = 'Bar Statistics: percent delta rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(percent_delta_down,          title = 'Percent Delta Falling', message = 'Bar Statistics: percent delta fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(buy_liquidations_up,         title = 'Buy Liquidations Rising', message = 'Bar Statistics: buy liquidations rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(buy_liquidations_down,       title = 'Buy Liquidations Falling', message = 'Bar Statistics: buy liquidations fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(sell_liquidations_up,        title = 'Sell Liquidations Rising', message = 'Bar Statistics: sell liquidations rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(sell_liquidations_down,      title = 'Sell Liquidations Falling', message = 'Bar Statistics: sell liquidations fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(total_liquidations_up,       title = 'Total Liquidations Rising', message = 'Bar Statistics: total liquidations rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(total_liquidations_down,     title = 'Total Liquidations Falling', message = 'Bar Statistics: total liquidations fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(delta_liquidations_positive, title = 'Delta Liquidations Turns Positive', message = 'Bar Statistics: liquidation delta turned positive on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(delta_liquidations_negative, title = 'Delta Liquidations Turns Negative', message = 'Bar Statistics: liquidation delta turned negative on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(open_interest_positive,      title = 'Open Interest Turns Positive', message = 'Bar Statistics: open interest turned positive, positions building on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(open_interest_negative,      title = 'Open Interest Turns Negative', message = 'Bar Statistics: open interest turned negative, positions unwinding on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(net_long_positive,           title = 'Net Long Turns Positive', message = 'Bar Statistics: net long turned positive on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(net_long_negative,           title = 'Net Long Turns Negative', message = 'Bar Statistics: net long turned negative on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(net_short_positive,          title = 'Net Short Turns Positive', message = 'Bar Statistics: net short turned positive on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(net_short_negative,          title = 'Net Short Turns Negative', message = 'Bar Statistics: net short turned negative on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(funding_rate_up,             title = 'Funding Rate Rising', message = 'Bar Statistics: funding rate rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(funding_rate_down,           title = 'Funding Rate Falling', message = 'Bar Statistics: funding rate fell on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(close_price_up,              title = 'Close Price Rising', message = 'Bar Statistics: close rose on {{exchange}}:{{ticker}} - {{interval}}')
alertcondition(close_price_down,            title = 'Close Price Falling', message = 'Bar Statistics: close fell on {{exchange}}:{{ticker}} - {{interval}}')

//              ╔════════════════════════════════╗
//              ║           CREATED BY           ║
//              ╚════════════════════════════════╝

// ██████╗ ██╗   ██╗ █████╗ ███╗   ██╗████████╗     █████╗ ██╗      ██████╗  ██████╗ 
//██╔═══██╗██║   ██║██╔══██╗████╗  ██║╚══██╔══╝    ██╔══██╗██║     ██╔════╝ ██╔═══██╗
//██║   ██║██║   ██║███████║██╔██╗ ██║   ██║       ███████║██║     ██║  ███╗██║   ██║
//██║▄▄ ██║██║   ██║██╔══██║██║╚██╗██║   ██║       ██╔══██║██║     ██║   ██║██║   ██║
//╚██████╔╝╚██████╔╝██║  ██║██║ ╚████║   ██║       ██║  ██║███████╗╚██████╔╝╚██████╔╝
// ╚══▀▀═╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝       ╚═╝  ╚═╝╚══════╝ ╚═════╝  ╚═════╝

Overview

Order Flow Bar Statistics [QuantAlgo] tracks aggressive buy and sell volume, total volume, volume delta, long and short liquidations, open interest changes, net positioning, funding rates, and close prices. Users can customize which statistics are visible, adjust footprint row sizing and heat lookback periods, format numerical outputs, and choose positioning calculation methods. It helps traders evaluate buyer versus seller conviction and spot absorption across individual bars.

Details

Published by

theonetrade on GitHub

Code credit

QuantAlgo, as written in the script's header

Draws

Separate pane below the chart

Markets

Crypto

Timeframes

M1-M5, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Buy Volumebooltrueshow_buy_vol
Sell Volumebooltrueshow_sell_vol
Total Volumebooltrueshow_total_vol
Delta Volumebooltrueshow_delta_vol
Percent Deltabooltrueshow_pct_delta
Liquidation NamingstringLiquidated position sideliq_naming
Buy Liquidationsbooltrueshow_buy_liq
Sell Liquidationsbooltrueshow_sell_liq
Total Liquidationsbooltrueshow_total_liq
Delta Liquidationsbooltrueshow_delta_liq
Open Interestbooltrueshow_oi
Net Longbooltrueshow_net_long
Show all 40 settings
SettingTypeDefaultVariable
Net Shortbooltrueshow_net_short
Positioning MethodstringDelta and OI splitnet_mode
Funding Ratebooltrueshow_funding
Close Pricebooltrueshow_close
Funding ScalestringDecimal to percentfr_scale
Funding HeatstringLevelfr_heat_mode
Display ModestringCoindisplay_mode
Heat Lookbackint50heat_length
Footprint Row Sizeint5000ticks_per_row
Delta EnginestringBid/ask enginedelta_engine
Swap Liquidation Feedsboolfalseswap_feeds
Abbreviate Thousandsbooltrueabbreviate
DecimalsstringAutodecimal_mode
Missing Data TextstringN/Ana_text
Show Row Namesbooltrueshow_names
Row Name StylestringFullname_style
Row Name Gapfloat0.15name_gap
Show Numbersbooltrueshow_values
Max Numbered Barsint30max_columns
Color PresetstringCustomcolor_preset
Bullish Colorcolor#00ffaabullish_input
Bearish Colorcolor#ff0000bearish_input
Zero Colorcolor#141414zero_color
Intensity Gammafloat0.55heat_gamma
Cell Text SizestringSmalltext_size_in
Tint Total By Deltabooltruetint_by_delta
Pane Backgroundcolor#000000pane_bg
Row Name Backgroundcolor#2a2a2aname_bg
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Oscillator Suite

by TamaraKGreen
47 stars

Oscillator Suite plots a normalised price oscillator in a separate pane and overlays a signal line that can use SMA, EMA, WMA, HMA, RMA, VWMA, T3, ZEMA, KAMA, or GKEMA. It marks bullish and bearish divergences, a smoothed money-flow series, confluence areas an

Indicator v5 Oscillators & momentumDivergence
Updated 2 months ago · None stated GitHub repository of Oscillator Suite

Relative Strength Table

by ChartsLector
41 stars

This indicator builds a table of relative strength for up to six user-chosen symbols against a benchmark, defaulting to SPY. It measures strength over four lookback periods, can average the visible periods, and can add relative volume as current volume divided

Indicator v6 Screeners & dashboardsVolume
Updated 4 weeks ago · None stated GitHub repository of Relative Strength Table

Session Pulse v2

by Matswm86
29 stars

Session Pulse v2 is a separate-pane intraday indicator designed for futures trading. It compares real-time volume, price range, and efficiency against multi-session historical medians for the exact same clock minute. The indicator classifies market conditions

Indicator v6 VolumeVolatility & bands
Updated 6 weeks ago · MIT GitHub repository of Session Pulse v2

This indicator calculates the Relative Strength Index (RSI) alongside a simple moving average to generate directional momentum signals in a separate pane. It supports Break Flip and Break Continuous scanning modes for long and short setups. A wide array of opt

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of Momentum Setup: RSI Direction Confirmation
11 stars

This indicator plots a smoothed Z-score of cumulative volume delta in a separate pane, showing whether buying or selling pressure is dominant and when the reading enters extreme zones. It marks spot accumulation, climax or exhaustion, and pivot-based price-vol

Indicator v6 Oscillators & momentumVolume Repaints
Updated 2 months ago · MIT GitHub repository of CVD Z-Score [NeuNue]

Intrabar Delta

by jayadevrana
11 stars

Intrabar Delta estimates buying and selling volume within each chart bar by fetching lower timeframe OHLCV data. It categorizes lower timeframe bars as bullish, bearish, or neutral to calculate buy and sell volume. The script plots the net intrabar volume delt

Indicator v6 VolumeScreeners & dashboards
Updated 4 weeks ago · MPL-2.0 GitHub repository of Intrabar Delta

More Volume scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers