Introduction
The barstate.isnew
function is pivotal in scripts that require action at the beginning of a new bar on the chart. We will explore its application through examples, ensuring a deep understanding of its use and benefits.
What is barstate.isnew
?
Definition and Basic Use
In Pine Script, barstate.isnew
is a boolean variable that returns true
if the script is executing on the first tick of a new bar. This feature is essential for strategies or studies where specific calculations or actions need to be performed only once per bar.
Syntax
if barstate.isnew // Your code here
Example: Implementing barstate.isnew
Let’s create a simple script that utilizes barstate.isnew
to calculate and plot a moving average only once per bar.
Code Example
//@version=5 indicator("My Moving Average with barstate.isnew", overlay=true) length = input(14, "Moving Average Length") price = close var float myMovingAvg = na if barstate.isnew myMovingAvg := ta.sma(price, length) plot(myMovingAvg, "Moving Average", color=color.blue)
Explanation of the Code
- Indicator Declaration:
//@version=5 indicator("My Moving Average with barstate.isnew", overlay=true)
- Sets the script version and declares a new indicator with the title “My Moving Average with barstate.isnew”.
overlay=true
allows the plot to be drawn directly on the price chart.
- Sets the script version and declares a new indicator with the title “My Moving Average with barstate.isnew”.
- Inputs and Variables:
length = input(14, "Moving Average Length") price = close var float myMovingAvg = na
length
is the period of the moving average, set to 14 by default.price
uses the closing price of the bar.myMovingAvg
is a variable to store the moving average value, initialized asna
(not available).
- Using
barstate.isnew
:if barstate.isnew myMovingAvg := ta.sma(price, length)
- This block updates
myMovingAvg
with the simple moving average (ta.sma
) of theprice
over the specifiedlength
, but only at the beginning of a new bar.
- This block updates
- Plotting the Moving Average:
plot(myMovingAvg, "Moving Average", color=color.blue)
- The
plot
function draws the moving average on the chart with the label “Moving Average” in blue color.
- The
Key Features and Takeaways
- Function Utility:
barstate.isnew
is ideal for scenarios where calculations are required only once per bar, optimizing script performance. - Syntax and Application: The function is straightforward, using a simple
if
condition to check for a new bar. - Versatility: It can be applied in various contexts, such as indicators, strategies, or custom calculations.
In conclusion, barstate.isnew
in Pine Script Version 5 is a valuable tool for script optimization and precise calculations. Its correct implementation can significantly enhance the performance and accuracy of trading scripts.