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

Understanding the timeframe.from_seconds() Function in Pine Script

Photo of author
Published on

This article will delve into the syntax, usage, examples, and key remarks of the timeframe.from_seconds() function, providing a comprehensive guide for Pine Script users.

Syntax

The timeframe.from_seconds() function comes in two forms:

  • timeframe.from_seconds(seconds) → simple string
  • timeframe.from_seconds(seconds) → series string

Arguments

  • seconds (simple int): This argument specifies the number of seconds you want to convert into a Pine Script compliant timeframe string.

Example

Let’s look at an example to understand how to use the timeframe.from_seconds() function effectively.

//@version=5
indicator("Extended TF Close", "", true)
int currentTfSeconds = timeframe.in_seconds()
string timeframeX5 = timeframe.from_seconds(currentTfSeconds * 5)
float extendedTfClose = request.security(syminfo.tickerid, timeframeX5, close)
plot(extendedTfClose)
Example

Walkthrough of Code

  • We define an indicator called “Extended TF Close”.
  • We obtain the current chart’s timeframe in seconds using timeframe.in_seconds() and store it in currentTfSeconds.
  • We then multiply currentTfSeconds by 5 to get a new timeframe, which is five times the current timeframe, and convert it into a Pine Script compliant timeframe string using timeframe.from_seconds(currentTfSeconds * 5).
  • The request.security function requests data (specifically the close price) for the ticker symbol of the current chart at the newly calculated timeframe.
  • Finally, we plot the close prices of the extended timeframe using plot(extendedTfClose).

Key Features and Remarks

  • Automatic Adjustment: If the number of seconds does not match a valid Pine Script timeframe, the function automatically adjusts to the next higher valid timeframe.
  • Specific Returns: For inputs of one second or less, it returns “1S”. For inputs between 2 and 5 seconds, it returns “5S”. Notably, 604,799 seconds returns “7D”, and 604,800 seconds returns “1W”, not “7D”.
  • Upper Limit: All values above 31,622,400 seconds (approximately 366 days) will return a “12M” timeframe, indicating the maximum timeframe granularity supported by this function.

Conclusion

  • The timeframe.from_seconds() function is a powerful tool for dynamically adjusting timeframes in Pine Script.
  • It provides flexibility in accessing data from different timeframes, enhancing the capability of indicators and strategies.
  • The automatic adjustment to the next valid timeframe ensures that scripts remain robust and adaptable to various chart settings.

By mastering the timeframe.from_seconds() function, Pine Script developers can create more dynamic, responsive, and versatile trading tools.

Leave a Comment