Pine Script Math & Precision

Pine Script Absolute Value: How to Use math.abs() in TradingView

In Pine Script, the absolute value is calculated using the math.abs() function. It accepts an integer, float, or series of numbers and returns the non-negative magnitude of that value. If the input number is negative, math.abs() converts it to positive. If the input is zero or positive, it returns the number unchanged. If the input is na, the function returns na.

Build Pine Script with AI

Syntax and behavior of math.abs() in Pine Script v6

The math.abs() function operates on both simple scalars and dynamic series values. It is widely applied in technical indicators to measure divergence width, bar range size, and stop distances where the direction of the price offset is irrelevant.

Input expressionReturned typeOutput valuePractical application
math.abs(-12.5)simple float12.5Fixed stop offset or parameter distance
math.abs(close - open)series floatPositive candle body heightCandlestick pattern sizing and filter rules
math.abs(close - ta.sma(close, 20))series floatDistance from 20 SMAMean reversion bands and stretch oscillators
math.abs(na)series float / intnaMust be guarded with nz() during early chart bars

Complete Pine Script v6 indicator using absolute value

The following script computes the absolute distance between price and an exponential moving average, then normalizes that distance as a percentage of price to detect overbought and oversold market stretches.

Pine Script v6: Absolute price distance indicatorpinescript
//@version=6
indicator("Absolute Distance Oscillator [v6]", overlay = false)

// Input settings
int maLength = input.int(20, "Moving Average Length", minval = 1)
float thresholdPercent = input.float(1.5, "Stretch Threshold (%)", minval = 0.1)

// Calculations
float maValue = ta.ema(close, maLength)
float rawDistance = close - maValue
float absoluteDistance = math.abs(rawDistance)
float percentDistance = (absoluteDistance / close) * 100.0

// Color assignment based on threshold breach
color plotColor = percentDistance > thresholdPercent ? color.red : color.teal

// Visual output
plot(percentDistance, "Absolute Distance %", color = plotColor, linewidth = 2)
hline(thresholdPercent, "Stretch Line", color = color.gray, linestyle = hline.style_dashed)
hline(0.0, "Zero Line", color = color.gray)

Common mistakes when calculating absolute value

Traders and developers frequently encounter subtle calculation errors when dealing with numeric signs in Pine Script:

  • Namespace omission: Writing abs(x) instead of math.abs(x) triggers compiler warnings in modern Pine Script versions.
  • Handling na returns: If an indicator input is not yet ready, math.abs(na) produces na. Use nz(math.abs(x), 0.0) when accumulating running sums.
  • Directional loss: Absolute value removes sign data. If your strategy logic requires knowing whether price is above or below an EMA, retain the raw difference alongside the absolute distance.
  • Series type compatibility: math.abs() accepts both integers and floats, returning the same numeric type as the provided argument.

When to use math.abs() vs math.max() or math.min()

While math.abs() extracts raw magnitude, related math functions serve distinct mathematical purposes in strategy development:

  • math.abs(x - y): Measures the absolute distance between two levels regardless of which is higher.
  • math.max(x, y): Returns the greater of two values, frequently used for trailing stops to prevent stop levels from loosening.
  • math.min(x, y): Returns the lesser of two values, ideal for upper resistance caps and risk boundaries.
Where Pineify fits

Pine Script AI Coding Agent

Generate accurate Pine Script v6 indicators, mathematical models, and custom distance oscillators without syntax errors using Pineify AI.

Also useful: Visual Pine Editor. Assemble moving average filters and volatility bands visually with drag-and-drop ease.

Build Pine Script with AI

Frequently asked questions

Mathematical calculations in Pine Script reflect technical model formulas and do not guarantee profitable trading results. Verify all formulas on historical and real-time chart data before deploying capital.

Sources and verification