Math
33 entries. What each one takes, what it returns, and a working example.
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.
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.
plot(abs(change(close, 1)))
The absolute magnitude of the per-bar price change (direction-less).
Arc-cosine (radians). Result: 1.047197551
The arc-cosine of x (in radians, 0..π).
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.
plot(todegrees(acos(1)))
acos(1) = 0 radians = 0 degrees.
Arc-sine (radians). Result: 0.5235987756
The arc-sine of x (in radians, -π/2..π/2).
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.
plot(todegrees(asin(1)))
asin(1) = π/2 radians = 90 degrees.
Arc-tangent (radians). Result: 0.7853981634
The arc-tangent of x (in radians, -π/2..π/2).
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).
plot(todegrees(atan(change(close, 1))))
The slope angle (degrees) of the per-bar price change.
Two-argument arc-tangent (quadrant-aware). Result: 0.7853981634
The angle of the point (x, y) (in radians, -π..π; quadrant-aware).
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.
plot(todegrees(atan2(1, 1)))
atan2(1, 1) = π/4 radians = 45 degrees.
Element-wise average of the arguments. ⚠ This function does not accept named arguments; pass the values positionally.
The element-wise average.
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.
plot(avg(high, low, close))
The per-bar average of high, low and close (same as hlc3).
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.
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.
plot(bool(volume) ? 1 : 0)
0 when volume is zero/na, otherwise 1.
Round up.
The value rounded up to an integer.
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.
plot(ceil(close / 10) * 10)
Snaps the close up to the nearest higher multiple of 10.
Clamps value into [lo, hi].
The value constrained to the [lo, hi] range.
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.
plot(clamp(rsi(close, 14), 30, 70))
Constrains RSI to the 30-70 band, trimming the overshoots.
Cosine (radians).
Cosine.
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.
plot(cos(0))
cos(0) = 1 (constant).
Exponential (e^x).
e raised to the power of x.
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.
plot(exp(log(close)))
exp undoes log and returns close (identity check).
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).
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.
plot(fixnan(iff(barstate.isconfirmed, close, na)))
Carries the last valid value across empty bars; the line does not break, it continues flat.
Convert numeric value to float (series/scalar; na preserved).
Converts the value to a floating-point number (na is preserved).
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.
plot(float(3))
Casts the integer 3 to 3.0.
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.
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).
plot(floor(close / 10) * 10)
Snaps the close down to the nearest lower multiple of 10 (price step).
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).
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.
plot(int(close))
The integer part of the close (truncated toward zero).
Natural logarithm.
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.
plot(log(close / prev(close, 1)))
The per-bar log return.
Base-10 logarithm.
Base-10 logarithm; na if x<=0.
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.
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...
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.
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).
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).
plot(max(close - open, 0))
The size of up-bodies only; 0 on down bars.
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).
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.
plot(min(high - close, close - low))
The shorter of the upper and lower wick.
Modulo (a mod b).
a mod b; na if b=0.
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.
plotshape(mod(barIndex, 10) == 0, style="cross", location="bottom")
A mark in the bottom band once every 10 bars.
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.
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.
plot(nz(change(close, 1), 0))
0 instead of na on the first bar; the normal change afterwards.
Power (x^y).
x to the power of y.
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).
plot(pow(2, 10))
2 to the power of 10 = 1024 (constant).
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.
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.
plot(random(0, 1, 42))
A reproducible random series in 0..1 per bar, seeded with 42.
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.
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.
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.
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.
plot(round_to_mintick(12.347, 0.05))
12.347 to the nearest 0.05 multiple → 12.35.
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.
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.
plot(sign(change(close, 1)))
+1 if price rose, -1 if it fell, 0 if unchanged.
Sine (radians).
Sine.
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.
plot(sin(toradians(barIndex * 10)))
A smooth oscillating (-1..1) wave driven by the bar index.
Square root.
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.
plot(sqrt(pow(high - low, 2)))
The square root of the squared bar range = the range itself (identity check).
Rolling sum over length bars.
The sum of the last length bars.
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.
plot(sum(volume, 5))
The total volume of the last 5 bars (rolling window).
Tangent (radians).
Tangent.
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.
plot(tan(0))
tan(0) = 0 (constant).
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 / π).
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.
plot(todegrees(3.141592653589793))
π radians = 180 degrees.
Converts degrees to radians. Result: 3.141592654
The same angle in radians (degrees × π / 180).
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.
plot(sin(toradians(90)))
Converts 90 degrees to radians and takes its sine → 1.