Skip to main content
On this page

math.abs() in Pine Script: Magnitudes, Units and Missing Values

· 4 min read
Pineify Team
Pine Script and AI trading workflow research team

math.abs() returns the magnitude of a numeric value: -5 becomes 5, and 5 stays 5. It removes direction; it does not normalize units, identify a divergence, or turn missing data into a valid observation.

Understanding math.abs() Function in Pine Script

Function and bar-return examples​

The following short fragments belong inside a script; they are not standalone indicators. yourNumber represents a numeric expression you must supply.

result = math.abs(yourNumber)

This return expression compares the current close with the previous chart bar, despite the variable name dailyChange. It is a daily return only on a daily chart. The previous close must exist and be nonzero:

dailyChange = math.abs((close - close[1]) / close[1] * 100)

Complete movement detector​

The existing v6 example below marks bars whose absolute close-to-close percentage move exceeds the input threshold. It does not predict a move or create a TradingView alert automatically.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
indicator("Smart Move Detector", overlay=true)

// User can adjust what qualifies as a "significant" move
moveThreshold = input.float(2.0, title="Movement Threshold (%)", minval=0.1, maxval=10.0)

// Calculate percentage change from previous bar
priceChangePercent = (close - close[1]) / close[1] * 100

// Get absolute value - direction doesn't matter for size
absoluteMovement = math.abs(priceChangePercent)

// Determine if this is a significant move
isSignificantMove = absoluteMovement > moveThreshold

// Visual alerts on chart
plotshape(
series = isSignificantMove,
location = location.belowbar,
color = color.orange,
style = shape.triangleup,
size = size.small,
title = "Big Move Alert"
)

// Plot the actual movement percentage
plot(absoluteMovement, title="Daily Movement %", color=color.blue, linewidth=2)

// Add a reference line for the threshold
hline(moveThreshold, title="Alert Threshold", color=color.red, linestyle=hline.style_dashed)

The plotted title “Daily Movement %” is descriptive text, not a timeframe request. The calculation uses chart bars. Because overlay=true, the percentage plot shares the price pane and can distort its scale; the triangles are easier to interpret than the line on some instruments. The first bar lacks a previous close, and a developing realtime close can change the current marker.

Interpret the calculation fragments​

This fragment averages the chart-bar high-low range. Since high is normally at least low, the absolute value is redundant. It is not ATR because it omits gaps relative to the previous close:

// Calculate average daily range over 20 periods
avgRange = ta.sma(math.abs(high - low), 20)
stopDistance = avgRange * 2 // Stop loss at 2x average range

The next fragment measures two magnitudes. It does not detect bullish or bearish divergence, because it discards signs and does not match swing points:

priceMove = math.abs(close - close[5])
rsiMove = math.abs(ta.rsi(close, 14) - ta.rsi(close, 14)[5])

This position-sizing sketch requires you to define the three inputs. A zero distance must be rejected. Price distance alone is not cash risk for every instrument; contract point value, currency conversion, lot increments and costs may also matter:

potentialLoss = math.abs(entryPrice - stopLoss)
positionSize = riskAmount / potentialLoss

Here each bar’s deviation is measured from that bar’s rolling mean, then those deviations are averaged. This differs from measuring every observation in the window against one current window mean:

// Average absolute deviation from moving average
avgPrice = ta.sma(close, 20)
deviation = math.abs(close - avgPrice)
avgDeviation = ta.sma(deviation, 20)

This final fragment expresses the open-to-close magnitude as a percentage. The division, not math.abs() itself, supplies the relative scale. It requires a valid, nonzero open:

normalizedMove = math.abs(close - open) / open * 100

Missing values and practical limits​

A missing numeric input yields a missing result. Substituting zero with nz() changes the meaning of the observation and should be intentional, not a general error fix. Likewise, a stop distance calculated from current volatility is not a complete stop-order implementation.

The earlier claim of detecting an AAPL gap before other alerts had no supporting trade or alert record. The examples demonstrate arithmetic only. They do not support a return forecast or a best threshold for a particular asset.

Source checked October 20, 2026: Pine Script v6 reference. The math namespace applies in v5 and v6; older examples may use abs() without that prefix.

Pineify Pine Script Editor