Pine Script Data Sanitization

Pine Script NZ and NA: Replacing Null Values and Preventing Runtime Errors

In Pine Script, na represents an unavailable or missing value, similar to null or NaN in other programming languages. The nz() function replaces na values with a specified replacement value; if no replacement is supplied, nz() defaults to 0. The na() function checks if an expression is na and returns a boolean (true or false). These functions prevent cascading calculation errors on historical chart bars.

Fix Pine Script Errors with AI

How na values propagate and how nz() stops them in v6

In Pine Script, any mathematical operation performed on an na value results in na (for example, na + 5 equals na). Because moving averages and oscillators produce na during their initial warmup period, unshielded cumulative calculations will permanently fail without nz().

Function callInput stateResulting outputPrimary usage
nz(close[1])First bar of chart (where close[1] is na)0.0Prevents crash when calculating bar-over-bar differences on bar 0
nz(fastMa, close)Warmup period (where fastMa is na)Current close priceSupplies a safe fallback so envelopes plot immediately
na(myVar)myVar is unassigned or natrueGuarding execution blocks before a signal has occurred
nz(dailyClose, dailyClose[1])Intrabar gap from request.securityLast known daily closeForward-filling gaps in multi-timeframe datasets

Complete Pine Script v6 script with safe na handling

The following Pine Script v6 indicator computes a cumulative running sum of volume-weighted price deltas. It uses nz() to initialize running totals cleanly on bar 0 and handles missing data gracefully.

Pine Script v6: Cumulative momentum tracker shielded with nz()pinescript
//@version=6
indicator("Safe Cumulative Momentum [v6]", overlay = false)

// Input parameters
int period = input.int(14, "Smoothing Period", minval = 1)
float fallbackLevel = input.float(0.0, "Warmup Default Value")

// Calculate price change safely on first bar
float priceChange = close - nz(close[1], close)
float volumeWeight = priceChange * volume

// Running cumulative delta using var with nz initialization
var float cumulativeDelta = 0.0
cumulativeDelta := cumulativeDelta + nz(volumeWeight, 0.0)

// Calculate smoothed line
float smoothedLine = ta.sma(cumulativeDelta, period)

// Replace na during warmup so chart plot stays continuous
float safePlotLine = nz(smoothedLine, cumulativeDelta)

// Visual output
plot(cumulativeDelta, "Raw Cumulative Delta", color = color.gray, linewidth = 1)
plot(safePlotLine, "Smoothed Signal", color = color.blue, linewidth = 2)
hline(0.0, "Zero Line", color = color.slate, linestyle = hline.style_dashed)

// Diagnostic label on last bar if warmup is ongoing
if barstate.islast and na(smoothedLine)
    label.new(bar_index, 0.0, "Indicator still in warmup", color = color.orange, textcolor = color.white)

Key differences between na, 0, and undefined in Pine Script

Understanding how TradingView handles null states avoids subtle bugs in strategy order generation:

  • na is not zero: Writing myVal == 0 will not evaluate to true when myVal is na. Always write na(myVal) or use nz(myVal) == 0.
  • plot() suppression: Passing na into plot() or plotshape() produces no visual mark on the chart, which is the standard technique for hiding indicator lines conditionally.
  • Warmup periods: Built-ins like ta.sma(close, 200) yield 199 bars of na. If your strategy checks ta.crossover(close, sma200), that condition will stay false until bar 200.
  • Custom fallbacks: nz() accepts a second parameter. For price levels, fallback to close (e.g. nz(stopLevel, close)) rather than 0.0 to prevent charting price spikes down to zero.

Safe handling of higher-timeframe data feeds

When fetching higher-timeframe data via request.security(), missing ticks and closed sessions frequently introduce na values into the series:

  • Forward fill: Use nz(htfValue, htfValue[1]) or request.security with gaps = barmerge.gaps_off to avoid gaps between higher-timeframe candle completions.
  • Sanitizing ratio calculations: When computing ratios like close / htfClose, verify that neither value is na and htfClose != 0 to prevent runtime math failures.
  • Alert safety: Ensure any condition feeding alertcondition() evaluates to false rather than na when data feeds lag.
Where Pineify fits

Pine Script AI Coding Agent

Sanitize data inputs, eliminate runtime na calculation crashes, and generate robust Pine Script v6 indicators with Pineify AI.

Also useful: Visual Pine Editor. Create indicators with automatic na handling and zero-value fallbacks built into every block.

Fix Pine Script Errors with AI

Frequently asked questions

Data sanitization with nz() provides numeric stability but does not correct underlying market data gaps. Validate all calculation assumptions against authentic historical exchange feeds.

Sources and verification