CODESCRIPT

Math

33 entries. What each one takes, what it returns, and a working example.

abs(x)

Drops the sign of a number and gives its distance from zero. Used to measure how far apart two values are regardless of direction. Given a series, it is computed for each bar.

Absolute value.

x
number
A number or series.

Note

Drops the sign and keeps the magnitude; works element-wise on both scalars and series.

When to use

To measure magnitude when the sign is irrelevant: change amount, deviation, wick length. Combine with sign if you also need direction.

CODESCRIPT
plot(abs(change(close, 1)))

The absolute magnitude of the per-bar price change (direction-less).

acos(x)

Arc-cosine (radians). Result: 1.047197551

The arc-cosine of x (in radians, 0..π).

x
number
A number or series; the input is clamped to the [-1, 1] range.

Note

To avoid na from out-of-range input, the value is first clamped to [-1, 1]. The result is in radians; use todegrees to convert.

When to use

In geometric angle calculations and when turning a normalized correlation/similarity into an angle.

CODESCRIPT
plot(todegrees(acos(1)))

acos(1) = 0 radians = 0 degrees.

asin(x)

Arc-sine (radians). Result: 0.5235987756

The arc-sine of x (in radians, -π/2..π/2).

x
number
A number or series; the input is clamped to the [-1, 1] range.

Note

To avoid na from out-of-range input, the value is first clamped to [-1, 1]. The result is in radians (todegrees for degrees).

When to use

In geometric angle and phase computations; when turning a normalized ratio into an angle.

CODESCRIPT
plot(todegrees(asin(1)))

asin(1) = π/2 radians = 90 degrees.

atan(x)

Arc-tangent (radians). Result: 0.7853981634

The arc-tangent of x (in radians, -π/2..π/2).

x
number
A number or series (a slope/ratio).

Note

Single-argument; gives the angle of a slope (Δy/Δx). For a sign/quadrant-aware angle use atan2.

When to use

When converting a line's slope into an angle (trend slope, channel angle).

CODESCRIPT
plot(todegrees(atan(change(close, 1))))

The slope angle (degrees) of the per-bar price change.

atan2(y, x)

Two-argument arc-tangent (quadrant-aware). Result: 0.7853981634

The angle of the point (x, y) (in radians, -π..π; quadrant-aware).

y
number
The vertical component (numerator).
x
number
The horizontal component (denominator).

Note

The two-argument arc-tangent: unlike atan it uses the signs to give the correct quadrant (-π..π). The result is in radians.

When to use

When computing a direction angle (two-axis change → angle) and you do not want atan to be quadrant-blind.

CODESCRIPT
plot(todegrees(atan2(1, 1)))

atan2(1, 1) = π/4 radians = 45 degrees.

avg(a, b,...)

Element-wise average of the arguments. ⚠ This function does not accept named arguments; pass the values positionally.

The element-wise average.

a
series
First value/series.
b
series
Second value/series (and beyond).

Note

Can take more than two arguments.

When to use

To average two or more values/series element-wise. To average a single series over time, use sma instead.

CODESCRIPT
plot(avg(high, low, close))

The per-bar average of high, low and close (same as hlc3).

bool(x)

Convert to boolean: zero/empty → false, nonzero → true. The result is never empty; it carries 1/0 as a series.

Zero/na → false, non-zero → true.

x
number
A number, series or boolean.

Note

In this language bool is NEVER na: bool(na) = false. A scalar input returns a real boolean, a series returns 1/0 (na→0). No collapse to the last value.

When to use

To turn a numeric value/series into a boolean condition (zero or not). When you want na to count safely as false.

CODESCRIPT
plot(bool(volume) ? 1 : 0)

0 when volume is zero/na, otherwise 1.

ceil(x)

Round up.

The value rounded up to an integer.

x
series
Value/series.

Note

Rounds up (toward plus infinity): ceil(2.1) = 3. Operates element-wise.

When to use

To round up (toward plus infinity) — the next step up, the minimum number of steps required.

CODESCRIPT
plot(ceil(close / 10) * 10)

Snaps the close up to the nearest higher multiple of 10.

