logo
    logo
    Log in
    Browse help/Custom Indicator Language

    Custom Indicator Language

    Requires SuperAvailable on: Web

    On this page

    A custom indicator is an indicator you write yourself, as a short script, when none of the built-in studies computes what you want. Once it is saved you can filter on it in a scan, draw it on a chart, and ask the AI terminal to explain it. Scripts run on the same price history as every built-in study, so a custom indicator is scanned across the whole universe like any other filter.

    The language is thinkScript-flavored: a handful of statements, the familiar price series, and a standard library of functions such as Average, ExpAverage, StDev, Highest and ATR. This article explains how to write a script, walks through the official scripts, and lists the limits and what the language cannot express yet.

    Reference: The editor's Reference panel is always the up-to-date list of every function, with its arguments and the lengths it accepts, plus a Guide with more examples. Every example in this article compiles, except the two that the text just above them says do not.

    Write your first custom indicator

    1. Under Custom Indicators in the sidebar, open My Scripts. This is your script library.
    2. Click New script for a blank script, or open the Official tab and choose Use as template on one of the official scripts. A template saves a copy you can edit.
    3. Write the script. The editor checks it as you type: the editor's bottom-right corner shows the first problem with its line and column, and the Budget panel shows how much of the cost and lookback limits each plot uses.
    4. Try values in the Inputs panel. That panel shows exactly what a scan or a chart will ask for. Values you try there are not saved.
    5. Click Save. The first save is version 1, and every later save is a new version.

    Here is a complete script. It measures how far the close sits from its 50-bar average, in percent:

    iscript
    # Distance from the 50-bar average, in percent.input length = 50 (2..200);
    def avg = Average(close, length);
    plot Distance = if avg > 0 then 100 * (close - avg) / avg else 0;

    Writing and saving scripts needs a larger screen. On a phone, the editor shows the saved script read-only.

    The shape of a script

    A script is a list of statements, and every statement ends with ;. There are four kinds, plus the display statements that say how a chart draws it:

    • input declares a parameter a scan or a chart can change.
    • def names an intermediate series. A def is never returned on its own.
    • plot is an output. A script has 1 to 8 plots, and each one is what a scan compares or a chart draws.
    • declare upper; or declare lower; (optional, at most once) says where every plot is drawn: over the candles, or in its own pane.

    These statements are always keyword name = expression;. There are no bare expressions, no function definitions, no return, and no reassigning a name that already exists. Line breaks and spaces are free, so a statement may span several lines.

    Comments start with # and run to the end of the line.

    Names are case-insensitive: keywords, functions and the names you declare. Signal, signal and SIGNAL are one name, and a name is declared once across inputs, defs and plots together. The most common mistake is computing a value in a def and then plotting it under the same name. This does not compile:

    iscript
    def trend = Average(close, 50);plot Trend = trend;

    Give the def its own name, or plot the expression directly:

    iscript
    def trendLine = Average(close, 50);plot Trend = trendLine;

    A name must be declared before the line that uses it. The built-in series are open, high, low, close and volume.

    Offsets read back in time: close[1] is the previous bar's close, and x[k] is the value of any expression k bars ago, conditions included.

    if … then … else is an expression that picks a value on every bar. The else is required, both branches must have the same type, and else if chains:

    iscript
    plot Direction = if close > open then 1 else if close < open then -1 else 0;

    Numbers and conditions

    Every value is a series of one of two types:

    • a number: price, volume, arithmetic, and every function that computes a value;
    • a condition (true/false): a comparison (==, !=, <, <=, >, >=), and, or, not, CrossesAbove, CrossesBelow and IsNaN.

    Compare with ==, never =, which only appears in input, def and plot. A condition is not a number: to count how often one was true, use CountTrue.

    iscript
    plot UpBars = CountTrue(close > open, 10);

    A plot can be a condition. Such a true/false plot reads as "is true" or "is false" in a scan, and puts a dot over the bars where it is true on a chart.

    Inputs

    There are two kinds of input:

    • A numeric input always has a range: input length = 14 (2..200);. The range is required. It bounds what a scan or chart may set, and the limits below are measured at the top of it. An input is a whole number when its default and both bounds are whole numbers, otherwise a decimal (2.0 (0.5..4.0)).
    • A series input names a data series: input src = volume;. A scan or chart can switch it to any other series in the Study Inputs Reference, such as dollar volume, and the same script then runs on that series.
    iscript
    # Relative volume z-score, over any series.input length = 60 (2..200);input src = volume;
    plot ZVol = ZScore(src, length);

    A value outside an input's range is refused, never clamped. One input cannot be constrained against another, so nothing stops a scan from setting a fast length above a slow one: give each input a sensible range of its own.

    There is no hl2 or ohlc4: write (high + low) / 2.

    Lengths, offsets and windows longer than 200 bars

    A window function's length, and the k in x[k], must be a whole-number constant or a whole-number input. They cannot be computed: length * 2 is not a length, so declare a second input instead. Lengths and offsets go up to 200 bars, and an input used as a length must keep its whole declared range inside the function's length range.

    A longer window composes from pieces of at most 200 bars joined by offsets. A 252-bar (52-week) high is the highest of the last 200 bars and the highest of the 52 bars before those:

    iscript
    # 52-week high and how far the close sits below it, in percent.def high252 = Max(Highest(high, 200), Highest(high, 52)[200]);
    plot High52w = high252;plot PctFromHigh = if high252 > 0 then 100 * (close - high252) / high252 else 0;

    Lowest, Sum, Average (a composed sum divided by the window) and CountTrue combine the same way. StDev, Variance, ZScore and PercentRank do not.

    Warm-up and missing values

    A window value is missing (NaN) until its window has filled: Average(close, 50) has no value for a stock's first 49 bars. BarsSince and ValueWhen are missing when the condition was not true within their window.

    A missing value matches no comparison. In a scan, the stock is simply not returned. That is usually what you want: BarsSince(released, 50) <= 3 means "within the last 3 bars", and it quietly excludes every stock where the event did not happen at all. When you want a number instead, Nz(x) replaces a missing value with 0, and Nz(x, r) with r.

    iscript
    input length = 50 (2..200);
    def crossUp = CrossesAbove(close, Average(close, length));
    # 0 bars when the cross happened on this bar, 200 when it never did.plot BarsSinceCross = Nz(BarsSince(crossUp, 200), 200);

    Guard every division whose denominator can be 0, as in if d > 0 then n / d else 0. A flat or halted stock makes ranges, volume sums and standard deviations 0.

    Limits

    Every script is checked before it is saved, and again when a scan runs it. The editor's Budget meter shows where each plot stands, so you rarely need to work these out by hand.

    • 800 bars of warmed lookback per plot. Each plot may need at most 800 bars of history before its first value. A window of length n needs n − 1 bars, an offset [k] adds k, and nested windows add up. The recursive averages (ExpAverage, WildersAverage, AdaptiveAverage, RSI, ATR) carry state from bar to bar, so they count 4× their length: ExpAverage(close, 200) alone needs all 800 bars.
    • Measured at the top of every range. Lookback and cost are measured with every whole-number input at the maximum you declared, so the range matters as much as the default. When a script is over a limit, shrink the range, not the default.
    • A cost budget per plot. Most functions cost the same whatever their length. Six cost in proportion to it: Variance, VarianceSample, StDev, StDevSample, ZScore and, at half the rate, PercentRank. One StDev at length 200 takes most of a plot's budget, so a second one only fits with a smaller range (two at 100 cost about the same as one at 200).
    • Per script: at most 8 plots, 16 numeric inputs and 16 KB of source.
    • Per scan: a scan can use up to 5 custom indicators, depending on your plan (5 is the most any plan allows), and all of them together share one cost budget. Each filter row counts, even two on one script, and so does a sort. The scan builder adds up their cost as you build and warns when a scan may be refused.

    Your plan sets how many scripts you can keep and how many custom indicators one scan or chart can use, and those numbers are shown in the app: the library shows your script count, and the scan builder and chart settings say when you have reached your plan's limit. Your plan's history limit applies to a custom indicator just as it does to a built-in study.

    An exponential average of an exponential average at full range goes over the lookback limit. With slowLength capped at 200 this plot would need 999 bars, so this does not compile:

    iscript
    input slowLength = 26 (3..200);input signalLength = 9 (2..50);
    def line = ExpAverage(close, 12) - ExpAverage(close, slowLength);plot Signal = ExpAverage(line, signalLength);

    Capping slowLength at 150 brings it to 799 bars:

    iscript
    input slowLength = 26 (3..150);input signalLength = 9 (2..50);
    def line = ExpAverage(close, 12) - ExpAverage(close, slowLength);plot Signal = ExpAverage(line, signalLength);

    No loops, no self-reference, no future bars

    A script is one expression per name, evaluated over every bar at once. There are no loops, no variables that change, and a name cannot refer to itself, even offset. The patterns people reach for recursion to write are built in:

    You wantUse
    An exponential or smoothed averageExpAverage, WildersAverage
    An average whose speed changes bar by bar (KAMA, VIDYA)AdaptiveAverage(series, alpha, length)
    Bars since something happenedBarsSince(condition, length)
    The value when something last happenedValueWhen(condition, series, length)
    How often something happenedCountTrue(condition, length)
    A running totalSum(series, length), a windowed total

    The entry price of the last crossover, and how long ago it was:

    iscript
    def crossUp = CrossesAbove(close, Average(close, 50));
    plot EntryPrice = ValueWhen(crossUp, close, 200);plot BarsSinceEntry = BarsSince(crossUp, 200);

    Future bars are never available: an offset counts back, so close[-1] does not compile.

    The official presets

    scanr.ai ships 15 official scripts. Anyone with access can use them in a scan or on a chart as they are, and Use as template on the library's Official tab saves a copy you can change.

    Five of them teach the language, from a one-line beginner script to an advanced three-plot one: RELVOL, VWAP Distance, RSI, MACD and Squeeze. Read them in order to learn it. The other ten are ready-made setups.

    RELVOL (relative volume)

    Relative volume asks one question of every bar: is this volume normal? It answers with a z-score, the number of standard deviations the bar's volume sits above or below its average over the last length bars. 0 is an ordinary day, 2 is unusually heavy, and a negative reading is quieter than usual.

    iscript
    # Relative volume z-score.input length = 60 (2..200);input src    = volume;
    plot ZVol = ZScore(src, length);

    The whole indicator is one line. input src = volume; makes the series an input, so a scan can run the same statistic on dollar volume or any other series. Try it in a scan: ZVol greater than 2 finds stocks whose daily volume is more than two standard deviations above its 60-day average.

    VWAP Distance

    VWAP Distance measures how far the close has stretched from a rolling volume-weighted average price, in percent. Above 0, the close is above the average price traders paid over the last length bars.

    iscript
    # Distance from a rolling VWAP, in percent.input length = 20 (2..200);
    def typical = (high + low + close) / 3;def vol     = Sum(volume, length);def vwap    = Sum(typical * volume, length) / vol;
    plot VwapDist = if vol > 0 then 100 * (close - vwap) / vwap else 0;

    The script builds the answer in steps, each a def. The last line guards the division: a window with no volume (a halted or newly listed stock) reads 0 instead of dividing by nothing. Try it in a scan: VwapDist less than −5 finds stocks closing more than 5% below their 20-day VWAP.

    RSI (Wilder's relative strength index)

    The RSI compares the size of recent gains with the size of recent losses, from 0 to 100. This script writes Welles Wilder's original definition out from its parts, so every step is visible.

    iscript
    # Wilder's RSI, from primitives.input length = 14 (2..200);input price  = close;
    def d     = price - price[1];def gain  = Max(d, 0);def loss  = Max(-d, 0);def g     = WildersAverage(gain, length);def l     = WildersAverage(loss, length);def total = g + l;
    plot RSI = if AbsValue(total) < 1e-14 then 0 else 100 * (g / total);

    price[1] is an offset: the previous bar's close. WildersAverage is recursive, so it counts four times length toward warm-up: at the largest length of 200 this script needs 800 bars, exactly the limit. Try it in a scan: RSI less than 30 finds oversold stocks.

    MACD

    MACD follows trend through the gap between a fast and a slow exponential average. The MACD line is the fast average minus the slow one, the signal line is an exponential average of the MACD line, and the histogram is the distance between them.

    iscript
    # MACD, written out from exponential averages.input fastLength   = 12 (2..100);input slowLength   = 26 (3..150);input signalLength = 9 (2..50);input price        = close;
    def fast = ExpAverage(price, fastLength);def slow = ExpAverage(price, slowLength);def line = fast - slow;def sig  = ExpAverage(line, signalLength);
    plot MACD      = line;plot Signal    = sig;plot Histogram = line - sig;

    This script has three plots, and a scan picks the one it compares. Chained exponential averages add up toward the 800-bar warm-up, which is why slowLength stops at 150: at 200, Signal would need 999 bars. Names are case-insensitive, so an input called signal would clash with the plot Signal; the input is signalLength. Try it in a scan: Histogram crossing above 0 finds the classic bullish crossover.

    Squeeze

    A volatility squeeze is a quiet market winding up: Bollinger Bands contract inside Keltner Channels, and the moment they expand back outside is the squeeze "firing", often the start of a larger move.

    iscript
    # Volatility squeeze: Bollinger Bands contract inside Keltner Channels.input length   = 20 (5..100);input bbMult   = 2.0 (0.5..4.0);input kcMult   = 1.5 (0.5..4.0);input lookback = 50 (5..200);
    def mid   = Average(close, length);def bbDev = StDev(close, length) * bbMult;def kcDev = ATR(high, low, close, length) * kcMult;
    # Both bands share the midline, so "BB inside KC" reduces to bbDev < kcDev.def squeezed = bbDev < kcDev;def released = squeezed[1] and not squeezed;
    plot InSqueeze        = squeezed;plot BarsSinceRelease = BarsSince(released, lookback);plot Momentum         = if mid > 0 then 100 * (close - mid) / mid else 0;

    InSqueeze is a true/false plot. released puts an offset on a condition: it is true on the one bar where the previous bar was squeezed and this one is not. BarsSince(released, lookback) is missing when no release falls inside the window, so BarsSinceRelease at most 3 quietly excludes every stock that has not fired lately. Try it in a scan: combine two plots of the same script, BarsSinceRelease at most 3 and Momentum above 0, for the bullish side of a fresh release.

    Ready-made setups

    These ten scan for a named setup. Open one on the Official tab to read its script, its inputs and what each plot means.

    ScriptWhat it finds
    Channel BreakoutA close beyond the highest high or lowest low of the prior bars, over a fast and a slow window (20 and 55 by default).
    Liquidity SweepA bar that trades through the extreme of the prior length bars and closes back inside it.
    RSI PullbackA short-period RSI dip while the close sits above its long-term average: 2 and 200 by default.
    First Red DayThe first down close after a run of up closes that gained at least minRunPct.
    Range BreakoutA close beyond a tight range of the prior length bars, on above-average volume.
    Fear GaugeFrom price alone: how far the low sits under the highest recent close, in percent, and whether that is unusually high for this stock.
    Channel WaveA channel index smoothed into a wave with a signal line: how far price has stretched from a moving center, and crosses at the extremes.
    Pivot BreakA close through the latest confirmed pivot high or low on above-average volume, and which way the latest break of swing structure went.
    Fair Value GapThe latest three-bar fair value gap on each side, whether it is still open, and price coming back into it.
    Oscillator DivergencePrice against RSI, the MACD histogram and signed volume at its last two confirmed pivots: how many diverge, and a signal when enough do.

    What the language cannot express yet

    When an indicator needs one of these, the honest answer is that this version cannot express it, followed by the closest thing it can.

    • Another timeframe, such as a weekly RSI on a daily chart. A script sees the bars of the timeframe it is scanned or charted on.
    • Another symbol, such as a ratio to SPY or relative strength against a sector ETF.
    • Values cumulative from the first bar or an anchor: a true OBV or A/D line, all-time highs, anchored VWAP, a session VWAP that resets each day. A windowed version is expressible when a window is acceptable.
    • Self-reference beyond the built-ins: SuperTrend, Parabolic SAR, a trailing stop that only moves up. Each is defined from its own previous value by a rule that none of the built-in functions computes.
    • Future bars: centered averages, ZigZag, anything that needs x[-1].
    • Time, sessions and calendars: time of day, day of week, the opening range, earnings dates.
    • Anything outside the price series: sector, fundamentals, events. Combine those with a custom indicator in the same scan instead.
    • Functions not in the standard library, such as weighted or Hull moving averages, linear regression or correlation. The editor's Reference panel lists the names people try under Not in this version, with what to use instead.
    • Text, literal colors, drawing tools and alerts. A plot is a number or a condition, nothing else. A script can ask a chart to draw a plot a certain way in the theme's colors.

    A windowed OBV, which is expressible:

    iscript
    def flow = if close > close[1] then volume else if close < close[1] then -volume else 0;
    plot OBV200 = Sum(flow, 200);

    Habits from Pine Script and thinkScript

    The language is thinkScript-flavored, but it is its own language, and these habits do not compile:

    HabitWrite instead
    // comment# comment
    .50.5
    x ^ 2x * x
    if a = bif a == b
    if c then x;if c then x else y; (every if needs an else)
    x := …, var, letdef x = …;, declared once
    ta.sma(close, 20), SimpleMovingAvg(close, 20)Average(close, 20)
    na, Double.NaNIsNaN(x) to test, Nz(x) to replace
    A missing ;Every statement ends with ;

    The Reference panel's Names from other languages finds the function a Pine Script or thinkScript name maps to.

    Using a custom indicator in a scan

    1. In the scan builder, click + on a filter group and choose Custom indicator.
    2. Pick one of your scripts or an official one. A script with several plots then asks which plot to compare.
    3. Set its inputs, then the condition: greater than, less than, crosses above and so on. A true/false plot reads "is true" or "is false" instead of a number.

    Each custom indicator filter shows the scan's combined cost, and warns when the scan may go over its budget and which filter's inputs to lower. If the scan is refused anyway, the error says which indicator and why.

    A saved scan keeps the exact version of the script it was saved with, so editing a script never changes what an existing scan finds. See Versions and upgrading a scan below.

    Using a custom indicator on a chart

    Open the chart settings and, under Custom indicators, click Add a custom indicator. A plot that is a price level, such as an average or a band, is drawn over the candles. A script's other plots share one pane. A true/false plot puts a dot above each bar where it is true. declare upper; or declare lower; in the script sets the placement for every plot.

    How a chart draws a script

    Five statements change that default. A scan ignores them, so restyling a script never changes what it matches. Write them anywhere in the script. A script can have up to 16 levels and 8 fills.

    • style Name histogram; sets how one plot draws: line, step (holds each value until the next bar), area, dots, columns, histogram, markers, or hidden (not drawn, but a fill, a barcolor or a scan can still use it). Add by sign to color each bar up at or above zero and down below it, and fading after it to dim a bar that moved back toward zero. A markers plot can name a shape (arrow_up, arrow_down, triangle_up, triangle_down, dot) and a position (above, below, value).
    • pane A, B; draws those plots together in a pane of their own. A price level can't go in a pane.
    • level 70; draws a horizontal line, and level 30 to 70; a shaded band. A value can be a numeric input, so the line moves with it. A script with more than one pane, or whose plots all draw over the candles, says which: level 0 in Name;.
    • fill A, B; shades between two plots in one pane, or a plot and a number: fill Hist, 0;. The shading is the up color where A is above B and the down color where it is below.
    • barcolor Cond; colors the candles where a true/false plot is true: up by default, or barcolor Cond down; or neutral. Where two are true on one bar, the later statement wins.

    A MACD that uses them, with a histogram colored by sign, an arrow under each crossover, a line at 0 and shading between its two lines:

    iscript
    input fast = 12 (2..100);input slow = 26 (3..150);input signalLength = 9 (2..50);
    def line = ExpAverage(close, fast) - ExpAverage(close, slow);
    plot MACD = line;plot Signal = ExpAverage(line, signalLength);plot Histogram = line - Signal;plot CrossUp = CrossesAbove(line, Signal);
    style Histogram histogram by sign fading;style CrossUp markers arrow_up below;level 0;fill MACD, Signal;

    A script names no colors: the chart's theme picks them. Colors and placement you set on your own chart win over the script's. A fill or a pane only sees the plots on your chart, so add a script's plots together to see them together. Each plot counts toward your plan's chart limit, so a four-plot script needs Super Pro to show all four.

    Versions and upgrading a scan

    Every save creates a new version, and the old ones are kept. A scan, saved or not, uses the version it was built with until you move it.

    When a newer version of one of your scripts exists, the scan builder shows a note above the filters (A newer version (v3) of "My RSI" exists) and the filter carries a badge. Nothing changes until you click Upgrade to v3. The upgrade first checks whether the new version would change what the scan finds: a plot that was renamed or removed, an input that disappeared, or a saved value outside a new range. If it would, the note lists the problems and saves nothing. If it would not, a saved scan with no unsaved edits is saved in one click; otherwise the filters on screen move to the new version and you save the scan as usual.

    To move several scans at once, open the script in the editor. Under its name, the page shows how many saved scans use it and how many of those have alerts on, for example Used by 5 scans (2 with alerts). When some sit on an older version, click Upgrade scans to v3. The dialog splits them in two:

    • Scans whose filters carry over, with a reminder that saving a scan starts its alerts again from the new version. Tickers already in its results won't alert. Click Upgrade 3 scans to save these one at a time.
    • Scans that need a look, with their problems and a link to open each one in the scan builder. The action won't save these.

    When it finishes, the dialog reports each scan. If a scan's alerts can't move to the new version, you see it as not upgraded and it stays on its old version. If you stop the run or leave the page, the scans it hadn't reached stay on their version too. Run it again and it picks up the rest.

    Deleting a script is undoable: deleted scripts stay under Deleted in the library and can be restored. Before you delete, the confirmation lists the saved scans that use it. Those filters stay off until the script is restored.

    Sharing a scan that uses a custom indicator

    Your scripts are private. When you share a scan that uses one of them, the share dialog warns that recipients cannot run it. Anyone who opens the link sees the other filters and your results. When someone opens the scan in their editor, any custom indicator they cannot run is switched off, not deleted, so they can see what the scan did and swap in their own. A sort on a script they cannot run is removed. The official presets belong to no one, so they are never switched off, but like every custom indicator they run only on Super and Super Pro: on a plan without custom indicators, a scan that uses one is refused.

    Asking the AI terminal about a script

    In the editor, Ask AI about this script opens the chat under the editor, which sees your script and the problems on screen. On a phone, it opens the AI terminal with them instead. It reads the same language reference and guide as the editor, so it can explain a script input by input, explain why a line does not compile, and suggest a fix, which it checks with the real compiler before calling it fixed. The AI terminal can also draft a new script for you to open in the editor, and save a draft once you confirm its card. See Ask the AI. The AI terminal is part of Super and Super Pro.

    Which plans include custom indicators

    Writing, saving, scanning with and charting custom indicators are part of Super and Super Pro. The plans differ in how many scripts you can keep and how many custom indicators one scan or chart can use, and the app shows your current limits. On any plan you can read the official scripts. If your plan lapses, your saved scripts stay readable and deletable.

    Was this page helpful?

    Still stuck?

    Ask scanr AI in the AI Terminal. It answers from this page. Included with Super and Super Pro.