Home » Ticker Functions » Understanding the timeframe.change() Function in Pine Script

Understanding the timeframe.change() Function in Pine Script

Photo of author
Published on

Let’s dive deeper into its syntax, arguments, and practical applications of timeframe.change() Function in Pine Script

Syntax

The syntax for the timeframe.change() function is straightforward:

timeframe.change(timeframe) → series bool

This function takes a single argument, timeframe, which is a string formatted according to the User manual’s timeframe string specifications, and returns a boolean series. The boolean series indicates true on the first bar of a new timeframe and false otherwise.

Arguments

  • timeframe (series string): A string that specifies the timeframe to detect changes in. This string must be formatted according to the specifications outlined in the User manual, with common examples including “1D” for daily, “4H” for four-hourly, etc.

Example

Let’s consider the provided example to understand how the timeframe.change() function can be implemented:

//@version=5
// Run this script on an intraday chart.
indicator("New day started", overlay = true)
// Highlights the first bar of the new day.
isNewPeriod = timeframe.change("1D")
bgcolor(isNewPeriod ? color.new(color.blue, 80) : na)
Example

In this example, the script is designed to be run on an intraday chart. It uses the timeframe.change() function to detect the start of a new day. When the first bar of a new day is detected, it highlights that bar with a specified background color.

Walkthrough of Code 

  • indicator("New day started", overlay = true) declares the script as an indicator with the title “New day started” and specifies that it should be drawn over the main price chart.
  • isNewPeriod = timeframe.change("1D") checks for the transition to a new day by using the “1D” timeframe string. The result is stored in the isNewPeriod variable, which is a series of boolean values.
  • bgcolor(isNewPeriod ? color.new(color.blue, 80) : na) uses a ternary operator to change the background color of the chart to a semi-transparent blue on the first bar of a new day. If isNewPeriod is false, no background color is applied (na).

Key Features and Takeaways

  • Function Usability: The timeframe.change() function is essential for scripts that need to perform actions or calculations at the beginning of a new timeframe.
  • Syntax and Application: It requires a string argument specifying the target timeframe and returns a boolean series, making it versatile for various trading strategies.
  • Practical Example: The provided example illustrates how to use this function to highlight the first bar of a new day on an intraday chart, aiding visual analysis and strategy development.

Leave a Comment