clamp(x, lo, hi)

Clamps value into [lo, hi].

The value constrained to the [lo, hi] range.

x
series
Value/series.
lo
number
Lower bound.
hi
number
Upper bound.

Note

Constrains x to the [lo, hi] range, pulling anything outside back to the bound.

When to use

To constrain a value to the [lo, hi] range — keeping an indicator within 0..100, trimming outliers. For a one-sided bound, max/min suffices.

CODESCRIPT
plot(clamp(rsi(close, 14), 30, 70))

Constrains RSI to the 30-70 band, trimming the overshoots.

cos(x)

Cosine (radians).

Cosine.

x
series
Radians.

Note

The input is in radians. The output is between -1 and 1. Operates element-wise.

When to use

In cycle/phase modeling alongside sin (a 90°-shifted counterpart). The input is in radians.

CODESCRIPT
plot(cos(0))

cos(0) = 1 (constant).

exp(x)

Exponential (e^x).

e raised to the power of x.

x
series
Exponent.

Note

e to the power of x; the inverse of the logarithm. Operates element-wise.

When to use

e to the power of x — the inverse of the logarithm. In exponential weighting and undoing a log return.

CODESCRIPT
plot(exp(log(close)))

exp undoes log and returns close (identity check).

fixnan(source)

Fills NA values with the last known (non-NA) value in the series — forward-fill. nz fills with a constant (0/y); fixnan carries the last value forward (series-dependent). Stays na until the first valid value.

A series of the same length: each na is filled with the last non-na value up to that point (na until the first valid value).

source
series
The series to forward-fill (may contain na).

Note

Do not confuse with nz: nz(x)/nz(x,y) puts a CONSTANT (0 or y) in place of na. fixnan(x) puts the LAST KNOWN value from the series (forward-fill, ffill) — not constant, varies with the data.

When to use

To make an intermittent/sparse series (e.g. a value computed only on some bars) continuous — the last value is held until the next update.

CODESCRIPT
plot(fixnan(iff(barstate.isconfirmed, close, na)))

Carries the last valid value across empty bars; the line does not break, it continues flat.

float(x)

Convert numeric value to float (series/scalar; na preserved).

Converts the value to a floating-point number (na is preserved).

x
number
A number or series.

Note

For type clarity; explicitly marks a numeric value as floating-point. An na input stays na. It is a no-op on already-float values.

When to use

When you want to explicitly convert an integer or a type-ambiguous value to a decimal number before floating-point arithmetic.

CODESCRIPT
plot(float(3))

Casts the integer 3 to 3.0.

floor(x)

Takes a number down to the nearest whole number below it. It goes down for negatives too: -2.3 gives -3. Used for values that must be whole, such as a lot count, when rounding up is never acceptable.

The value rounded down to an integer.

x
series
Value/series.

Note

Rounds down (toward minus infinity): floor(-2.1) = -3. Differs from int, which truncates toward zero.

When to use

To round down (toward minus infinity) — bucket/step index, whole-lot sizing. int truncates toward zero instead (differs for negatives).

CODESCRIPT
plot(floor(close / 10) * 10)

Snaps the close down to the nearest lower multiple of 10 (price step).

int(x)

Truncate toward zero to integer (int(10.9)=10, int(-10.9)=-10; series/scalar; na preserved).

Truncates the fraction toward zero to an integer (na is preserved).

x
number
A number or series.

Note

Truncates toward zero: int(10.9)=10, int(-10.9)=-10. floor differs (rounds down, differs for negatives). An na input stays na.

When to use

To drop the fraction before using a value as an index/counter. Also works element-wise on a series.

CODESCRIPT
plot(int(close))

The integer part of the close (truncated toward zero).

log(x)

Natural logarithm.

x
number
A number or series.

Note

Natural logarithm (base e). Undefined for input ≤0. Operates element-wise.

When to use

Natural logarithm (base e). For log returns (log(close/prev(close,1))) and linearizing exponential growth. Use log10 for base 10.

CODESCRIPT
plot(log(close / prev(close, 1)))

The per-bar log return.

log10(x)

Base-10 logarithm.

