Time

Actualizado
█  OVERVIEW


This library is a Pine Script™ programmer’s tool containing a variety of time related functions to calculate or measure time, or format time into string variables.



█  CONCEPTS


`formattedTime()`, `formattedDate()` and `formattedDay()`

Pine Script™, like many other programming languages, uses timestamps in UNIX format, expressed as the number of milliseconds elapsed since 00:00:00 UTC, 1 January 1970. These three functions convert a UNIX timestamp to a formatted string for human consumption.

These are examples of ways you can call the functions, and the ensuing results:



These functions use str.format() and some of the special formatting codes it allows for. Pine Script™ documentation does not yet contain complete specifications on these codes, but in the meantime you can find some information in the The Java™ Tutorials and in Java documentation of its MessageFormat class. Note that str.format() implements only a subset of the MessageFormat features in Java.


`secondsSince()`

The introduction of varip variables in Pine Script™ has made it possible to track the time for which a condition is true when a script is executing on a realtime bar. One obvious use case that comes to mind is to enable trades to exit only when the exit condition has been true for a period of time, whether that period is shorter that the chart's timeframe, or spans across multiple realtime bars.

For more information on this function and varip please see our Using `varip` variables publication.



`timeFrom( )`

When plotting lines, boxes, and labels one often needs to calculate an offset for past or future end points relative to the time a condition or point occurs in history. Using xloc.bar_index is often the easiest solution, but some situations require the use of xloc.bar_time. We introduce `timeFrom()` to assist in calculating time-based offsets. The function calculates a timestamp using a negative (into the past) or positive (into the future) offset from the current bar's starting or closing time, or from the current time of day. The offset can be expressed in units of chart timeframe, or in seconds, minutes, hours, days, months or years. This function was ported from our Time Offset Calculation Framework.



`formattedNoOfPeriods()` and `secondsToTfString()`

Our final two offerings aim to confront two remaining issues:

How much time is represented in a given timestamp?
How can I produce a "simple string" timeframe usable with request.security() from a timeframe expressed in seconds?


`formattedNoOfPeriods()` converts a time value in ​ms to a quantity of time units. This is useful for calculating a difference in time between 2 points and converting to a desired number of units of time. If no unit is supplied, the function automatically chooses a unit based on a predetermined time step.

`secondsToTfString()` converts an input time in seconds to a target timeframe string in timeframe.period string format. This is useful for implementing stepped timeframes relative to the chart time, or calculating multiples of a given chart timeframe. Results from this function are in simple form, which means they are useable as `timeframe` arguments in functions like request.security().



█  NOTES


Although the example code is commented in detail, the size of the library justifies some further explanation as many concepts are demonstrated. Key points are as follows:
 • ​Pivot points are used to draw lines from. `timeFrom( )` calculates the length of the lines in the specified unit of time.
  By default the script uses 20 units of the charts timeframe. Example: a 1hr chart has arrows 20 hours in length.
 • At the point of the arrows `formattedNoOfPeriods()` calculates the line length in the specified unit of time from the input menu.
  If “Use Input Time” is disabled, a unit of time is automatically assigned.
 • At each ​pivot point a label with a formatted date or time is placed with one of the three formatting helper functions to display the time or date the ​pivot occurred.
 • A label on the last bar showcases `secondsSince()`. The label goes through three stages of detection for a timed alert.
  If the difference between the high and the open in ticks exceeds the input value, a timer starts and will turn the label red once the input time is exceeded to simulate a time-delayed alert.
 • In the bottom right of the screen `secondsToTfString()` posts the chart timeframe in a table. This can be multiplied from the input menu.


Look first. Then leap.



█  FUNCTIONS


formattedTime(timeInMs, format)
  Converts a UNIX timestamp (in milliseconds) to a formatted time string.
  Parameters:
    timeInMs: (series float) Timestamp to be formatted.
    format: (series string) Format for the time. Optional. The default value is "HH:mm:ss".
  Returns: (string) A string containing the formatted time.

