Open terminal

Scripts · Reference

The script language

Write your own indicators, run them on the chart and share them. This is the complete guide to the language: how a script runs, the data it can read, every built-in function, and examples you can open in one click.

Updated 15 Nov 2026 · Back to the overview · Short intro in the Handbook

Overview

ZScript is a small language for writing your own indicators and running them on the chart. A script reads the same data the chart already shows you — candles, footprint, large prints — and draws lines, markers, boxes and background colors. It is built so that other people's scripts are safe to try.

Runs on your machine

Everything is calculated in your browser. Nothing is uploaded and nothing is sent to our servers.

Reads what your plan shows

A script sees the data the matching tool would show you on your plan, symbol and timeframe. It cannot see more.

Draws, nothing else

No network, no files, no account access. The only output is drawing on your chart, so imported scripts cannot leak or change anything.

Where to find it
Click Scripts in the top bar to open the script editor — a floating panel for writing code, with tabs, line numbers, errors and inputs. Your scripts then appear in Indicators → My scripts, next to the built-in indicators, where you switch them on and off. The gear next to a script (in the chart legend or in the list) opens its settings — the inputs only — and the pencil opens its code. Indicators → Community lists scripts other people published. This page is the full reference.

Your first script

  1. Click Scripts in the top bar to open the script editor, then press + (or pick one from Templates).
  2. Replace the code with the script below (or press Open in Scripts on it, which opens the Import screen).
  3. Switch the script on with On chart. The line appears on the chart; change Length in the Inputs box under the editor and it updates at once.
A moving average
indicator "Hello" overlay
input length = 20 "Length" min 2 max 500

onBar {
  plot(sma(close, length), "SMA", color = BLUE, width = 2)
}

Three things are happening here:

  • indicator "Hello" overlay names the script and draws it on the price chart.
  • input length = 20 ... becomes a numeric field in the Inputs box under the editor (with the limits you give).
  • onBar { ... } is the code that runs for every bar. sma(close, length) is the average of the last 20 closes and plot draws it.

The whole language on one screen

Cheat sheet
indicator "Name" overlay            // or: pane (own pane for plot)
needs footprint                     // levels, buy, sell, delta     |   needs tape → trades
                                    // needs gex → gex   |   needs options → opts, callPrem…   |   needs book → book
                                    // needs oi → oi   |   needs liq → liqBuy, liqSell
input length = 20 "Length" min 2 max 500
input side = "both" "Side" options("buy", "sell", "both")
input on = true "Show marks"        // true / false → a switch;  #rrggbb → a color picker

fn mid(a, b) = (a + b) / 2          // your own helper

onBar {                             // runs once per bar, oldest → newest
  let x = close - open              // new value on each bar;  x[1] = the previous bar
  var count = 0                     // keeps its value from bar to bar
  if x > 0 { count += 1 } else { count = 0 }
  for i in 0..3 { count += 0 }      // 0, 1, 2
  plot(sma(close, length), "SMA", color = BLUE)
  mark(on and x > 0, high, "up", "triangleDown", ORANGE, 1, "above")
}

How a script runs

The onBar block runs once for every bar, from the oldest loaded bar to the newest. On each run the script can see that bar and every earlier bar — never a later one.

bar 0onBar runs
→
bar 1onBar runs
→
bar 2onBar runs
→
last barruns again on every update

Why that matters

  • No look-ahead. A signal can only use information that existed on its bar, so it cannot "know" the future. Closed bars never change.
  • Replay behaves like live. In Replay the script receives bars only up to the replay clock, exactly as it would have live.
  • The last bar is live. While it is open the script runs again on every update, so its marks can change until it closes (see Gotchas).
  • It is fast. After the first run only the last few bars are recalculated.

Remembering things between bars

Declared withBehaviour
New each barlet x = …Calculated again on every bar. x[1] is its value on the previous bar, x[2] two bars ago.
Keptvar x = …Set once on the first bar, then keeps its value; change it with x = … or x += ….
Built inclose, high…History works the same way: close[1], high[3].

Missing values (na)

Early bars and impossible calculations produce na ("not available"). The rules are simple: arithmetic with na gives na; comparisons with na are false; dividing by zero gives na; plotting na leaves a gap; mark and box with an na price draw nothing. Use isna(x) to test and nz(x, 0) to replace.

Script structure

A script is a few header lines followed by optional fn helpers and one onBar block. Order of the header lines does not matter. Comments start with //.

PartSyntaxWhat it does
Nameindicator "Name" overlayNames the script. overlay draws on the price chart (default). pane gives plot() its own pane below the chart; marks, boxes and background tints still go on the price chart.
Dataneeds footprint
needs footprint, tape
Declares which data the script uses: footprint unlocks levels, buy, sell, delta; tape unlocks trades; gex unlocks gex; options unlocks opts, callPrem, putPrem, bullPrem, bearPrem, optCount; book unlocks book. Without the line the script cannot use them.
Inputsinput len = 20 "Length" min 2 max 500A setting the user can change without touching the code. See Inputs.
Helpersfn name(a, b) = exprYour own function. See Functions and lambdas.
BodyonBar { … }The code that runs for every bar. Exactly one per script.

Values and operators

KindExamplesNotes
number42 0.5 1e6 -3All numbers are decimal numbers.
booltrue falseConditions. false, na, 0 and "" count as false everywhere a condition is expected; everything else is true.
string"Abs " 'up'Text for labels. + joins text and numbers: "Vol " + volume. Escape with a backslash: "say \"hi\"".
color#22d3ee #22d3ee80 BUY#rrggbb or #rrggbbaa; named colors BUY SELL WHITE GRAY YELLOW ORANGE PURPLE GREEN RED BLUE PINK; alpha(color, 0.3) changes opacity.
nanaThe missing value (see How a script runs).
list / recordlevels big.priceData from the chart — see Lists and records.

Operators

From the loosest to the tightest binding:

OperatorsMeaning
a ? b : cIf a then b else c.
or   ||Either is true. Stops early when the left side is true.
and   &&Both are true. Stops early when the left side is false.
==   !=Equal / not equal (numbers, text, na).
< <= > >=Comparison. False when either side is na.
+   -Add, subtract. + also joins text.
*   /   %Multiply, divide, remainder. Dividing by zero gives na.
-x   not x   !xNegate; logical not.
x ** yPower, right to left: 2 ** 3 ** 2 is 512. Binds tighter than a minus sign: -2 ** 2 is -4.
f(x)   a.b   a[i]Call, field, index.
Line breaks
A statement ends at the end of the line (or ;). Lines continue inside ( ) and [ ], after an operator at the end of the line, and a line may start with and / or. The { of a block may sit on the next line, and so may else.

Variables and flow

let, var and assignment

onBar {
  let body = close - open        // let: calculated on every bar
  var wins = 0                   // var: starts at 0, then keeps its value
  if body > 0 {
    wins += 1                    // also: -=  *=  /=  or plain =
  }
  plot(wins, "up bars")
}

if / else

onBar {
  let dir = 0
  if close > open {
    dir = 1
  } else if close < open {
    dir = -1
  } else {
    dir = 0
  }
  plot(dir, "dir", style = "histogram")
}

For a quick choice use the conditional expression: let dir = close > open ? 1 : -1.

for

Two forms: a number range (the end is not included) and every item of a list.

indicator "Loops" pane
needs footprint

onBar {
  var n = 0
  for i in 0..5 { n += i }            // adds 0+1+2+3+4
  let total = 0
  for l in levels { total += l.total } // every price row of the bar
  plot(total, "volume (rows)")
}
Prefer list methods
levels.sumBy("total") does the same as the loop and is cheaper. Loops are counted against the compute budget (Limits).

Functions and lambdas

Write a helper once and use it many times. A function is either a single expression or a block with return.

fn mid(a, b) = (a + b) / 2

fn bodyPct(o, c, h, l) {
  let range = h - l
  if range == 0 { return 0 }
  return abs(c - o) / range * 100
}

onBar {
  plot(mid(high, low), "mid")
  plot(bodyPct(open, close, high, low), "body %")
}
  • Arguments can be named when calling: mid(b = low, a = high).
  • A function can read inputs and built-in series, but cannot change your variables and cannot call itself (no recursion).
  • Indicators that keep state (sma, ema…) must be called in onBar, not inside your own functions.

Lambdas

A short unnamed function written x => expression or (a, b) => expression. They are used with list methods, and can be stored in a variable.

indicator "Heavy rows" pane
needs footprint

onBar {
  let big = levels.filter(l => l.total > 200)
  let heavy = big.sumBy(l => l.buy + l.sell)
  plot(heavy, "heavy rows")
}

Lists and records

Chart data comes as lists of records. A record has named fields you read with a dot; a list holds items you read with a method, an index or a for loop.

indicator "Rows and records" overlay
needs footprint

onBar {
  let big = levels.maxBy("total")     // one record (the busiest row)
  let n = len(levels)                 // number of rows
  let first = levels[0]               // first row (lowest price)
  let last = levels[-1]               // last row (highest price)
  mark(big.sell > big.buy, big.price, "S " + fmt(big.sell, 0))
}
  • Fields of a missing record (na) are na, so levels.maxBy("total").price is safe on a bar with no rows.
  • Methods take either a field name ("total") or a lambda (l => l.buy - l.sell). See List methods.
  • You can write a list yourself: [1, 2, 3] (it may span several lines). Lists also come from the data and from list methods.

Inputs

An input line declares a setting. The editor builds a form from it, remembers the value per script, and the script reads it as an ordinary variable.

The five kinds
indicator "Inputs demo" overlay
input length  = 20       "Length"  min 2 max 500     // number
input minVol  = 40       "Minimum volume"           // number, no limits
input showText = true    "Show text"                // switch
input side    = "both"   "Side" options("buy", "sell", "both")   // drop-down
input tint    = #8b5cf6  "Color"                    // color picker

onBar { plot(sma(close, length), "SMA", color = tint) }
Default valueBecomesOptions
a numbernumber fieldmin and max clamp the value. With both (a span up to 2 000) the form shows a slider next to the number.
true / falseswitch
a string + options(...)drop-downThe default must be one of the options.
a stringtext field
#rrggbbcolor picker

The text in quotes after the default is the label shown in the Inputs box. Input names must be unique and cannot be built-in names.

Hints and groups

Two more words can follow an input: tip "..." adds a hint (a ? next to the label; hover it), and group "..." starts a titled group — every input after it belongs to that group until the next group.

indicator "Grouped inputs" overlay
input length = 20 "Length" min 2 max 200 group "Average" tip "How many bars the average looks back."
input src = "close" "Source" options("close", "hl2")
input up = #4ade80 "Up colour" group "Look"
input down = #f87171 "Down colour"

onBar {
  let v = src == "close" ? close : hl2
  plot(sma(v, length), "Average", color = close > open ? up : down)
}

Bar data

These names are always available inside onBar. Add [n] for history (close[1] is the previous close).

NameMeaningNeeds
timeBar open time, seconds since 1970 (UTC).—
open, high, low, closePrices of the bar.—
volumeVolume of the bar. With needs footprint it equals buy + sell when the candle has no volume of its own.—
indexBar number, 0 for the first loaded bar. Used to place boxes and lines.—
hl2, hlc3, ohlc4(high + low) / 2, (high + low + close) / 3, (open + high + low + close) / 4.—
dayUTC day number (days since 1970).—
hourUTC hour 0–23.—
newdayTrue on the first bar of each UTC day. Use it to restart a running total (see the VWAP example).—
dowUTC day of the week: 0 = Sunday … 6 = Saturday.—
sessionStartTrue on the first bar of each trading session (and on the first loaded bar). See Sessions and data history.—
sessionMinMinutes since the session opened (0 on the opening bar).—
sessionDaySession number: goes up by one at each session open. Equal for all bars of one session.—
sessionOpen, sessionEndOpen time and close time of the bar's session, in seconds (UTC). The close is also when same-day options expire (see Sessions and data history).—
minToCloseMinutes left until the session closes (0 once it has closed). Handy for 0DTE: gamma and charm change fastest in the last hour.—
inSessionTrue while the bar is inside regular hours (between the open and the close). False before the open and after the close.—
sessionFracHow far through the session the bar is, from 0 (open) to 1 (close).—
hasDataTrue on bars where every kind of data the script needs has started. False before that (those bars have na, empty lists or zero premium).—
dataFromTime (seconds, UTC) from which all the data the script needs exists; na while some data is still missing.—
buy, sell, deltaAggressive buy volume, sell volume and buy − sell of the bar.footprint
levelsList of price rows of the bar, with the volume traded on each (below).footprint
tradesList of large prints that happened in the bar (below).tape
gexRecord with the gamma levels and net exposure as they stood at the end of the bar (below).gex
optsList of options prints that happened in the bar (below).options
callPrem, putPremTotal premium (USD) of call prints and of put prints in the bar.options
bullPrem, bearPremPremium of bullish prints (buy call, sell put) and of bearish prints (sell call, buy put).options
optCountNumber of options prints in the bar.options
bookRecord with the order book at the end of the bar: mid, bids, asks (below).book
oiFutures open interest at the end of the bar (contracts / coins), or na when there is no sample for that bar. Needs needs oi.oi
liqBuy, liqSellFutures liquidations in the bar, in USD: liqBuy = shorts that were force-closed (forced buys), liqSell = longs that were force-closed (forced sells). 0 when there were none. Needs needs liq.liq

Footprint levels

With needs footprint, levels is the list of price rows of the current bar, lowest price first. Rows use your Footprint price step — the same rows the Footprint chart draws.

FieldMeaning
priceLower edge of the row.
buyVolume bought aggressively at this row (market buys hitting the offer).
sellVolume sold aggressively at this row.
totalbuy + sell.
deltabuy − sell.
indicator "Busiest row" overlay
needs footprint

onBar {
  let big = levels.maxBy("total")
  mark(big.total > 0, big.price, fmt(big.total, 0), "square", YELLOW)
}

Large prints

With needs tape, trades is the list of large prints that happened during the current bar, oldest first. These are the trades above the shared large-trade floor — the same ones BigTrade Bubbles show — not every tick.

FieldMeaning
timeSeconds since 1970 (UTC).
priceExecution price.
sizeSize of the print.
side"buy" (aggressive buyer) or "sell".
indicator "Print balance" pane
needs tape

onBar {
  let b = trades.filter(t => t.side == "buy").sumBy("size")
  let s = trades.filter(t => t.side == "sell").sumBy("size")
  plot(b - s, "net prints", color = PURPLE, style = "histogram")
}

GEX

With needs gex, gex is a record with the gamma exposure the GEX Heatmap shows, as it stood at the end of the current bar: each value is the latest one published up to that moment, so an old bar keeps the numbers it had then. A value that does not exist yet is na.

FieldMeaning
flipGamma flip price.
callWall, putWallCall wall and put wall prices.
maxPainMax pain price.
emUpper, emLowerUpper and lower edge of the expected move.
net, netChex, netDexNet GEX, net charm exposure and net delta exposure.
heatList of {{price, value}}: the signed exposure on each price row of the heatmap during this bar, lowest price first. Empty where the heatmap has no data. Read it only when you need it; it is built on demand.

The values follow the GEX settings of the chart (asset, expiry scope, metric): the script reads the same feed the heatmap draws. gex[1].flip is the flip of the previous bar, like any bar series.

indicator "Flip distance" pane
needs gex

onBar {
  plot((close - gex.flip) / close * 100, "% from flip", color = YELLOW)
  hline(0, color = GRAY)
}

Options prints

With needs options, opts is the list of options prints that happened during the current bar, oldest first: the same options tape the Options Bubbles show for the symbol you are viewing. Five numbers per bar are ready-made so you do not have to add them up.

FieldMeaning
timeSeconds since 1970 (UTC).
type"call" or "put".
side"buy" when the buyer of the option was aggressive, "sell" otherwise.
strike, expiry, dteStrike, expiry date (text) and days left to expiry at the time of the print. dte is a fractional number of days (0.5 = twelve hours left).
otm, moneynessotm is true when the option was out of the money at the print (call: strike above spot; put: strike below spot). moneyness is strike / spot (above 1: the strike sits above the price).
size, price, premiumContracts, price per contract and total premium in USD.
spotUnderlying price at the time of the print.
block, combotrue for a block trade; the structure name when the print belongs to a combo, otherwise empty text.

Ready-made per bar: callPrem, putPrem (premium by option type), bullPrem (buy call + sell put), bearPrem (sell call + buy put) and optCount. Bullish and bearish are counted the same way as in the Options Tape widget.

indicator "Big options prints" overlay
needs options
input minPremium = 250000 "Minimum premium (USD)" min 0

onBar {
  let big = opts.filter(t => t.premium >= minPremium)
  let calls = big.filter(t => t.type == "call").sumBy("premium")
  let puts = big.filter(t => t.type == "put").sumBy("premium")
  mark(calls > puts and calls > 0, low, text = "C " + fmt(calls / 1000, 0) + "k", shape = "triangleUp", color = BUY, pos = "below")
  mark(puts > calls and puts > 0, high, text = "P " + fmt(puts / 1000, 0) + "k", shape = "triangleDown", color = SELL, pos = "above")
}

Order book

With needs book, book is the order book at the end of the current bar, taken from the per-minute snapshots of the Orderbook Heatmap. It is a record: mid (mid price), bids (highest price first) and asks (lowest price first); each item is {price, size}. A bar with no snapshot yet has book = na.

A book can hold thousands of rows, so prefer the helpers in the reference (bookDepth, bookWall, bookImbalance) over looping through bids and asks yourself.

indicator "Book pressure" pane
needs book

onBar {
  plot(bookImbalance(book, 1), "imbalance", color = PURPLE, style = "histogram")
  hline(0, color = GRAY)
}

Open interest and liquidations

With needs oi, oi is the futures open interest at the end of the current bar (the same data as the OI pane). A bar with no sample yet has oi = na; use oi - oi[1] for the change from the previous bar.

With needs liq, liqBuy and liqSell are the USD value of futures liquidations inside the bar: liqBuy = short positions that were force-closed (the exchange buys), liqSell = long positions that were force-closed (the exchange sells). Both are 0 on quiet bars.

Both cover the last 24 hours and are free for every account, like the OI and Liquidations panes. They exist for BTC, ETH, gold and silver perps (OI also for SP500 and XYZ100). On another symbol the script shows a message that the data is not available.

indicator "OI change and liquidations" pane
needs oi, liq

onBar {
  plot(oi - oi[1], "OI change", color = PURPLE, style = "histogram")
  plot(liqSell - liqBuy, "Liquidations (long - short)", color = RED)
  hline(0, color = GRAY)
}

Sessions and data history

Trading sessions

A session has an open and a close. For options the close is also the expiry time of same-day (0DTE) options, so a script can ask how long is left. Built-in values:

ValueMeaning
sessionStartTrue on the first bar of a session (and on the first loaded bar).
sessionMin, sessionFracMinutes since the open, and how far through the session the bar is (0–1).
minToCloseMinutes until the close / expiry; 0 once it has passed.
inSessionTrue between the open and the close (regular hours). Bars before the open or after the close are false.
sessionOpen, sessionEndThe open and close time of the bar's session, in seconds (UTC).
sessionDayA number that goes up at each open; the same for every bar of one session.

Daylight saving time for New York is handled for you, and so are the NYSE half days (13:00 close on the Friday after Thanksgiving, 24 December and 3 July when they fall Monday to Thursday). Public holidays are not listed: a closed day simply has no bars.

The hours depend on the symbol you are viewing, unless the script says otherwise:

SymbolDefault hoursClose / expiry
Stocks / ETFs / indices (GLD, SPY, QQQ, SPX, US500, USTEC…)ET 09:30-16:0016:00 New York (13:00 on half days) — when same-day options expire
Gold and silverET 18:00-17:0017:00 New York the next day, one hour before the next open
BTC / ETHUTC 08:00No separate close: the session lasts 24 hours and ends at the next 08:00 UTC, when the daily option expiries roll
Anything elseUTC 00:0024 hours, ends at the next 00:00 UTC

To choose your own, put session "ET 09:30-16:00" (New York time) or session "UTC 08:00-21:00" on the indicator line. With only an open (session "UTC 08:00") the session lasts until the next open. Bars outside regular hours (pre-market, after the close) still belong to the session that came before them, so inSession is the way to filter them out.

indicator "Last hour of 0DTE" pane session "ET 09:30-16:00"
needs options
onBar {
  let last = inSession and minToClose <= 60
  plot(last ? bullPrem - bearPrem : na, "net premium, last hour", style = "histogram")
  if sessionStart { print("session closes at", sessionEnd) }
}
indicator "Session delta" pane session "ET 09:30"
needs footprint
onBar {
  var run = 0
  if sessionStart { run = 0 }
  run += delta
  plot(run, "delta since open", color = BUY, style = "histogram")
}

How far back the data goes

Footprint, large prints, options prints, GEX and the order book each start at a different time (see What a script can see). Use hasData to skip the bars before that, and dataFrom to see where it starts:

indicator "Premium since data starts" pane
needs options
onBar {
  plot(hasData ? bullPrem - bearPrem : na, "net premium")
  if hasData and not hasData[1] { print("options data starts at", dataFrom) }
}

Looking at values

print(label, value) shows a value for the latest bar in the Runtime tab of the editor — handy while you write a script. Lists show their first eight items, and records show their fields.

Heatmaps

A heatmap colours a grid of bar × price band by a value. The usual recipe has three steps, and each one has a built-in that keeps it cheap:

  1. Group the data of the bar into price bands with groupSum — one pass, however many bands.
  2. Accumulate (optional) with mergeSum — keep a running total per band across bars, and restart it at sessionStart.
  3. Draw one heatcell per band. The colour scale is automatic.
indicator "Net premium heat" overlay
needs options
input band = 500 "Strike band" min 1
onBar {
  var acc = []
  if sessionStart { acc = [] }
  let now = opts.groupSum("strike", t => (t.type == "call") == (t.side == "buy") ? t.premium : -t.premium, band)
  acc = mergeSum(acc, now)
  for r in acc { heatcell(abs(r.sum) > 0, r.key, r.key + band, r.sum) }
}

Green is bullish (buy call, sell put) and red is bearish. Swap acc for now in the last line to see only what happened in each bar instead of the running total.

Tips

  • Do not write one filter + sumBy per band: it reads every item once per band and quickly exhausts the compute budget on long charts. groupSum reads each item once.
  • Bands start at multiples of step (key = floor(strike / step) * step), so they line up from bar to bar and between sessions.
  • Lists you build with groupSum and mergeSum are new lists each time; keep them in a var to carry them to the next bar.
  • Hide noise with the condition: heatcell(abs(r.sum) > minAbs, …).
  • Two or more heatmaps in one script can use different colours with pos / neg.

What a script can see

A script has no special access. It reads the same data stores the chart tools use, so what it sees follows what you can see:

  • Symbol. Each kind of data exists on the symbols where the matching tool exists: footprint and large prints (perps), GEX, options prints (crypto, gold and the ETFs that have Options Bubbles) and the order book (symbols with the Orderbook Heatmap). If you open a script on another symbol, the editor says the data is not available and the script waits.
  • Plan. Whatever limits your plan puts on a tool (live only, delayed, shorter history) apply to a script that uses the same data.
  • History depth. A script sees the bars the chart has loaded, and for each kind of data only as far back as that data has been loaded: options prints and order-book snapshots start from what the chart holds (recent hours to days), GEX from the heatmap's history. Bars before that have no value (na, an empty list, or zero premium). Scrolling back loads more.
  • Timeframe. levels are grouped into the bars of the current timeframe, with your Footprint price step.
Not trading signals
Scripts and the ready-made examples display conditions in the order flow. They do not tell you what to trade.

Reference

Every built-in function, with its arguments and defaults. Press / to search.

Math and utility

#mergeSum(a, b)→ list

Adds two lists from groupSum together, key by key, and returns a new list sorted by key. Use it to accumulate across bars: acc = mergeSum(acc, thisBar). Anything that is not a list counts as empty.

ArgumentDefaultMeaning
arequiredlist from groupSum (or empty)
brequiredlist from groupSum
var acc = []
acc = mergeSum(acc, opts.groupSum("strike", "premium", 500))

#abs(x)→ number

Absolute value.

ArgumentDefaultMeaning
xrequirednumber
plot(abs(close - open), "body")

#sqrt(x)→ number

Square root. Negative input gives na.

ArgumentDefaultMeaning
xrequirednumber
let r = sqrt(volume)

#log(x)→ number

Natural logarithm. Zero or negative gives na.

ArgumentDefaultMeaning
xrequirednumber
let lv = log(volume)

#exp(x)→ number

e raised to x.

ArgumentDefaultMeaning
xrequirednumber
let g = exp(0.5)

#sign(x)→ number

-1, 0 or 1.

ArgumentDefaultMeaning
xrequirednumber
let dir = sign(close - open)

#floor(x)→ number

Round down to a whole number.

ArgumentDefaultMeaning
xrequirednumber
let k = floor(close / 100)

#ceil(x)→ number

Round up to a whole number.

ArgumentDefaultMeaning
xrequirednumber
let k = ceil(close / 100)

#round(x, d)→ number

Round to d decimals.

ArgumentDefaultMeaning
xrequirednumber
d0decimals
let p = round(close, 1)

#pow(x, y)→ number

Same as x ** y.

ArgumentDefaultMeaning
xrequiredbase
yrequiredexponent
let sq = pow(delta, 2)

#max(a, b, …)→ number

Largest value. na if any value is na.

ArgumentDefaultMeaning
a, b, …requiredany number of values
let hi = max(open, close)

#min(a, b, …)→ number

Smallest value. na if any value is na.

ArgumentDefaultMeaning
a, b, …requiredany number of values
let lo = min(open, close)

#isna(x)→ bool

True when the value is missing (na).

ArgumentDefaultMeaning
xrequiredany value
let missing = isna(zscore(volume, 20))

#nz(x, d)→ value

Replaces na with d.

ArgumentDefaultMeaning
xrequiredany value
d0replacement
let safe = nz(close[1], close)

#str(x)→ string

Converts a value to text (na becomes "na").

ArgumentDefaultMeaning
xrequiredany value
let t = "bar " + str(index)

#fmt(x, d)→ string

Formats a number with a fixed number of decimals, for labels.

ArgumentDefaultMeaning
xrequirednumber
d2decimals, 0–8
let t = fmt(volume, 0)

#len(x)→ number

Number of items (or characters). Also available as x.len.

ArgumentDefaultMeaning
xrequiredlist or string
let rows = len(levels)

#alpha(color, a)→ color

Same color with a different opacity — for soft boxes and background tints.

ArgumentDefaultMeaning
colorrequireda color
arequiredopacity 0–1
let soft = alpha(BUY, 0.2)

Indicators

Call them on every bar
Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

#sma(src, n)→ number

Simple moving average of the last n values. na until n bars exist.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

plot(sma(close, 20), "SMA", color = BLUE)

#sum(src, n)→ number

Sum of the last n values.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let v20 = sum(volume, 20)

#highest(src, n)→ number

Highest value over the last n bars, including the current one.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let top = highest(high, 50)

#lowest(src, n)→ number

Lowest value over the last n bars.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let bottom = lowest(low, 50)

#stdev(src, n)→ number

Population standard deviation over the last n values.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let sd = stdev(close, 20)

#zscore(src, n)→ number

How many standard deviations the current value is from the mean of the last n (0 when there is no variation). Good for "unusual volume".

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let z = zscore(volume, 50)

#ema(src, n)→ number

Exponential moving average, smoothing 2 / (n + 1), starting from the first value.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

plot(ema(close, 21), "EMA", color = PINK)

#rma(src, n)→ number

Wilder smoothing (smoothing 1 / n) — the average used inside RSI and ATR.

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let smooth = rma(delta, 14)

#change(src, n)→ number

Value now minus the value n bars ago.

ArgumentDefaultMeaning
srcrequiredseries
n1bars back

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let d1 = change(close)

#cum(src)→ number

Running total from the first loaded bar (na values are skipped).

ArgumentDefaultMeaning
srcrequiredseries

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

plot(cum(delta), "CVD")

#crossover(a, b)→ bool

True on the bar where a crosses above b.

ArgumentDefaultMeaning
arequiredseries
brequiredseries

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let up = crossover(close, sma(close, 20))

#crossunder(a, b)→ bool

True on the bar where a crosses below b.

ArgumentDefaultMeaning
arequiredseries
brequiredseries

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let down = crossunder(close, sma(close, 20))

#barssince(cond)→ number

Bars since the condition was last true (0 on that bar). na before the first time.

ArgumentDefaultMeaning
condrequiredcondition

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let age = barssince(close > open)

#rsi(src, n)→ number

Relative strength index, 0–100 (Wilder).

ArgumentDefaultMeaning
srcrequiredseries
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

plot(rsi(close, 14), "RSI")

#atr(n)→ number

Average true range of the bars (uses high, low and the previous close).

ArgumentDefaultMeaning
nrequiredlength 1–5000

Keeps its own state per bar — call it on every bar, not inside an if or after and/or (see Gotchas).

let range = atr(14)

Footprint helpers

These take the levels list (and need needs footprint). Adjacent rows are one Footprint price step apart.

#poc(levels)→ level or na

The row with the most volume in the bar.

ArgumentDefaultMeaning
levelsrequiredlist of levels
let p = poc(levels)
mark(p.total > 0, p.price, "POC")

#valueArea(levels, pct)→ record

Value area of the bar as {poc, vah, val} (prices of the POC row and the highest / lowest row inside the area).

ArgumentDefaultMeaning
levelsrequiredlist of levels
pct70percent of volume, 1–100
let va = valueArea(levels, 70)
plot(va.vah, "VAH")

#imbalance(levels, ratio, minVol)→ list

Diagonal imbalances: buying at a row against selling one row below, and selling at a row against buying one row above. Each item is {price, side, ratio, vol} with side "buy" or "sell".

ArgumentDefaultMeaning
levelsrequiredlist of levels
ratio3how many times bigger
minVol0minimum volume on the winning side
let im = imbalance(levels, 3, 10)

#stacked(imbs, side, n)→ bool

True when at least n imbalances of that side sit on neighbouring rows.

ArgumentDefaultMeaning
imbsrequiredlist from imbalance()
siderequired"buy" or "sell"
n3rows in a row
let zone = stacked(imbalance(levels, 3, 10), "buy", 3)

Order book helpers

These take the book record (and need needs book). The band is a percentage of the mid price, so the same number works on any symbol.

#bookDepth(book, side, pct)→ number or na

Total size resting within pct % of the mid price on one side.

ArgumentDefaultMeaning
bookrequiredthe book record
siderequired"bid" or "ask"
pct1band around the mid price, in percent
let bids = bookDepth(book, "bid", 1)
let asks = bookDepth(book, "ask", 1)
plot(bids - asks, "net depth")

#bookWall(book, side, pct)→ level or na

The biggest resting level inside the band as {price, size}.

ArgumentDefaultMeaning
bookrequiredthe book record
siderequired"bid" or "ask"
pct2band around the mid price, in percent
let w = bookWall(book, "ask", 2)
plot(w.price, "ask wall")

#bookImbalance(book, pct)→ number or na

(bid − ask) / (bid + ask) inside the band: −1 means only asks, +1 only bids.

ArgumentDefaultMeaning
bookrequiredthe book record
pct1band around the mid price, in percent
plot(bookImbalance(book, 1), "imbalance", style = "histogram")

List methods

Called on a list with a dot: levels.filter(…). The argument named key is either a field name in quotes or a lambda; fn is a lambda.

#list.filter(fn)

A new list with the items for which the function is true.

let big = levels.filter(l => l.total > 100)

#list.map(fn)

A new list with the function applied to every item.

let prices = levels.map(l => l.price)

#list.any(fn)

True if the function is true for at least one item.

let hasBig = trades.any(t => t.size > 50)

#list.all(fn)

True if the function is true for every item (true for an empty list).

let calm = trades.all(t => t.size < 5)

#list.count(fn)

Number of items for which the function is true. Without an argument, the number of items.

let nBuys = trades.count(t => t.side == "buy")

#list.sum(key)

Sum of a field or function result. Without an argument, the sum of the items themselves.

let total = levels.sum("total")

#list.sumBy(key)

Sum of key over all items. key is a field name ("size") or a function.

let bought = trades.filter(t => t.side == "buy").sumBy("size")

#list.maxBy(key)

The item with the largest key, or na for an empty list.

let big = levels.maxBy("total")

#list.minBy(key)

The item with the smallest key, or na.

let bottomRow = levels.minBy("price")

#list.top(n, key)

The n items with the largest key, biggest first.

let three = levels.top(3, "total")

#list.first()

First item or na.

let a = levels.first()

#list.last()

Last item or na.

let b = levels.last()

#list.at(i)

Item at position i (0 is the first, negative counts from the end). Same as list[i].

let second = levels.at(1)

#list.groupSum(key, value, step)

Groups the items in one pass and adds up value in each group. key is the number to group by (a field name or a lambda), value what to add (a field name or a lambda; leave it out to count items), step the width of a group (leave it out to group by the exact key). Returns a list of {key, sum, count} sorted by key; with a step, key is the start of the band (key + step is its end). Much cheaper than a filter + sumBy for every band.

let bands = opts.groupSum("strike", "premium", 500)

Drawing

These are the only way a script produces output. Each call belongs to the current bar. Positional arguments come first; named ones (color = BLUE) after.

#plot(value, name, color, width, style, axis, label)

Draws a value for this bar. In an overlay script it is drawn on the price scale; in a pane script it gets its own pane. histogram only draws bars in a pane (on the price chart it falls back to dots). Up to 32 plots per script. Two plot calls that use the same name on the same bar are an error (the second would hide the first) — give each its own name; an if / else that plots the same name in either branch is fine. To draw two things in different units in one pane (for example price and premium), give one of them axis = "own". indicator "x" pane nolabels hides every plot's name.

ArgumentDefaultMeaning
valuerequirednumber (na leaves a gap)
name"plot"series name; the same name is the same line
colorWHITEcolor
width11–6
style"line""line", "histogram" or "dots"
axis"right"pane scripts only: "right" (the pane's shared scale), "left" (the left scale) or "own" (a hidden scale just for this line)
labeltruefalse hides the name on the price axis
plot(sma(close, 20), "SMA", color = BLUE, width = 2)

#print(label, value)

Writes a line to the Runtime tab of the script editor. Only the latest bar prints (so the output stays short): up to 40 lines, lists are cut after 8 items. Use it to look at a value while you write a script.

ArgumentDefaultMeaning
labelrequiredtext to show before the value (optional: with one argument it is the value)
valuerequirednumber, text, true / false, list or record
print("delta", delta)
print("rows", levels.len)

#heatcell(cond, bottom, top, value, scale, pos, neg, curve, opacity, bars)

One cell of a heatmap: this bar by a price band, coloured by its value. Weak cells fade out, strong ones get opaque. Unlike box it is built for thousands of cells: up to 150 000 per script, drawn only where visible and grouped by colour. Draw several cells per bar (one per price band) to build the map.

ArgumentDefaultMeaning
condrequireddraw only when true
bottomrequiredlower price of the cell
toprequiredupper price
valuerequirednumber with a sign: positive uses pos, negative uses neg
scaleautomaticthe |value| that gets the full colour. Left out: the 99.5th percentile of all |values| the script draws, so one huge cell does not wash the rest out
posGREENcolour of positive values
negREDcolour of negative values
curve"sqrt""sqrt" (default, lifts weak cells), "lin" or "log"
opacity0.850.05–1, the opacity of the strongest cell
bars1how many bars the cell spans, starting at this bar
let net = delta
heatcell(abs(net) > 0, close - 250, close + 250, net)

#hline(price, color, style)

A horizontal line across the pane. Same price twice draws once; up to 64 lines.

ArgumentDefaultMeaning
pricerequirednumber
colorGRAYcolor
style"solid""solid", "dashed" or "dotted"
hline(2, color = ORANGE, style = "dashed")

#mark(cond, price, text, shape, color, size, pos)

A marker (and optional text) on this bar. Marks on bars far from the visible range are not drawn.

ArgumentDefaultMeaning
condrequireddraw only when true
pricerequiredwhere to put it
text""short label
shape"circle"circle, diamond, triangleUp, triangleDown, square, cross, none
colorWHITEcolor
size10.5–4
pos"at""at" (text beside the shape), "above", "below" or "center" (text inside the shape, e.g. a bubble with a number)
mark(close > open, low, "up", "triangleUp", BUY, 1, "below")

#label(cond, price, text, color, pos)

Text only (a mark with no shape).

ArgumentDefaultMeaning
condrequireddraw only when true
pricerequiredwhere
textrequiredthe text
colorWHITEcolor
pos"at""at", "above", "below" or "center"
label(volume > 1000, high, "big", YELLOW, "above")

#box(cond, bar0, bar1, top, bottom, color, border)

A rectangle between two bars and two prices. Bars are given as index numbers, so index + 10 reaches ten bars to the right.

ArgumentDefaultMeaning
condrequireddraw only when true
bar0requiredfirst bar (an index value)
bar1requiredlast bar (an index value)
toprequiredupper price
bottomrequiredlower price
colorsoft purplefill
borderpurpleborder color
box(close > open, index, index + 10, high, low, alpha(BUY, 0.15), BUY)

#line(cond, bar0, p0, bar1, p1, color, width, style)

A straight line between two points.

ArgumentDefaultMeaning
condrequireddraw only when true
bar0requiredstart bar (index)
p0requiredstart price
bar1requiredend bar (index)
p1requiredend price
colorWHITEcolor
width11–6
style"solid""solid", "dashed" or "dotted"
line(high > high[1], index - 1, high[1], index, high, ORANGE)

#bgcolor(cond, color)

Tints the whole column of this bar on the price chart.

ArgumentDefaultMeaning
condrequiredtint only when true
colorrequiredcolor (use alpha() to keep it soft)
bgcolor(zscore(volume, 50) > 2, alpha(ORANGE, 0.1))

#alert(cond, text)

Records an alert event for the bar. Not delivered anywhere yet — alerts from scripts are planned.

ArgumentDefaultMeaning
condrequiredwhen true
text"alert"message
let top20 = highest(high, 20)
alert(close > top20[1], "breakout")

Example scripts

These are the scripts in the editor's Templates menu and in Indicators → Script examples. Press Open in Scripts to open one (it is added switched off — turn it on with On chart), then edit it.

Absorption (footprint)

Looks at the busiest row of each bar. If most of the volume there was one-sided but price still closed the other way and barely moved past the level, it marks an absorbed push.

indicator "Absorption (footprint)" overlay
needs footprint
input minVol = 40 "Minimum volume at the level"
input maxMoveTk = 2 "Allowed move past the level (rows)" min 0 max 50
input side = "both" "Side" options("buy", "sell", "both")

onBar {
  let big = levels.maxBy("total")                 // busiest level of the bar
  let step = (high - low) / max(len(levels), 1)   // approximate row height
  let room = maxMoveTk * step
  // sells absorbed: heavy selling at 'big', yet the bar closes up and the high stays close to it
  let sellAbs = big.sell >= minVol and close >= open and (high - big.price) <= room and side != "buy"
  let buyAbs  = big.buy  >= minVol and close <= open and (big.price - low) <= room and side != "sell"
  mark(sellAbs, big.price, text = "Abs " + fmt(big.sell, 0), shape = "diamond", color = BUY)
  mark(buyAbs,  big.price, text = "Abs " + fmt(big.buy, 0),  shape = "diamond", color = SELL)
}

Exhaustion (footprint)

A strong one-sided bar whose extreme row has almost no aggressive volume left — an unfinished auction. Shows a marker at the high or low.

indicator "Exhaustion (footprint)" overlay
needs footprint
input thinPct = 15 "Extreme row thinner than x% of the row average" min 1 max 100
input minDelta = 100 "Minimum delta" min 0
input volZ = 0.5 "Minimum volume z-score" min -3 max 5

onBar {
  let avg = volume / max(len(levels), 1)           // average volume per row
  let hi = levels.maxBy("price")                   // top row
  let lo = levels.minBy("price")                   // bottom row
  let z = zscore(volume, 50)
  let strong = isna(z) or z >= volZ
  // buying exhausted at the high: up bar, large positive delta, but the top row has very little buying
  let topEx = close > open and delta >= minDelta and hi.buy <= avg * thinPct / 100 and strong
  // selling exhausted at the low
  let botEx = close < open and -delta >= minDelta and lo.sell <= avg * thinPct / 100 and strong
  mark(topEx, high, text = "Exh", shape = "triangleDown", color = SELL, pos = "above")
  mark(botEx, low,  text = "Exh", shape = "triangleUp",   color = BUY,  pos = "below")
}

Stacked Imbalance zones

Finds bars where diagonal imbalances stack on several neighbouring rows and draws a zone that extends to the right.

indicator "Stacked Imbalance zones" overlay
needs footprint
input ratio = 3 "Imbalance ratio" min 1.2 max 20
input stack = 3 "Consecutive rows" min 2 max 10
input minVol = 10 "Minimum volume" min 0
input extend = 15 "Extend (bars)" min 1 max 200

onBar {
  let im = imbalance(levels, ratio, minVol)
  let buys = im.filter(x => x.side == "buy")
  let sells = im.filter(x => x.side == "sell")
  let okBuy = stacked(im, "buy", stack)
  let okSell = stacked(im, "sell", stack)
  box(okBuy, index, index + extend, buys.maxBy("price").price, buys.minBy("price").price, alpha(BUY, 0.18), BUY)
  box(okSell, index, index + extend, sells.maxBy("price").price, sells.minBy("price").price, alpha(SELL, 0.18), SELL)
}

Volume spike (z-score)

A pane script: volume measured in standard deviations from the recent average, with a threshold line and a background tint.

indicator "Volume spike (z-score)" pane
input length = 50 "Lookback bars" min 5 max 500
input level = 2 "Threshold" min 0.5 max 6

onBar {
  let z = zscore(volume, length)
  plot(z, "z", color = PURPLE, style = "histogram")
  hline(level, color = ORANGE, style = "dashed")
  bgcolor(z >= level, alpha(ORANGE, 0.08))
}

VWAP (daily, UTC)

Shows var + newday: a running total that restarts each UTC day. The line breaks at the day change.

indicator "VWAP (daily)" overlay
input k = 1 "Band width (σ)" min 0 max 5

onBar {
  var pv = 0
  var vv = 0
  var p2 = 0
  if newday {
    pv = 0
    vv = 0
    p2 = 0
  }
  pv += hlc3 * volume
  vv += volume
  p2 += hlc3 * hlc3 * volume
  let vwap = vv > 0 ? pv / vv : na
  let sd = vv > 0 ? sqrt(max(p2 / vv - vwap * vwap, 0)) : na
  let cut = newday                                  // break the line at each new day
  plot(cut ? na : vwap, "VWAP", color = YELLOW, width = 2)
  plot(cut ? na : vwap + k * sd, "+σ", color = alpha(YELLOW, 0.5))
  plot(cut ? na : vwap - k * sd, "-σ", color = alpha(YELLOW, 0.5))
}

Delta divergence (footprint)

Price closes at a new high / low over N bars while delta is clearly weaker than at the previous extreme.

indicator "Delta divergence" overlay
needs footprint
input length = 10 "Lookback bars" min 3 max 100
input weak = 50 "Delta only x% of the recent extreme" min 5 max 100

onBar {
  let hh = highest(close, length)
  let ll = lowest(close, length)
  let dh = highest(delta, length)
  let dl = lowest(delta, length)
  let bear = close >= hh and dh > 0 and delta < dh * weak / 100
  let bull = close <= ll and dl < 0 and delta > dl * weak / 100
  mark(bear, high, text = "Δ div", shape = "triangleDown", color = SELL, pos = "above")
  mark(bull, low,  text = "Δ div", shape = "triangleUp",   color = BUY,  pos = "below")
}

Big prints (tape)

Uses trades: sums large buy and sell prints per bar and marks bars where one side dominates.

indicator "Big prints (tape)" overlay
needs tape
input minTotal = 50 "Minimum total size per side" min 0
input dom = 3 "Dominance (x)" min 1.1 max 20

onBar {
  let b = trades.filter(t => t.side == "buy").sumBy("size")
  let s = trades.filter(t => t.side == "sell").sumBy("size")
  let buyDom = b >= minTotal and b >= dom * max(s, 0.000001)
  let sellDom = s >= minTotal and s >= dom * max(b, 0.000001)
  mark(buyDom, low, text = "B " + fmt(b, 1), shape = "circle", color = BUY, pos = "below")
  mark(sellDom, high, text = "S " + fmt(s, 1), shape = "circle", color = SELL, pos = "above")
}

GEX levels (flip & walls)

Uses gex: the flip and the walls as step lines, with a mark when price closes across the flip.

indicator "GEX levels (flip & walls)" overlay
needs gex
input showWalls = true "Show call / put walls"

onBar {
  plot(gex.flip, "Flip", color = YELLOW, width = 2)
  plot(showWalls ? gex.callWall : na, "Call wall", color = BUY)
  plot(showWalls ? gex.putWall : na, "Put wall", color = SELL)
  let up = close > gex.flip and close[1] <= gex[1].flip
  let dn = close < gex.flip and close[1] >= gex[1].flip
  mark(up, low, text = "Flip", shape = "triangleUp", color = BUY, pos = "below")
  mark(dn, high, text = "Flip", shape = "triangleDown", color = SELL, pos = "above")
}

Options premium flow

Uses opts: bullish minus bearish options premium per bar in its own pane.

indicator "Options premium flow" pane
needs options
input minPremium = 0 "Ignore prints below (USD)" min 0

onBar {
  let big = opts.filter(t => t.premium >= minPremium)
  let bull = big.filter(t => (t.type == "call" and t.side == "buy") or (t.type == "put" and t.side == "sell")).sumBy("premium")
  let bear = big.sumBy("premium") - bull
  plot(bull - bear, "Net premium", color = PURPLE, style = "histogram")
  hline(0, color = GRAY)
}

Options net heat (by strike)

A heatmap of options flow by strike: groupSum bands the premium, mergeSum keeps the running total (restarting each session) and heatcell paints it. See Heatmaps.

indicator "Options net heat" overlay
needs options
input mode = "cumulative" "Mode" options("cumulative", "per bar") group "Data" tip "Cumulative adds each bar up from the session open and restarts at the next session. Per bar shows only what happened in that bar."
input step = 0 "Strike band" min 0 tip "Width of one price band. 0 = automatic (about 0.5% of the price)."
input minAbs = 0 "Hide below (USD)" min 0 tip "Cells with a smaller net premium are not drawn."
input posCol = #4ade80 "Bullish colour" group "Look"
input negCol = #f87171 "Bearish colour"
input curve = "sqrt" "Colour curve" options("sqrt", "lin", "log") tip "sqrt lifts weak cells, lin shows true proportions."
input opacity = 0.85 "Opacity" min 0.1 max 1

// the band: your choice, or the nearest round value to 0.5% of the price
fn pickStep(px, want) = want > 0 ? want : [0.5, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500].minBy(v => abs(v - px * 0.005))

onBar {
  var acc = []
  var band = 0
  if sessionStart { acc = []; band = 0 }                    // a new session starts from zero (and picks its band again)
  if band == 0 { band = pickStep(close, step) }             // ONE band width for the whole session, so the running total never mixes widths
  let half = band / 2
  // net bullish - bearish premium of this bar, summed into bands CENTRED on the strike (a strike sits in the middle of its cell, not at the edge)
  let now = opts.groupSum(t => t.strike + half, t => (t.type == "call") == (t.side == "buy") ? t.premium : -t.premium, band)
  if mode == "cumulative" { acc = mergeSum(acc, now) }       // add this bar to the running total
  let rows = mode == "cumulative" ? acc : now
  for r in rows {
    heatcell(abs(r.sum) > minAbs, r.key - half, r.key + half, r.sum, pos = posCol, neg = negCol, curve = curve, opacity = opacity)
  }
}

Order book imbalance

Uses book: how lopsided the resting orders are near the price, as a histogram with a tint for strong imbalance.

indicator "Order book imbalance" pane
needs book
input band = 1 "Depth band (% of price)" min 0.1 max 10
input level = 0.5 "Highlight above (absolute)" min 0.1 max 1

onBar {
  let imb = bookImbalance(book, band)
  plot(imb, "Imbalance", color = PURPLE, style = "histogram")
  hline(0, color = GRAY)
  bgcolor(imb >= level, alpha(BUY, 0.08))
  bgcolor(imb <= -level, alpha(SELL, 0.08))
}

Active flow bubbles (tape + book)

Uses trades, book and levels: finds large aggressive buying or selling that no resting wall stops, and draws a bubble at the VWAP or POC. Size and opacity follow a 0–100 strength score and the number sits in the middle (pos = "center"). Grey bubbles mean a wall absorbed it.

indicator "Active flow bubbles" overlay
needs tape
needs book
needs footprint
input anchor = "vwap" "Bubble price" options("vwap", "poc") group "Bubbles" tip "vwap = volume-weighted price of the aggressive prints. poc = the busiest price row of the bar (footprint); falls back to vwap when the bar has no footprint rows."
input fullSize = 20 "Size for a full-strength size score" min 0.0001 tip "Aggressive size that counts as 100% on the size part of the strength."
input strengthBy = "combined" "Strength" options("combined", "size", "pressure") tip "combined = size x pressure x dominance (geometric mean). size = only the aggressive size. pressure = aggressive size against the resting book ahead of it."
input showText = "strength" "Text" options("strength", "size", "none")
input minOpacity = 0.25 "Weakest opacity" min 0.05 max 1
input maxOpacity = 0.85 "Strongest opacity" min 0.1 max 1
input minVol = 5 "Min aggressive size per bar" min 0 group "Signal" tip "Total size of large prints of the dominant side in the bar. Tune it to your symbol."
input dom = 2 "Dominance (x)" min 1 max 20 tip "The aggressive side must be at least x times the other side."
input reach = 0.3 "Wall search range (% of price)" min 0.05 max 5 group "Walls" tip "How far above (asks) or below (bids) the price a wall can stand in the way. Also the range of the book depth used for pressure."
input wallMult = 1 "Wall blocks at x * aggressive size" min 0.1 max 20 tip "A resting wall this many times the aggressive size would absorb the prints."
input confirm = "no" "Require bar direction" options("no", "yes")
input showBlocked = "yes" "Show absorbed (blocked) prints" options("yes", "no")

onBar {
  let b = trades.filter(t => t.side == "buy").sumBy("size")
  let s = trades.filter(t => t.side == "sell").sumBy("size")
  let askDepth = nz(bookDepth(book, "ask", reach), 0)
  let bidDepth = nz(bookDepth(book, "bid", reach), 0)
  let hasBook = not isna(bookDepth(book, "bid", reach))
  let aw = bookWall(book, "ask", reach)
  let bw = bookWall(book, "bid", reach)
  let awSize = nz(aw.size, 0)
  let bwSize = nz(bw.size, 0)

  // one side dominates the large prints of the bar
  let buySide = hasBook and b >= minVol and b >= dom * max(s, 0.000001) and (confirm == "no" or close >= open)
  let sellSide = hasBook and s >= minVol and s >= dom * max(b, 0.000001) and (confirm == "no" or close <= open)
  // free = no wall big enough to absorb it; blocked = a wall is sitting right there
  let buyFree = buySide and awSize < wallMult * b
  let sellFree = sellSide and bwSize < wallMult * s
  let buyBlk = buySide and awSize >= wallMult * b
  let sellBlk = sellSide and bwSize >= wallMult * s

  // STRENGTH 0..1: size vs fullSize, pressure vs the book ahead, dominance among large prints
  let sizeB = min(1, b / fullSize)
  let sizeS = min(1, s / fullSize)
  let presB = b / max(b + askDepth, 0.000001)
  let presS = s / max(s + bidDepth, 0.000001)
  let domB = b / max(b + s, 0.000001)
  let domS = s / max(b + s, 0.000001)
  let strB = strengthBy == "size" ? sizeB : strengthBy == "pressure" ? presB : pow(sizeB * presB * domB, 1 / 3)
  let strS = strengthBy == "size" ? sizeS : strengthBy == "pressure" ? presS : pow(sizeS * presS * domS, 1 / 3)

  // where to draw: volume-weighted price of the dominant prints, or the bar's POC row
  let bVwap = trades.filter(t => t.side == "buy").sumBy(t => t.price * t.size) / max(b, 0.000001)
  let sVwap = trades.filter(t => t.side == "sell").sumBy(t => t.price * t.size) / max(s, 0.000001)
  let pr = poc(levels)
  let pocOk = anchor == "poc" and not isna(pr) and nz(pr.total, 0) > 0
  let buyPx = pocOk ? pr.price : bVwap
  let sellPx = pocOk ? pr.price : sVwap

  // stronger = bigger AND more opaque; the number sits in the middle of the bubble
  let rb = 1 + 3 * strB
  let rs = 1 + 3 * strS
  let ab = minOpacity + (maxOpacity - minOpacity) * strB
  let as = minOpacity + (maxOpacity - minOpacity) * strS
  let tb = showText == "strength" ? str(round(strB * 100, 0)) : showText == "size" ? fmt(b, 1) : ""
  let ts = showText == "strength" ? str(round(strS * 100, 0)) : showText == "size" ? fmt(s, 1) : ""

  mark(buyFree, buyPx, text = tb, shape = "circle", color = alpha(BUY, ab), size = rb, pos = "center")
  mark(sellFree, sellPx, text = ts, shape = "circle", color = alpha(SELL, as), size = rs, pos = "center")
  mark(showBlocked == "yes" and buyBlk, buyPx, text = "abs", shape = "circle", color = alpha(GRAY, minOpacity + 0.2), size = 1 + 3 * sizeB, pos = "center")
  mark(showBlocked == "yes" and sellBlk, sellPx, text = "abs", shape = "circle", color = alpha(GRAY, minOpacity + 0.2), size = 1 + 3 * sizeS, pos = "center")
}

Gotchas

State functions must run on every bar

sma, ema, rsi, crossover… remember what they saw on earlier bars. If you only call them sometimes, they miss bars and return na. The trap is and / or: the right side is skipped when the left side already decides the result.

// wrong: crossover() is skipped on bars where volume is small
let bad = volume > 100 and crossover(close, sma(close, 20))

// right: call it first, combine afterwards
let cross = crossover(close, sma(close, 20))
let good = volume > 100 and cross

The forming bar is recomputed

While a bar is still open, the script runs again on every update, so marks and boxes on the last bar can appear, move or disappear until it closes. Closed bars never change. This is the same behaviour as any live indicator; if you only want closed-bar signals, test index < the last bar or wait for the next bar.

Top-level names are unique

Every let / var at the top of onBar needs its own name, which cannot be a built-in (close, sma…). Variables created inside an if or for block are local to that block.

Use var at the top level

var keeps its value between bars only when it is declared directly in onBar, not inside a block.

History works on top-level variables and built-in series

x[1] reads x one bar ago when x is a top-level let / var or a built-in series like close and holds a number. On a list, x[1] means the item at position 1 (a list from the previous bar is not reachable by index).

No while, no recursion — on purpose

A script must always finish, so there is no while and a function cannot call itself. for over a list or a range (0..n) is always bounded, and it supports break and continue; list methods (filter, any, sumBy…) cover most of what you would loop for.

Lists: [a, b, c] and indexing

You can write a list: [1, 2, 3]. x[i] is the item at position i when x holds a list (levels[0], levels[-1]), and the value i bars ago when x holds a number.

let picks = [close, open, high]
let best = picks.maxBy(v => v)

Sharing and safety

Share a script

  • Share → Copy share code copies a short piece of text with the script and its settings. Copy link copies a short link such as app.z-options.com/?s=k3m9x2ab that opens the Import screen of whoever clicks it (they need to be signed in). Signed out, or offline, it falls back to a longer link that carries the whole script.
  • To import, press Import in the script editor (or Indicators → My scripts → Import code) and paste the code. You see the full source first. The script is added switched off; you turn it on yourself.
  • Your scripts live in your browser. Copy a share code to back one up or move it to another device.

Publish to Community

  • In the script editor press Publish. The page shows a picture of your chart with the script running, plus a description (up to 2000 characters; the first paragraph is the short text on the card), a category, up to 5 tags, and a choice to show or hide the source code. The script appears in Indicators → Community (Top, Trending, Newest) as a gallery or a list, under your username.
  • Use on chart copies a Community script into your My scripts, marked COMMUNITY with the author's name, and switches it on. If the author shows the source you can read it first (the Source code tab) and edit your copy freely. If the author hides it, you can still use the script and change its settings; the code is not shown and the copy cannot be edited, shared or published again.
  • You can update a published script (people keep their copy until they use it again) or remove it from Community at any time. Removing it does not delete copies people already added.
  • Boost a script you find useful (not your own). Top and Trending rank by boosts, then by how many people use it.
  • Publishing needs an active trial or plan; browsing and using scripts needs only an account. Up to 5 new scripts per day and 25 published scripts per account.
  • You cannot publish a script you got from someone else — publish your own work.
  • Hidden source is kept out of the page, not encrypted: scripts run in the viewer's browser, so a determined person can still extract the code. Never put secrets in a script.

Why other people's scripts are safe to try

  • The language has no way to reach the network, your files, your account or other tabs. There is simply no such command.
  • A script can only read chart data (bars, footprint, large prints) and draw. It cannot place orders or change your settings.
  • Every script has a compute budget. One that loops too long is stopped with a message instead of freezing the chart.
  • A script that fails never breaks the chart or your other scripts; the editor shows its error instead.
Source is always visible
Because scripts run in your browser, their source is always readable. There are no hidden or locked scripts.

Limits

LimitValueNotes
Work per bar60 000 stepsCounts every operation; a loop over a list costs one step per item.
Work per run8 000 000 stepsA run covers all loaded bars; later updates only redo the last few.
Heatmap cells150 000 per scriptheatcell calls. Extra ones are dropped and the panel says "output truncated".
Drawing objects5 000 per scriptMarks, labels, boxes, lines and alerts together. Extra ones are dropped and the panel says "output truncated".
Plots32 per scriptDistinct plot names.
Horizontal lines64 per script
Indicator window1 – 5 000 barsThe n in sma, highest, stdev…
Loop range100 000Size of a..b.
Function nesting24 calls deepUser functions and lambdas.
Library40 scripts, 40 000 characters eachStored in your browser.

Error messages

Errors appear under the editor with the line number; click one to jump to it.

MessageWhat to do
Not declared: xA name is used before it exists. Check spelling; declare it with let / var / input.
Using 'levels' needs the line "needs footprint"Add needs footprint (for levels, buy, sell, delta), needs gex, needs options, needs book or needs tape (for trades) under the indicator line.
No such function: fMisspelled or not part of the language. See the reference above.
f needs at least N argumentsA required argument is missing.
f has no argument 'x'A named argument does not exist. Check the parameter names in the reference.
Named arguments must come after positional onesWrite mark(cond, price, text = "x"), not mark(text = "x", cond, price).
Variable x is declared twice / x is a built-in namePick another name.
Assignment to an undeclared variable: xDeclare with let or var before assigning with =, +=…
… keeps state per bar, so it cannot be called inside your own functionsCall sma, ema… in onBar, then pass the result to your function.
Function f calls itself (recursion is not allowed)Use a loop (for i in 0..n) or list methods.
Expected '}' / Missing '}'A block is not closed. Every { needs a }.
Script exceeded its compute budgetThe script did too much work on one bar (usually a long loop). Shorten the loop, narrow the list with filter first, or use the built-in helpers.
Loop is too longA for a..b range is limited to 100 000 steps.
This script needs footprint data, which is not available for this symbolFootprint exists only on the symbols where the Footprint chart exists. Switch symbol, or remove the dependency.
Waiting for data...The footprint or large-print history is still loading. It starts by itself.
More than 32 plotsOne script can draw up to 32 different plot names.
Window length must be a number from 1 to 5000The n of sma, highest… must be between 1 and 5000.

Not available yet

Being honest about what is missing:

  • More data. Open interest, liquidations, funding and the Greek ladder are not available to scripts yet. Footprint, large prints, GEX, options prints and the order book are.
  • Alerts. alert() records an event but nothing is sent yet.
  • Comments. Community has boosts and use counts only; there are no comments or discussion yet.
  • Phones. The script editor and the Community list are on the desktop layout; scripts you enabled there still draw on the phone layout of the same browser.