Skip to content
AlertaChartAlertaScript / docs
AlertaScript / Utilities

Reference

Utilities

Guides and navigation are localized. Built-in reference descriptions and code examples are maintained in English.

Name / SignatureDescriptionReturns
alerta.ta.barssinceta.barssince(condition)Counts the number of bars since the condition was true.series int
alerta.ta.cumta.cum(source)Calculates the cumulative sum of source.series float
alerta.ta.risingta.rising(source, length)Returns true when source is greater than all previous values in the lookback window.series bool
alerta.ta.fallingta.falling(source, length)Returns true when source is lower than all previous values in the lookback window.series bool
alerta.ta.rangeta.range(source, length)Returns max(source, length) - min(source, length).series float
alerta.ta.devta.dev(source, length)Returns average absolute deviation from the moving mean over length bars.series float
alerta.ta.varianceta.variance(source, length, biased)Returns rolling variance. `biased=true` computes population variance, `false` uses sample variance.series float
alerta.ta.percentrankta.percentrank(source, length)Returns the percentile rank (0..100) of the current value inside the rolling window.series float
alerta.ta.percentile_nearest_rankta.percentile_nearest_rank(source, length, percentage)Returns rolling percentile using nearest-rank method.series float
alerta.ta.percentile_linear_interpolationta.percentile_linear_interpolation(source, length, percentage)Returns rolling percentile using linear interpolation between nearest ranks.series float
alerta.ta.kcwta.kcw(source, length, mult, useTrueRange)Returns channel width as `(upper - lower) / basis`.series float
alerta.ta.bbwta.bbw(source, length, mult)Returns Bollinger width as `(upper - lower) / basis`.series float
alerta.ta.cogta.cog(source, length)Computes Center of Gravity oscillator over the lookback window.series float
alerta.ta.correlationta.correlation(sourceA, sourceB, length)Rolling Pearson correlation between two series.series float
alerta.ta.maxta.max → series floatPine v6 built-in VARIABLE (no parentheses): the running all-time high — the maximum of `high` from the first bar up to the current bar.series float
alerta.ta.minta.min → series floatPine v6 built-in VARIABLE (no parentheses): the running all-time low — the minimum of `low` from the first bar up to the current bar.series float
alerta.ta.medianta.median(source, length)Returns rolling median of source values over length bars.series float
alerta.ta.modeta.mode(source, length)Returns most frequent value in the rolling window.series float
switchswitch <expr> <pattern> => <body> <pattern> => <indented block, last statement is the value> => <default>Pine-style switch with indent-based body. Cases are evaluated top-to-bottom; first match wins. A trailing `=>` arm (no pattern) acts as the default case. Works as a statement OR as an expression (assignable to a variable). The subject may be omitted, in which case every case is a boolean condition and may open with `not`. `type` and `method` are soft keywords, so either can be used as an ordinary variable or parameter name — `f_ma(src, len, type) => switch type` is accepted. An arm may open an indented BLOCK instead of a single expression — declare locals, branch, and the block's last statement is the arm's value — and a pattern may itself be an enum member (`Model.rolling =>`) or start with a unary minus (`-1 =>`).any
function-default-paramsname(param1, param2 = <default>, [type] param3 = <default>) => <body> name(value, param3 = other) // named at the call sitePine v6 parity: function parameters may declare default values. Defaults are evaluated at call time when the caller omits the slot and can reference earlier parameters. Typed prefixes (`float`, `int`, `string`, `bool`, `color`, `simple`, `series`) are accepted but informational only, and a qualifier may precede a USER type or enum — `simple ParticipationModel model`, `series Pivot p`, `simple Lib.Kind k`, `simple Sess[] all`. At the CALL SITE arguments may be named, exactly as for builtins: positional arguments fill slots left to right, a named argument claims its own slot, and any slot left over takes the parameter's default. Arguments are evaluated in the order they are written, whatever slots they fill — `f(b = array.pop(xs), a = array.pop(xs))` gives b the first value popped. The same applies to `method` calls.any
user-type-instancestype Name <type> field = <default> method name(Name self, …) => <body> Name.new(<positional…>, field = <value>)Pine v5/v6 user-defined types. `Type.new(...)` takes positional arguments in field-declaration order AND named ones for any field, in the same call — the two forms mix freely, and a field nobody names keeps its declared default. A `method` declared on the type dispatches on the RECEIVER's type, so several types may each declare their own `update` — and the same choice is made when the method is called in its function form, `update(x)`, by the type of its first argument. A method also dispatches on an instance read back out of a collection, directly (`arr.get(i).close()`) or through a variable (`Sess s = ss.get(i)` then `s.reset()`), and on a handle type — `method push_bar(float[] self, …)` is reached as `buf.push_bar(…)` wherever `buf` lives, including a field of another type.instance of the type
multiline-strings'''text over several lines''' | """text"""Pine's multi-line string literal. `'''…'''` or `"""…"""` spans lines and may contain the other quote character — apostrophes and double quotes — without escaping, which is why long `tooltip =` texts are written this way. Everything between the delimiters is taken literally.string
compound-assignmentname += <expr> // also -=, *=, /=, %=Pine v5/v6 parity: `x += y`, `x -= y`, `x *= y`, `x /= y`, `x %= y` are supported and desugar to `x := x + y` (etc.). Works on any reassignable variable (let/var/varip) and inside function bodies, if branches, for/while loops.void
generic-collectionvar array<T> name = array.new<T>(size?, initialValue?)Pine v6 generic type syntax: `array<T>`, `matrix<T>`, `map<T>` work both as type annotations on var/let declarations and as call generics on `.new<T>(...)`. Equivalent to the type-suffixed form (e.g. `array.new<float>()` is the same as `array.new_float()`).Array<T> | Matrix<T> | Map<T>
alerta.inputinput(name, defaultValue, options) / input(defval, title, type)Defines a user-configurable parameter that appears in the indicator settings. Supports AlertaScript input(name, defaultValue), Pine-style input(defaultValue, title="Name"), input(title="Name", defval=value), and legacy type=bool/int/float/string/source.any
alerta.iffiff(condition, trueValue, falseValue)Pine v1/v2 compatibility helper. Returns the true branch when condition is truthy, otherwise the false branch. Works with scalar values and series.any or series any
alerta.nana(val)Returns true if the value is null, undefined, or NaN.series bool
alerta.nznz(val, replacement)Replaces null, undefined, or NaN values with a replacement value (default 0).series any
alerta.fixnanfixnan(source)Replaces null/NaN values with the previous non-null value in the series.series any
alerta.typeoftypeof(value)Returns the runtime type name of a value, or series type for arrays.string
alerta.runtime.errorruntime.error(message)Stops the script with an error as soon as a bar reaches the call. Nothing the script would have drawn is shown, and the error reads "Runtime Error: <message>" with the line of the call. A call on a branch no bar reaches changes nothing, so it is the way to refuse settings or data a script cannot work with.void
alerta.boolbool(value)Casts a value to boolean using Pine-style truthiness.bool or series bool
alerta.intint(value)Casts numeric values to integer (truncates fractional part).int or series int
alerta.floatfloat(value)Casts value to floating-point number.float or series float
alerta.stringstring(value)Converts value to string representation.string or series string
alerta.colorcolor(value)Casts value to color representation (hex/rgba string).color or series color
alerta.color.newcolor.new(baseColor, transparency)Returns the base color with the given transparency, 0 (opaque) to 100 (invisible). The transparency replaces the base color's own: color.new(c, 0) is opaque even when c was translucent. It may be a series, so one plot can change its transparency from bar to bar.color
alerta.color.rgbcolor.rgb(r, g, b, transparency)Builds a color from red/green/blue and optional transparency.color
alerta.color.from_gradientcolor.from_gradient(source, min, max, colorA, colorB)Interpolates between two colors based on source value inside min/max range.series color
alerta.color.rcolor.r(colorValue)Returns the red channel (0..255) of a color.int
alerta.color.gcolor.g(colorValue)Returns the green channel (0..255) of a color.int
alerta.color.bcolor.b(colorValue)Returns the blue channel (0..255) of a color.int
alerta.color.tcolor.t(colorValue)Returns the transparency channel (0..100) of a color.int
alerta.fixedfixed(val, precision)Format a number to fixed decimal places.series string
alerta.str.containsstr.contains(source, target)Returns true if the source string contains the target string.series bool
alerta.str.lengthstr.length(source)Returns the length of the string.series int
alerta.str.substringstr.substring(source, begin, end)Returns a substring from begin to end.series string
alerta.str.replacestr.replace(source, target, replacement, occurrence)Replaces one occurrence of target with replacement — the first unless occurrence says otherwise.series string
alerta.str.replace_allstr.replace_all(source, target, replacement)Replaces all occurrences of target with replacement.series string
alerta.str.splitstr.split(source, separator)Splits string by separator into an array.array<string>
alerta.str.lowerstr.lower(source)Converts string to lowercase.series string
alerta.str.upperstr.upper(source)Converts string to uppercase.series string
alerta.str.format_timestr.format_time(time, format?, timezone?)Formats a UNIX time (milliseconds) as text with Java date letters: yyyy / yy (year), M / MM / MMM / MMMM (9, 09, Sep, September), d / dd, E / EEEE (Mon, Monday), HH (0–23), hh (1–12), a (AM/PM), k, K, mm, ss, SSS (milliseconds), D (day of year), w (week of year), u (weekday 1–7 from Monday), Z (+0300), XXX (+03:00) and z (EDT); text in single quotes is kept verbatim and '' is a quote. The time is read on the given timezone, or on the exchange clock (syminfo.timezone) when none is given — UTC on crypto charts.series string
alerta.str.startswithstr.startswith(source, prefix)Checks if string starts with prefix.series bool
alerta.str.endswithstr.endswith(source, suffix)Checks if string ends with suffix.series bool
alerta.str.trimstr.trim(source)Removes whitespace from start and end.series string
alerta.str.posstr.pos(source, target)Returns the index of the first occurrence of target, or na if it is not found.series int
alerta.str.matchstr.match(source, regex)Returns the first regex match in the source string, or na when not found.series string
alerta.str.tonumberstr.tonumber(source)Converts a plain decimal number written as text into a float: digits, an optional sign at the start and at most one decimal point ("1234.50", "-12.5", "+3", ".5"). Anything else is na — an empty string, surrounding spaces, thousands separators ("1,234"), currency signs, exponents ("1e3") and hexadecimal ("0x10").series float
alerta.str.tostringstr.tostring(value, format)Converts value to string representation. Supports Pine-style format strings and format enums such as format.mintick. Without a format, a number is written with at most ten decimals and no exponent (0.1 + 0.2 gives "0.3"), na as "NaN", a bool as "true" or "false", and an array as its elements in brackets, such as "[1, 2, 3]".series string
alerta.str.formatstr.format(template, arg0, arg1, ...)Formats a template string using positional placeholders, read as Pine reads them (Java MessageFormat): {0}, {0,number,#.##}, {0,number,integer}, {0,number,percent}, {0,number,currency}, {0,date,yyyy-MM-dd} and {0,time,HH:mm}. Text between single quotes is written as it is, and two single quotes write one. A number argument is grouped by thousands by default, na is written as "NaN" and an array as "[1, 2, 3]".series string
alerta.max_bars_backmax_bars_back(var, num)Declares the historical-buffer budget for a series. Accepted for Pine compatibility and has no effect: every bar of a series' history can already be referenced.void
alerta.log.infolog.info(message) | log.info(formatString, arg0, arg1, …) — and the same for log.warning and log.errorWrites a message to the script's diagnostics, shown in the editor next to the line that wrote it: log.info as information, log.warning as a warning and log.error as an error (the chart's script badge counts warnings and errors). None of them stops the script — everything else still runs and draws; use runtime.error to stop it. Useful for inspecting calculations without drawing an extra plot.void
alerta.str.repeatstr.repeat(source, repeat, separator = "")Builds a string by repeating source a non-negative number of times, optionally inserting a separator between repetitions.string
ifif close > openRuns an indented block when its condition is true. An optional else branch handles the other case.language construct
varvar float previous = naInitializes a variable once and retains its value between bars. Use := to assign a new value to the existing variable.language construct
varipvarip int updates = 0Declares a variable that persists between realtime updates. Historical bars do not reproduce every realtime update, so historical and live results can differ.language construct
typetype LevelDeclares a structured value with named fields. Construct an instance with Type.new() and define receiver methods with method.language construct
exportlibrary("Example")Marks a library declaration for use by an importing script. Availability also depends on the library resolver and the imported version.language construct
function-shadowingaverage(float source, int length = 20) =>User-defined names are resolved within their lexical scope. Avoid reusing builtin namespace names; use explicit namespaces to make a call’s meaning clear.language construct
alerta.str.length_in_pixelsstr.length_in_pixels(string, size)The approximate width of a text in pixels, for laying out labels and tables: 7 pixels per character of the default font. The size argument is accepted; the estimate does not depend on it.int
AlertaScript

No results found.

Search by name, alias, or keyword.