formattedDate(timeInMs, format)
  Converts a UNIX timestamp (in milliseconds) to a formatted date string.
  Parameters:
    timeInMs: (series float) Timestamp to be formatted.
    format: (series string) Format for the date. Optional. The default value is "yyyy-MM-dd".
  Returns: (string) A string containing the formatted date.

formattedDay(timeInMs, format)
  Converts a UNIX timestamp (in milliseconds) to the name of the day of the week.
  Parameters:
    timeInMs: (series float) Timestamp to be formatted.
    format: (series string) Format for the day of the week. Optional. The default value is "EEEE" (complete day name).
  Returns: (string) A string containing the day of the week.

secondsSince(cond, resetCond)
  The duration in milliseconds that a condition has been true.
  Parameters:
    cond: (series bool) Condition to time.
    resetCond: (series bool) When `true`, the duration resets.
  Returns: The duration in seconds for which `cond` is continuously true.

timeFrom(from, qty, units)
  Calculates a +/- time offset in variable units from the current bar's time or from the current time.
  Parameters:
    from: (series string) Starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
    qty: (series int) The +/- qty of units of offset required. A "series float" can be used but it will be cast to a "series int".
    units: (series string) String containing one of the seven allowed time units: "chart" (chart's timeframe), "seconds", "minutes", "hours", "days", "months", "years".
  Returns: (int) The resultant time offset `from` the `qty` of time in the specified `units`.

formattedNoOfPeriods(​ms, unit)
  Converts a time value in ​ms to a quantity of time units.
  Parameters:
    ms: (series int) Value of time to be formatted.
    unit: (series string) The target unit of time measurement. Options are "seconds", "minutes", "hours", "days", "weeks", "months". If not used one will be automatically assigned.
  Returns: (string) A formatted string from the number of `ms` in the specified `unit` of time measurement

secondsToTfString(tfInSeconds, mult)
  Convert an input time in seconds to target string TF in `timeframe.period` string format.
  Parameters:
    tfInSeconds: (simple int) a timeframe in seconds to convert to a string.
    mult: (simple float) Multiple of `tfInSeconds` to be calculated. Optional. 1 (no multiplier) is default.
  Returns: (string) The `tfInSeconds` in `timeframe.period` format usable with `request.security()`.
Notas de prensa
v2

Minor typos and updates.

`formattedNoOfPeriods()` now returns singular form, rather than plural when the number of time units is less than 2. For a 1min timeframe, it will thus return "1 minute" instead of "1 minutes".

Changed the default value of the `resetCond` parameter in `secondsSince()` to `barstate.isnew`. By default, the function will now reset the timer on each new bar, unless otherwise stated. The updated documentation is as follows:


secondsSince(cond, resetCond)
  The duration in milliseconds that a condition has been true.
  Parameters:
    cond: (series bool) Condition to time.
    resetCond: (series bool) When `true`, the duration resets. Optional. Default is `barstate.isnew`.
  Returns: (int) The duration in seconds for which `cond` is continuously true.
Notas de prensa
v3

Small bug fix for `formattedNoOfPeriods()` in regards to returning plural timeframe units.
Notas de prensa
v4

Updated the `secondsToTfString()` function to support the recently added 10S timeframe.

formattingstringstimesessions

Biblioteca Pine

Siguiendo fielmente el espíritu TradingView, el autor ha publicado este código Pine como una biblioteca de código abierto, permitiendo que otros programadores de Pine en nuestra comunidad lo utilicen de nuevo. ¡Olé por el autor! Puede utilizar esta biblioteca de forma privada o en otras publicaciones de código abierto, pero tenga en cuenta que la reutilización de este código en una publicación se rige por las Normas internas.


Tools and ideas for all Pine coders: pinecoders.com
Our Pine FAQ & Code: pinecoders.com/faq_and_code/
Pine news broadcasts: t.me/PineCodersSquawkBox or twitter.com/PineCoders
También en:

Exención de responsabilidad