PINE LIBRARY
Atualizado Utils

Library "Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float): (float) the number to be formatted
Returns: (string) The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int): (int) The timestamp to stringify
Returns: (int) The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int): (int) The timestamp to stringify
Returns: (int) The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: (int) The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: ["Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool): (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int): (int) The hour number
minuteNumber (int): (int) The minute number
Returns: (int) The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int): The timestamp to start with (# of seconds)
end (int): The timestamp to end with (# of seconds)
Returns: (float) The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple) [premarketHigh, premarketLow]
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple) [afterHoursHigh, afterHoursLow]
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple) [overnightHigh, overnightLow]
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple) [premarketHigh, premarketLow, afterHoursHigh, afterHoursLow, overnightHigh, overnightLow]
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: ["Solid", "Dashed", "Dotted", "None/Hidden"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string): (string) Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool): (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: (float) The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string): (string) Plain english position string
Returns: (string) The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: (string) The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int): (int) The number of items to find singular/plural for.
Returns: (int) The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int): The timestamp to start with (# of seconds)
end (int): The timestamp to end with (# of seconds)
Returns: (float) The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: (bool) True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string): (string) The string to be padded
labelStyle (string): (string) The style of the label being padded for.
Returns: (string) The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int): (int) The number of items to find singular/plural for.
singular (string): (string) The string to return if num is singular. Defaults to an empty string.
plural (string): (string) The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: (string) The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: (int) The number of secondsof that timeframe
timeframeToString(tf)
Convert a timeframe string to a consistent standard.
Parameters:
tf (string): (string) The timeframe string to convert
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float): (float) the number to be formatted
Returns: (string) The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int): (int) The timestamp to stringify
Returns: (int) The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int): (int) The timestamp to stringify
Returns: (int) The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: (int) The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: ["Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool): (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int): (int) The hour number
minuteNumber (int): (int) The minute number
Returns: (int) The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int): The timestamp to start with (# of seconds)
end (int): The timestamp to end with (# of seconds)
Returns: (float) The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple) [premarketHigh, premarketLow]
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple) [afterHoursHigh, afterHoursLow]
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple) [overnightHigh, overnightLow]
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple) [premarketHigh, premarketLow, afterHoursHigh, afterHoursLow, overnightHigh, overnightLow]
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: ["Solid", "Dashed", "Dotted", "None/Hidden"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string): (string) Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool): (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: (float) The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string): (string) Plain english position string
Returns: (string) The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: (string) The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int): (int) The number of items to find singular/plural for.
Returns: (int) The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int): The timestamp to start with (# of seconds)
end (int): The timestamp to end with (# of seconds)
Returns: (float) The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: (bool) True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string): (string) The string to be padded
labelStyle (string): (string) The style of the label being padded for.
Returns: (string) The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int): (int) The number of items to find singular/plural for.
singular (string): (string) The string to return if num is singular. Defaults to an empty string.
plural (string): (string) The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: (string) The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: (int) The number of secondsof that timeframe
timeframeToString(tf)
Convert a timeframe string to a consistent standard.
Parameters:
tf (string): (string) The timeframe string to convert
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
Notas de Lançamento
v2 Added getSizeString function. Updated function comments.Added:
getSizeFromString(sizeString)
Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"]. This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
sizeString (string): Plain english size string
Returns: The string expected by tradingview functions
Notas de Lançamento
v3 Fixed a bug that caused size to return incorrectly in getSizeFromString()Notas de Lançamento
v4 Added convenience functions for calculating price levels associated with RSI levels.Added:
getRsiAvgsExpression(rsiLength)
Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
Parameters:
rsiLength (simple int): The length of the RSI requested.
Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown)
use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
Parameters:
rsiLevel (float): The RSI level to find price at.
rsiLength (int): The length of the RSI to calculate.
avgUp (float): The average move up of RSI.
avgDown (float): The average move down of RSI.
Returns: The price level where the provided RSI level would be met.
Notas de Lançamento
v5 Modified getRsiAvgsExpression to also return the RSI value.Notas de Lançamento
v6 Added convenience functions for rendering price labels.Added:
getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor)
Defines a label for the end of a price level line.
Parameters:
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
labelStyle (string): A plain english string as defined in getLabelStyleFromString.
labelSize (string): The size of the label.
labelColor (color): The color of the label.
textColor (color): The color of the label text (defaults to #ffffff)
Returns: The label that was created.
setPriceLabel(label, labelName, price, labelOffset)
Updates the label position & text based on price changes.
Parameters:
label (label): The label to update.
labelName (string): The name of the price level to be placed on the label.
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
getPriceLabelLine(price, labelOffset, labelColor, lineWidth)
Defines a line that will stretch from the plot line to the label.
Parameters:
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
labelColor (color)
lineWidth (int): The width of the line. Defaults to 1.
setPriceLabelLine(line, price, labelOffset, lastTime)
Updates the price label line based on price changes.
Parameters:
line (line): The line to update.
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
lastTime (int): The last time that the line should stretch from. Defaults to time.
Notas de Lançamento
v7 Fixed a mistake on timeframeToString function, and introduced a new function to get the English-friendly timeframe of the chart.Added:
timeframeOfChart()
Convert a timeframe string to a consistent standard.
Returns: The standard format for the string, or the unchanged value if it is unknown.
Updated:
timeframeToString(timeframe)
Convert a timeframe string to a consistent standard.
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
Notas de Lançamento
v8 Fixed a bug where price label was dropping the 0 on .10c prices.Notas de Lançamento
v9 Updated timeframeToString to calculate the strings instead of using a set dictionary.Notas de Lançamento
v10 Adding ability to override label template on price labelsUpdated:
setPriceLabel(label, labelName, price, labelOffset, labelTemplate)
Updates the label position & text based on price changes.
Parameters:
label (label): The label to update.
labelName (string): The name of the price level to be placed on the label.
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
labelTemplate (string): The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
Notas de Lançamento
v11 Added changing colors to lines/labels.Updated:
setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor)
Updates the label position & text based on price changes.
Parameters:
label (label): The label to update.
labelName (string): The name of the price level to be placed on the label.
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
labelTemplate (string): The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
labelStyle (string)
labelColor (color)
textColor (color)
setPriceLabelLine(line, price, labelOffset, lastTime, lineColor)
Updates the price label line based on price changes.
Parameters:
line (line): The line to update.
price (float): The price level to render the label at.
labelOffset (int): The number of candles to place the label to the right of price.
lastTime (int): The last time that the line should stretch from. Defaults to time.
lineColor (color)
Notas de Lançamento
v12 Added convenience functionAdded:
stringToTimeframe(strTimeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
strTimeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
Notas de Lançamento
v13 Migrated to pine version 6. Fixed a bug in stringToTimeframe that caused hour timeframes to fail when an hour number is not provided.Notas de Lançamento
v14 Another bugfix to stringToTimeframeUpdated:
stringToTimeframe(timeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
Notas de Lançamento
v15 Added convenience functions for determining if the current chart's bars can be used to calculate a moving average rather than calling request.security for the same.Added:
getMinutesInSession()
Determine the total session length in minutes on a given chart (because tradingview does not provide these values, and the user could be looking at regular or extended session data)
Returns: int The number of minutes per session
getTimeframeMinutes(timeframe)
Convenience function used to determine if a provided timeframe can be used when calculating a moving average on the current chart (instead of calling request.security for the same)
Parameters:
timeframe (string)
Returns: int the number of minutes in the provided timeframe if valid for these kinds of calculations, na otherwise.
getValidMALength(htfMinutes, length)
Used when determining if a moving average on a higher timeframe can be calculated using the bars on the current chart.
Parameters:
htfMinutes (int): The number of minutes in the higher timeframe being requested for the moving average
length (int): The length of the moving average being calculated
Returns: int The number of minutes in the higher timeframe moving average if there is enough data on the chart to calculate the moving average
Notas de Lançamento
v16 Added a bugfix to not hard-code the max_bars_backUpdated:
getValidMALength(htfMinutes, length, maxBarsBack)
Used when determining if a moving average on a higher timeframe can be calculated using the bars on the current chart.
Parameters:
htfMinutes (int): The number of minutes in the higher timeframe being requested for the moving average
length (int): The length of the moving average being calculated
maxBarsBack (int): The max # of bars back that we should be allowed to use. Defaults to 5000
Returns: int The number of minutes in the higher timeframe moving average if there is enough data on the chart to calculate the moving average
Biblioteca do Pine
No verdadeiro espirito do TradingView, o autor desse código Pine o publicou como uma biblioteca de código aberto, para que outros programadores Pine da nossa comunidade possam reusa-los. Parabéns ao autor! Você pode usar essa biblioteca privadamente ou em outras publicações de código aberto, mas a reutilização desse código em publicações é regida pelas Regras da Casa.
I release TradingView indicators and libraries designed to make you a better trader. For detailed info about them, head over to improve.trading
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Biblioteca do Pine
No verdadeiro espirito do TradingView, o autor desse código Pine o publicou como uma biblioteca de código aberto, para que outros programadores Pine da nossa comunidade possam reusa-los. Parabéns ao autor! Você pode usar essa biblioteca privadamente ou em outras publicações de código aberto, mas a reutilização desse código em publicações é regida pelas Regras da Casa.
I release TradingView indicators and libraries designed to make you a better trader. For detailed info about them, head over to improve.trading
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.