One versatile function available in Pine Script is nz
, which stands for “non-zero”. In this tutorial, we will take an in-depth look at the nz
function, its syntax, and how to effectively use it in your Pine Script code.
What is nz
in Pine Script?
The nz
function is designed to replace NaN
(Not a Number) values with zeros or a specified replacement value in a series. This function is particularly useful when dealing with technical indicators or strategies that often generate NaN
values.
The nz
function can be used with various types of values such as integers, floats, colors, and boolean values. It can handle both simple values and series of these types.
Syntax of nz
The syntax of the nz
function is as follows:
nz(source, replacement)
Where:
source
is the series of values to process. This could be a series of integers, floats, boolean values, or colors.replacement
is the optional value that will replace allNaN
values in thesource
series. This can also be a series of integers, floats, boolean values, or colors.
If the replacement
argument is not specified, the nz
function defaults to zero.
Practical Use Case Example
Let’s go through an example to better understand the nz
function. In this example, we will use a simple moving average (SMA) of the close price over the last 100 periods. SMA can have NaN
values for the first few bars of the chart where there isn’t enough data to calculate a 100-period SMA.
//@version=5 indicator("nz", overlay=true) plot(nz(ta.sma(close, 100)))

In this code:
- We’re using Pine Script version 5 (
//@version=5
) indicator("nz", overlay=true)
creates a new indicator script with the title “nz”. Theoverlay=true
means the indicator will be plotted on the price chart.plot(nz(ta.sma(close, 100)))
plots the 100-period SMA of the close prices, using thenz
function to replaceNaN
values with zero.
Key Takeaways
The nz
function is a valuable tool in Pine Script, especially when dealing with technical indicators or strategies that often produce NaN
values. Remember these key points:
- The
nz
function is used to replaceNaN
values with a specified value (default is zero). - It can handle various types of data – integers, floats, colors, and boolean – and works with both simple values and series of these types.
- The
nz
function is crucial for ensuring that your Pine Script code doesn’t crash or behave unexpectedly due toNaN
values.
Conclusion
Understanding and effectively using the nz
function is critical for coding robust indicators and strategies in Pine Script. It ensures your script can handle NaN
values gracefully and prevents unexpected behavior that could arise from such values. Whether you’re a beginner or an experienced Pine Script developer, the nz
function is a powerful tool in your coding arsenal.