Base-10 logarithm; na if x<=0.

x
series
Positive value/series.

Note

Base-10 logarithm. Undefined for input ≤0. Operates element-wise.

When to use

Base-10 logarithm — order of magnitude (number of digits), log-scaled indicators. Use log for the natural log.

CODESCRIPT
plot(log10(volume))

The base-10 logarithm of volume (its order of magnitude).

math.pi / e / phi / rphi / sqrt2 / sqrt3

Math constants (dot access): pi=3.14159..., e=2.71828..., phi=golden ratio 1.61803..., rphi=inverse golden ratio 0.61803..., sqrt2=1.41421..., sqrt3=1.73205...

CODESCRIPT
plot(close * math.phi)

Multiplies the close by the golden ratio and plots it; this namespace carries ready constants such as pi, e and the golden ratio.

max(a, b,...)

Maximum (2 or more values, element-wise). ⚠ This function does not accept named arguments; pass the values positionally.

The larger of the two (element-wise).

a
number
First value.
b
number
Second value.

Note

Picks the larger of two values element-wise; a series and a constant can be mixed.

When to use

To take the larger of two values (or of a value and a floor) — applying a floor, or clipping negatives with max(x,0).

CODESCRIPT
plot(max(close - open, 0))

The size of up-bodies only; 0 on down bars.

min(a, b,...)

Minimum (2 or more values, element-wise). ⚠ This function does not accept named arguments; pass the values positionally.

The smaller of the two (element-wise).

a
number
First value.
b
number
Second value.

Note

Picks the smaller of two values element-wise; a series and a constant can be mixed.

When to use

To take the smaller of two values — applying a ceiling, keeping a value below a limit. If you need both bounds at once, clamp is shorter.

CODESCRIPT
plot(min(high - close, close - low))

The shorter of the upper and lower wick.

mod(a, b)

Modulo (a mod b).

a mod b; na if b=0.

a
series
Dividend.
b
series
Divisor.

Note

The remainder of a divided by b. Undefined when the divisor is 0. Operates element-wise.

When to use

Remainder/period operations: every Nth bar (mod(barIndex, N) == 0), position within a cycle. The result is undefined when the divisor is 0.

CODESCRIPT
plotshape(mod(barIndex, 10) == 0, style="cross", location="bottom")

A mark in the bottom band once every 10 bars.

nz(source, replacement=0)

Puts the number you give in place of an empty (`na`) value and leaves a filled one as it is. Indicators return empty on the first bars because they cannot be computed yet; if that gap enters a calculation the result is empty too. `nz` keeps the chain going.

The series without na.

source
series
Source series.
replacement
number
Value to substitute for na (default 0).

Note

Replaces na values with replacement (default 0), leaving the rest untouched.

When to use

To replace na values with a safe number (default 0) — early bars, missing volume, an undefined ratio. It keeps chained rules from breaking on na.

CODESCRIPT
plot(nz(change(close, 1), 0))

0 instead of na on the first bar; the normal change afterwards.

pow(x, y)

Power (x^y).

x to the power of y.

x
number
Base.
y
number
Exponent.

Note

x to the power of y. Operates element-wise; base and exponent may be series.

When to use

Exponentiation: squares/cubes, exponential weights, compound ratios. For a square root, sqrt is clearer than pow(x,0.5).

CODESCRIPT
plot(pow(2, 10))

2 to the power of 10 = 1024 (constant).

random(min?, max?, seed?)

Per-bar deterministic random (seed → backtest==live). Defaults to 0-1 when bounds are omitted. Returns a series. Result: 0.9707432389

A series holding a deterministic random value in [min, max) for each bar.

min
number
Lower bound (inclusive).
max
number
Upper bound.
seed
number
Optional. Seed (default 0); the same seed reproduces the same sequence.

Note

It is deterministic: with the same seed the backtest and live results match exactly (seed → reproducibility). It is not a truly unpredictable number.

When to use

For Monte-Carlo/jitter experiments, stress testing or adding synthetic noise — wherever reproducibility matters.

CODESCRIPT
plot(random(0, 1, 42))

