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)const float12.5Fixed stop offset or parameter distance
math.abs(close - open)series floatNon-negative 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(float(na))float with a missing valuenaRetain missing data unless a specific fallback is justified

Complete Pine Script v6 indicator using absolute value

The following script computes the absolute distance between price and an exponential moving average, then divides by the magnitude of price to express a non-negative percentage distance. It cannot distinguish above-EMA from below-EMA moves or establish overbought/oversold conditions. A zero or missing denominator returns na.

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 = not na(close) and close != 0 ? (absoluteDistance / math.abs(close)) * 100.0 : na

// 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: The old built-in abs() name is not available as that built-in in v5/v6. Use math.abs() rather than expecting only a compiler warning.
  • Handling na returns: A missing numeric input produces a missing result. Use an explicit numeric type for an na literal. Replacing missing data with zero changes the calculation and is appropriate only when zero is the intended fallback.
  • 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 value. Taking the maximum of an existing long stop and a new candidate prevents that stop level from decreasing; it does not guarantee a fill at that price.
  • math.min(x, y): Returns the lesser value. It can cap a calculated value or prevent a short-position stop from increasing when used with the previous stop.
Where Pineify fits

Pine Script AI Coding Agent

Request a Pine Script calculation, inspect its formula and missing-data behavior, and ask for an explicit syntax check of the final complete source.

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