A reproducible random series in 0..1 per bar, seeded with 42.

round(x, decimals=0)

Rounds a number to the given number of decimals. Used to shorten a number before showing it in a panel or a label. ⚠ Rounding a price can distort a calculation; use the rounded value for display and keep the raw one for maths.

The rounded value.

x
series
Value/series to round.
decimals
number
Number of decimal places (default 0).

Note

Operates element-wise.

When to use

To simplify decimals for display or threshold comparison. To snap to a symbol's price step, use round_to_mintick instead.

CODESCRIPT
plot(round(close, 2))

The close rounded to two decimals.

round_to_mintick(value, tick?)

Rounds the value to the tick step (default 0.01). Result: 12.35

The value rounded to the nearest multiple of tick.

value
number
The value or series to round.
tick
number
Optional. The price step (default 0.01; falls back to 0.01 if ≤0).

Note

To snap a price to the symbol's trading step. If you want a fixed number of decimals, round is more appropriate.

When to use

To align a computed level (stop, target, entry) to the real price step.

CODESCRIPT
plot(round_to_mintick(12.347, 0.05))

12.347 to the nearest 0.05 multiple → 12.35.

sign(x)

Gives the sign of a number: +1 when positive, -1 when negative, 0 when zero. Use it when you want the direction without the size — for instance to check whether two series point the same way.

Sign: +1 when positive, 0 at zero, −1 when negative.

x
number
A number or series.

Note

Returns only -1, 0 or +1 (positive→1, negative→-1, zero→0). Operates element-wise.

When to use

To reduce a value's direction to +1/0/-1. Combine with abs when you also want magnitude.

CODESCRIPT
plot(sign(change(close, 1)))

+1 if price rose, -1 if it fell, 0 if unchanged.

sin(x)

Sine (radians).

Sine.

x
series
Radians.

Note

The input is in radians. The output is between -1 and 1. Operates element-wise.

When to use

Trigonometric/cyclical modeling, phase generation. The input is in radians; convert degrees with toradians first.

CODESCRIPT
plot(sin(toradians(barIndex * 10)))

A smooth oscillating (-1..1) wave driven by the bar index.

sqrt(x)

Square root.

x
number
A number or series.

Note

A negative input returns na. Operates element-wise.

When to use

In standard deviation, RMS and distance calculations. A negative input returns na, so guard it with nz/clamp first.

CODESCRIPT
plot(sqrt(pow(high - low, 2)))

The square root of the squared bar range = the range itself (identity check).

sum(source, length)

Rolling sum over length bars.

The sum of the last length bars.

source
series
Series to sum.
length
number
Window length.

Note

The first length-1 bars are None.

When to use

To sum the values over the last length bars (rolling window). For a running total from the start, use cum.

CODESCRIPT
plot(sum(volume, 5))

The total volume of the last 5 bars (rolling window).

tan(x)

Tangent (radians).

Tangent.

x
series
Radians.

Note

The input is in radians. It diverges near odd multiples of 90°. Operates element-wise.

When to use

Slope/angle computations. It blows up near odd multiples of 90°, so clamping the output is safer.

CODESCRIPT
plot(tan(0))

tan(0) = 0 (constant).

todegrees(rad)

Converts an angle from radians to degrees. Used in indicators that work with angles, to turn the result into a readable number.

The same angle in degrees (rad × 180 / π).

rad
number
An angle in radians (a number or series).

Note

Trigonometric/arc functions output radians; use this for readable degrees. The inverse is toradians.

When to use

To convert the result of acos/asin/atan/atan2 into a human-readable angle.

CODESCRIPT
plot(todegrees(3.141592653589793))

π radians = 180 degrees.

toradians(degrees)

Converts degrees to radians. Result: 3.141592654

The same angle in radians (degrees × π / 180).

degrees
number
An angle in degrees (a number or series).

Note

sin/cos/tan expect radians; convert a degree value with this before passing it in. The inverse is todegrees.

When to use

Before feeding a degree-based angle into sin/cos/tan.

CODESCRIPT
plot(sin(toradians(90)))

Converts 90 degrees to radians and takes its sine → 1.