iteratorThe "Iterator" library is designed to provide a flexible way to work with sequences of values. This library offers a set of functions to create and manage iterators for various data types, including integers, floats, and more. Whether you need to generate an array of values with specific increments or iterate over elements in reverse order, this library has you covered.
Key Features:
Array Creation: Easily generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
Flexible Iteration: Includes methods to iterate over arrays of different types, such as booleans, integers, floats, strings, colors, and drawing objects like lines and labels.
Reverse Iteration: Support for reverse iteration, giving you control over the order in which elements are processed.
Automatic Loop Control: One of the key advantages of this library is that when using the .iterate() method, it only loops over the array when there are values present. This means you don’t have to manually check if the array is populated before iterating, simplifying your code and reducing potential errors.
Versatile Use Cases: Ideal for scenarios where you need to loop over an array without worrying about empty arrays or checking conditions manually.
This library is particularly useful in cases where you need to perform operations on each element in an array, ensuring that your loops are efficient and free from unnecessary checks.
Library "iterator"
The "iterator" library provides a versatile and efficient set of functions for creating and managing iterators.
It allows you to generate arrays of integers or floats with customizable steps, both inclusive and exclusive of the end values.
The library also includes methods for iterating over various types, including booleans, integers, floats, strings, colors,
and drawing objects like lines and labels. With support for reverse iteration and flexible customization options.
iterator(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop. Will return and empty array if start = stop.
iterator_inclusive(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
iterator_inclusive(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
itr(stop, start, step)
Creates an array of integers from start to stop with a specified step, excluding the stop value.
Parameters:
stop (int) : The end value of the iterator, exclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop.
itr(stop, start, step)
Creates an array of floats from start to stop with a specified step, excluding the stop value.
Parameters:
stop (float) : The end value of the iterator, exclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop.
itr_in(stop, start, step)
Creates an array of integers from start to stop with a specified step, including the stop value.
Parameters:
stop (int) : The end value of the iterator, inclusive.
start (int) : The starting value of the iterator. Default is 0.
step (int) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of integers incremented by the step value from start to stop, including the stop value.
itr_in(stop, start, step)
Creates an array of floats from start to stop with a specified step, including the stop value.
Parameters:
stop (float) : The end value of the iterator, inclusive.
start (float) : The starting value of the iterator. Default is 0.
step (float) : The increment value for each step in the iterator. Default is 1. Must be greater than 0.
Returns: An array of floats incremented by the step value from start to stop, including the stop value.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
method iterate(self, reverse)
Creates an iterator array for the indices of ana array, with an option to reverse the order.
Namespace types: array
Parameters:
self (array) : The array to iterate over.
reverse (bool) : A boolean flag indicating whether to reverse the iterator order. Default is false.
Returns: An array of integers representing the indices of the array. The order can be reversed if specified.
Utilities
Maximum Bar Range in TicksThis is a simple indicator that gives the maximum range of any bar on the chart in ticks. I found it useful when sizing arrays and it might also be valuable when working out risk parameters.
Dark & Light Theme [TradingFinder] Switching Colors Library🔵 Introduction
One of the challenges of script users is matching the colors used in indicators or strategies. By default, colors are chosen to display based on either the dark theme or the light theme.
In scripts with a large number of colors used, changing all colors to better display in dark mode or light mode can be a difficult and tedious process.
This library provides developers with the ability to adjust the colors used in their scripts based on the theme of the display.
🔵 Logic
To categorize the color spectrum, the range from 0 to 255 of all three main colors red, green and blue was divided into smaller ranges.
Blue color, which is more effective in darkening or lightening colors, is divided into 8 categories, red color into 5 categories, and green color into 3 categories, because it has little effect on darkening or brightening colors.
The combination of these categories creates 120 different modes for the color range, which leads to a more accurate identification of the color and its brightness, and helps to decide how to change it.
Except for these 120 modes, there are 2 other modes that are related to colors almost white or black, which makes a total of 122 modes.
🔵 How to Use
First, you can add the library to your code as shown in the example below.
import TFlab/Dark_Light_Theme_TradingFinder_Switching_Colors_Library/1 as SC
🟣 Parameters
SwitchingColorMode(Color, Mode) =>
Parameters:
Color (color)
Mode (string)
Color : In this parameter, enter the color you want to adjust based on light mode and dark mode.
Mode : Three modes "Off", "Light" and "Dark" are included in this parameter. "Light" mode is for color adjustment for use in "Light Mode".
"Dark" mode is for color adjustment for use in "Dark Mode" and "Off" mode turns off the color adjustment function and the input color to the function is the same as the output color.
🔵 Function Outputs
OriginalColor = input.color(color.red)
= SC.SwitchingColorMode(OriginalColor, Mode)
TimeFilterLibrary "TimeFilter"
provides utilities for dates and times
inSession(session, timezone, period)
Parameters:
session (simple string)
timezone (simple string)
period (simple string)
Returns: bool inSession Whether the current time is within the defined time session
inDateRange(startDate, endDate)
Parameters:
startDate (int)
endDate (int)
Returns: bool inRange Whether the current time is within the defined date range
isWeekDay(weekDay, timezone)
Parameters:
weekDay (int)
timezone (simple string)
Returns: bool isWeekDay Whether the provided day is the current day of the week
inWeek(useMon, useTue, useWed, useThu, useFri, useSat, useSun, timezone)
Parameters:
useMon (bool)
useTue (bool)
useWed (bool)
useThu (bool)
useFri (bool)
useSat (bool)
useSun (bool)
timezone (simple string)
Returns: bool inWeek Whether the current time is one of the defined days
filter(useRange, useSession, useWeek, inRange, inSession, inWeek)
Parameters:
useRange (bool)
useSession (bool)
useWeek (bool)
inRange (bool)
inSession (bool)
inWeek (bool)
Returns: bool filter Whether the filter matches or not
garbage_collection_and_utilitiesGarbage Collection and Utilities is a library that offers a set of functions designed for efficient management of various types of arrays. This library provides garbage collection utilities to remove and delete excess elements, and also includes utilities for checking the size of arrays. It's particularly useful for developers who want to manage labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings efficiently within their scripts.
Both dump and trim act on the array backwards . This means that for trim , the elements that will be left start from 0. If you want the most recent element to be left after trim, you must use unshift().
Garbage Collection:
Functions to remove and delete excess elements from various types of arrays.
Useful for freeing up memory and keeping the arrays within desired size limits.
Size Checking:
Functions to check if arrays are larger than a specified size.
Helps in ensuring that arrays have enough elements before performing operations.
Supported Types:
Compatible with a wide range of array types, including labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
Usage:
The dump methods are ideal for clearing out unwanted elements from arrays, while the trim methods allow for more refined control over the size of arrays.
The ready methods enable you to verify if arrays have the required number of elements before proceeding with further operations.
Library "garbage_collection_and_utilities"
Provides garbage collection utilities for managing and trimming various types of arrays, and utilities to check if an array is of a specific size. Included types are: labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
method ready(self, size)
Checks if an array of labels is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of lines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of polylines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of boxes is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of linefills is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of chart points is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of floats is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of integers is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of booleans is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of strings is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
Bar ReplayThis indicator mirrors TradingView's bar replay feature to a certain extent, offering traders a streamlined way to analyze past market movements. It's a practical tool for strategy testing, pattern recognition, and refining trading approaches.
While it may have some limitations, it offers a practical solution for strategy testing and refining trading approaches for free and gets the job done. After all, having a tool is better than having none.
This is just an experiment so don't take it that seriously. I hope you guys find it useful.
If you have some ideas for improvement or found any bugs, kindly let me know.
How to use it?
Step 1 : Add the indicator to the chart.
Step 2 : Select the candle .
Step 3 : Make the changes visible.
Step 4 : How to Navigate
Step 5 : Change the date easily
The blank screen issue.
Note : There are some limitations
The data is limited to the free plan.
It's not smooth as the real Bar replay feature.
I haven't checked the bugs so let me know if you found any.
Range PercentageRange Percentage is a simple indicator utility to clearly display and dynamically alert on where a chosen series falls between two bounds, either series themselves or constant values.
To set up, select between series or value for upper and lower bounds. Only the chosen options will be used by the indicator, though you may enter the non-selected option. Configure the thresholds if you wish to use them for visual display or alerting. If you only care about the background color, disable both thresholds and the percentage line and move the indicator into the main pane.
Some sample use cases:
Coloring background on a zoomed-in chart to show to show price change relative to the entire value of an asset, not just the range selected on the y-axis
Get alerts which adjust dynamically as price approaches another series or dynamic value
Determine at a glance where a price falls between your identified support/resistance lines, no matter where you zoom or scroll
Compare relative gain of two assets
Identify trends of a price closing closer to low or high over time
This indicator is often most useful in conjunction with other indicators which produce a plotted series output and can save a lot of time thinking or interpreting. Its usefulness to a trader depends entirely on the rationale for choosing a lower/upper bound and sample series that are meaningful to that trader.
UtilsLibrary "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: . 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)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
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)
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: . 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: . 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.
CommonTypesMapUtilLibrary "CommonTypesMapUtil"
Common type Container library, for central usage across other reference libraries.
ArrayBool
Fields:
v (bool )
ArrayBox
Fields:
v (box )
ArrayPoint
Fields:
v (chart.point )
ArrayColor
Fields:
v (color )
ArrayFloat
Fields:
v (float )
ArrayInt
Fields:
v (int )
ArrayLabel
Fields:
v (label )
ArrayLine
Fields:
v (line )
ArrayLinefill
Fields:
v (linefill )
ArrayString
Fields:
v (string )
ArrayTable
Fields:
v (table )
MTF Fair Value Gap [BigBeluga]The MTF Fair Value Gap (FVG) indicator provides multi-timeframe options to observe lower or higher gaps in different timeframes within your current one. This can enhance the confluence in your trading decisions.
🔶 USAGE
An FVG is formed when a candle has an 'empty' body, leaving a gap. These areas are often filled before the market continues to trend in its original direction.
In practical terms, FVGs serve to highlight support areas (bullish FVGs) and resistance zones (bearish FVGs). As a gap is filled, signaling the end of the existing imbalance, it tends to foreshadow an impending price reversal.
While this approach is inherently contrarian, individuals seeking a more trend-following strategy can opt to use FVG identification as straightforward signals. This entails taking a long position upon detecting a bullish FVG and adopting a short position in the presence of a bearish FVG.
🔹 Mitigation
The mitigation point is where the user selects when the FVG is considered filled or no longer usable.
Source => Choose the candle's low/high or close as the mitigation point.
Point => Choose the FVG's mitigation point to trigger after the candle's Source has filled it. Users can choose between the middle point or the top/bottom of the FVG.
ccc
🔹 MTF
This script can display MTF FVGs from different timeframes while showing the current one. This is extremely useful as it avoids the need to switch timeframes frequently and can add significant confluence with the current FVG.
🔹 Threshold
The Threshold is an input to remove insignificant FVGs that are too small to be truly useful. Users can choose between:
Auto => Automatically remove unusable FVGs.
Manual => Set an automatic Threshold.
🔶 TIPS
Users can choose how many FVGs to display on the current chart for better visualization.
Users can choose which FVGs to display: only the current one, only MTF ones, or both.
JavaScript-style Debug ConsoleThis library provides a JavaScript-style debug console to Pine Coders. It supports the most commonly used utilities from the WHATWG Console Standard including the following:
• console.log
• console.debug
• console.info
• console.warn
• console.error
• console.assert
• console.count
• console.countReset
• console.group
• console.groupEnd
• console.clear
In addition to the WHATWG standard, this library also supports the following methods:
• console.show
• console.hide
FEATURES
• Follows the WHATWG Console Standard, which is widely adopted by all major JavaScript runtimes including browsers and Node.js.
• Provides an out-of-box UI with pre-configured theming, ensuring a clean and professional-looking console.
• Allows for easy UI customizations to fit your personal preferences.
• Has extremely simple import and initialization, making it easy to integrate with your existing codebase.
USAGE
1. Import this library:
import algotraderdev/Console/1
2. Initialize the console object:
var console = Console.new()
// You can also specify optional params to customize the look & feel.
var console = Console.new(
position = position.bottom_right,
max_rows = 50,
width = 0,
text_size = size.normal,
background_color = #000000CC,
timestamp_color = #AAAAAA,
info_message_color = #DDDDDD,
debug_message_color = #AAAAAA,
warn_message_color = #FFEB3B,
error_message_color = #ff3c00)
3. Use the console object to debug your code. Here are some examples:
// Basic logging
console.log('hello world!') // prints 'hello world'
console.warn('warn') // prints 'warn' in yellow
console.error('error') // prints 'error' in red
console.clear() // clears the console
// Assertion
console.assert(a.isEmpty(), 'array should be empty') // prints 'assertion failed: array should be empty' if the array is not empty
// Counter
console.count('fooFunction') // prints 'fooFunction: 1'
console.count('fooFunction') // prints 'fooFunction: 2'
console.countReset('fooFunction') // resets the counter
console.count('fooFunction') // prints 'fooFunction: 1'
// Group
console.log('A')
console.group()
console.log('B')
console.group()
console.log('C')
console.log('D')
console.groupEnd()
console.log('E')
console.groupEnd()
console.log('F')
// prints
// A
// B
// C
// D
// E
// F
// Hide and show
console.hide()
console.show()
[-_-] DictionaryThe script shows an example implementation of dictionary-like data type which can store key:value pairs (Python style). Both keys and values can have any of the following type:
• string
• integer
• float
• boolean
• color
You can add items of different types to the same dictionary (e.g. key = 12 and value = "value" stored in the same dictionary with key = "key" and value = 0.23).
Under the hood dictionary is a custom Object (see www.tradingview.com), that has two array fields (one for storing keys, another for storing values). Keys and values of different types are converted into a string representation when adding a new item to the dictionary. The value is then converted back to certain type (bool/color/etc.) from that string representation when being retrieved. Script also utilises the new Methods (see www.tradingview.com).
The following methods are implemented:
• init() -> initialises the array fields of dictionary (without this the script throws an error "Array methods can't be called when ID of array is na"
• set(key, value) -> add a new item to dictionary; if an item for given key already exists - change it to new value
• getS(key) -> get value of string type
• getI(key) -> get value of integer type
• getF(key) -> get value of float type
• getB(key) -> get value of boolean type
• getC(key) -> get value of color type
• remove(key) -> removes item from dictionary
• len() -> get length of dictionary (the number of keys)
I could not make just one "get" function that returns any type of value (color/string/etc.), so instead I created a get function for each value type. Example usage:
• you add a string item: dictionary.set(2, "string here")
• you add a float item: dictionary.set(3, 24.56)
• to retrieve first value (key=2) do this: dictionary.getS(2)
• to retrieve second value (key=3) do this: dictionary.getF(3)
FrizLabz_Time_Utility_MethodsLibrary "FrizLabz_Time_Utility_Methods"
Some time to index and index to time helper methods made them for another library thought I would try to make
them as methods
UTC_helper(utc)
UTC helper function this adds the + to the positive utc times, add "UTC" to the string
and can be used in the timezone arg of for format_time()
Parameters:
utc : (int) | +/- utc offset
Returns: string | string to be added to the timezone paramater for utc timezone usage
bar_time(bar_amount)
from a time to index
Parameters:
bar_amount : (int) | default - 1)
Returns: int bar_time
time_to_index(_time)
from time to bar_index
Parameters:
_time : (int)
Returns: int time_to_index | bar_index that corresponds to time provided
time_to_bars_back(_time)
from a time quanity to bar quanity for use with .
Parameters:
_time : (int)
Returns: int bars_back | yeilds the amount of bars from current bar to reach _time provided
bars_back_to_time(bars_back)
from bars_back to time
Parameters:
bars_back
Returns: int | using same logic as this will return the
time of the bar = to the bar that corresponds to bars_back
index_time(index)
bar_index to UNIX time
Parameters:
index : (int)
Returns: int time | time in unix that corrresponds to the bar_index
to_utc(time_or_index, timezone, format)
method to use with a time or bar_index variable that will detect if it is an index or unix time
and convert it to a printable string
Parameters:
time_or_index : (int) required) | time in unix or bar_index
timezone : (int) required) | utc offset to be appled to output
format : (string) | default - "yyyy-MM-dd'T'HH:mm:ssZ") | the format for the time, provided string is
default one from str.format_time()
Returns: string | time formatted string
GET(line)
Gets the location paramaters of a Line
Parameters:
line : (line)
Returns: tuple
GET(box)
Gets the location paramaters of a Box
Parameters:
box : (box)
Returns: tuple
GET(label)
Gets the location paramaters and text of a Label
Parameters:
label : (label)
Returns: tuple
GET(linefill)
Gets line 1 and 2 from a Linefill
Parameters:
linefill : (linefill)
Returns: tuple
Format(line, timezone)
converts Unix time in time or index params to formatted time
and returns a tuple of the params as string with the time/index params formatted
Parameters:
line : (line) | required
timezone : (int) | default - na
Returns: tuple
Line(x1, y1, x2, y2, extend, color, style, width)
similar to line.new() with the exception
of not needing to include y2 for a flat line, y1 defaults to close,
and it doesnt require xloc.bar_time or xloc.bar_index, if no x1
Parameters:
x1 : (int) default - time
y1 : (float) default - close
x2 : (int) default - last_bar_time/last_bar_index | not required for line that ends on current bar
y2 : (float) default - y1 | not required for flat line
extend : (string) default - extend.none | extend.left, extend.right, extend.both
color : (color) default - chart.fg_color
style : (string) default - line.style_solid | line.style_dotted, line.style_dashed,
line.style_arrow_both, line.style_arrow_left, line.style_arrow_right
width
Returns: line
Box(left, top, right, bottom, extend, border_color, bgcolor, text_color, border_width, border_style, txt, text_halign, text_valign, text_size, text_wrap)
similar to box.new() but only requires top and bottom to create box,
auto detects if it is bar_index or time used in the (left) arg. xloc.bar_time and xloc.bar_index are not used
args are ordered by purpose | position -> colors -> styling -> text options
Parameters:
left : (int) default - time
top : (float) required
right : (int) default - last_bar_time/last_bar_index | will default to current bar index or time
depending on (left) arg
bottom : (float) required
extend : (string) default - extend.none | extend.left, extend.right, extend.both
border_color : (color) default - chart.fg_color
bgcolor : (color) default - color.new(chart.fg_color,75)
text_color : (color) default - chart.bg_color
border_width : (int) default - 1
border_style : (string) default - line.style_solid | line.style_dotted, line.style_dashed,
txt : (string) default - ''
text_halign : (string) default - text.align_center | text.align_left, text.align_right
text_valign : (string) default - text.align_center | text.align_top, text.align_bottom
text_size : (string) default - size.normal | size.tiny, size.small, size.large, size.huge
text_wrap : (string) default - text.wrap_auto | text.wrap_none
Returns: box
Label(x, y, txt, yloc, color, textcolor, style, size, textalign, text_font_family, tooltip)
similar to label.new() but only requires no args to create label,
auto detects if it is bar_index or time used in the (x) arg. xloc.bar_time and xloc.bar_index are not used
args are ordered by purpose | position -> colors -> styling -> text options
Parameters:
x : (int) default - time
y : (float) default - high or low | depending on bar direction
txt : (string) default - ''
yloc : (string) default - yloc.price | yloc.price, yloc.abovebar, yloc.belowbar
color : (color) default - chart.fg_color
textcolor : (color) default - chart.bg_color
style : (string) default - label.style_label_down | label.style_none
label.style_xcross,label.style_cross,label.style_triangleup,label.style_triangledown
label.style_flag, label.style_circle, label.style_arrowup, label.style_arrowdown,
label.style_label_up, label.style_label_down, label.style_label_left, label.style_label_right,
label.style_label_lower_left, label.style_label_lower_right, label.style_label_upper_left,
label.style_label_upper_right, label.style_label_center, label.style_square,
label.style_diamond
size : (string) default - size.normal | size.tiny, size.small, size.large, size.huge
textalign : (string) default - text.align_center | text.align_left, text.align_right
text_font_family : (string) default - font.family_default | font.family_monospace
tooltip : (string) default - na
Returns: label
Grid Indicator - The Quant ScienceQuickly draw a 10-level grid on your chart with our open-source tool.
Our grid tool offers a unique solution to traders looking to maximize their profits in volatile market conditions. With its advanced features, you can create customized grids based on your preferred start price and line distance, allowing you to easily execute trades and capitalize on price movements. The tool works automatically, freeing up your time to focus on other important aspects of your trading strategy.
The benefits of using this tool are numerous. Firstly, it eliminates the need for manual calculation, making the analysis process much more efficient. Secondly, the automatic nature of the tool ensures that each grids are draw at precisely prices, giving you the best possible chance of maximizing your analysis. Finally, the ability to easily customize grids means that you can adapt your strategy quickly and effectively, even in rapidly changing market conditions.
So why wait? Take control of your trading and start using our innovative grid tool today! With its advanced features and ease of use, it's the perfect solution for traders of all levels looking to take their trading to the next level.
HOW TO USE
Using it is easy. Add the script to your chart and set the price and distance between the grids.
UtilitiesLibrary "Utilities"
My utility functions library.
toPips(_v)
Convert price to pips.
Parameters:
_v : Price
Returns: Pips
toPrice(_p)
Convert pips to price.
Parameters:
_p
Returns: Price
price_range(_a, _b)
The difference will be returned.
Parameters:
_a
_b : @return Price as positive number
get_day(_n, _lang)
Get the day of the week
Parameters:
_n : Number of day of week
_lang : en or ja
source(_name)
TODO: add function description here
Parameters:
_name
Returns: TODO: add what function returns
clear_lines(_arr, _min)
Deletes the lines included in the array.
Parameters:
_arr : Array of lines
_min : Deletes the lines included in the array.
clear_labels(_arr, _min)
Deletes the labels included in the array.
Parameters:
_arr : Array of labels
_min : Deletes the labels included in the array.
clear_boxes(_arr, _min)
Deletes the boxes included in the array.
Parameters:
_arr : Array of boxes
_min : Deletes the boxes included in the array.
HendrixLIBRARY - utilsLibrary "HendrixLIBRARY"
getVolumeData()
getLTF(customTimeframe, ltf)
Parameters:
customTimeframe
ltf
sumArray(a)
Parameters:
a
arrs2vals(upVolumeArray, downVolumeArray, volArr)
Parameters:
upVolumeArray
downVolumeArray
volArr
getVolumesFromUpDownArrays(upVolumeArray, downVolumeArray)
Parameters:
upVolumeArray
downVolumeArray
getDeltaFromVolumes(upVolume, downVolume)
Parameters:
upVolume
downVolume
getDeltaFromUpDownArrays(upVolumeArray, downVolumeArray)
Parameters:
upVolumeArray
downVolumeArray
getUpColor()
getDownColor()
getBlackColor()
getColors()
printTableTR(txt)
Parameters:
txt
printTableBR(txt)
Parameters:
txt
printTableMR(txt)
Parameters:
txt
print(txt, lbl)
Parameters:
txt
lbl
printSyminfo(sym)
Parameters:
sym
Pair ViewerPair-Trading is a recognized and widely used trading method, this indicator is a tool that allows via several display interfaces (2 at the moment) to see relative performance ratios of two assets.
The inputs are pretty simple to understand but here is the list of them :
- Ticker #1 : The first Asset's ticker // numerator of the ratio
- Ticker #2 : The second Asset's ticker // denominator of the ratio
- View as : Display Method
- Up Color : Color of positive candle (when close > open)
- Down Color : Color of negative candle (when close < open)
Of course, this indicator only shows stuff at the chart, it does NOT provide any investment advice.
conditionLibrary "condition"
True/False Condition tools and toggles for booleans and utility.
suggested use is checking if a calculation is required, or can be skipped
speeding up script calculations in realtime and historical scenarios.
isonlywihtout(_first_cond, _second_cond)
output is true only if first true and second false
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isonlywih(_first_cond, _second_cond)
output is true only for the first condition if the second condition is also true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isactive(_cond)
output is true active only while actively true
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotactive(_cond)
output is true only while condition is not active
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isontoggle(_cond)
output is true and holds on True activation , na input has no effect, only a false will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isofftoggle(_cond)
output is true and holds on False activation, na input has no effect, only a true will disengage
Parameters:
_cond : (bool) Condition met
Returns: True if coditions met
isnotboth(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isneither(_first_cond, _second_cond)
output is false only if both are active, either or neither pass true
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
isbothtoggled(_first_cond, _second_cond)
output is true and held when both trigger true, and only disengages if both are false at once
Parameters:
_first_cond : (bool) First Condition
_second_cond : (bool) Second Condition
Returns: True if coditions met
UtilitiesLibrary "Utilities"
General utilities
print_series(s, skip_na, position, show_index, from_index, to_index)
Print series values
Parameters:
s : Series (string)
skip_na : Flag to skip na values (optional bool, dft = false)
position : Position to print the Table (optional string, dft = position.bottom_center)
show_index : Flag to show series indices (optional bool, dft = true)
from_index : First index to print (optional int, dft = 0)
to_index : Last index to print (optional int, dft = last_bar_index)
Returns: Table object, if series was printed
print(v, position, at_index)
Print value
Parameters:
v : Value (string)
position : Position to print the Table (optional string, dft = position.bottom_center)
at_index : Index at which to print (optional int, dft = last_bar_index)
Returns: Table object, if value was printed
calcLibrary "calc"
Library for math functions. will expand over time.
split(_sumTotal, _divideBy, _forceMinimum, _haltOnError)
Split a large number into integer sized chunks
Parameters:
_sumTotal : (int) Total numbert of items
_divideBy : (int) Groups to make
_forceMinimum : (bool) force minimum number 1/group
_haltOnError : (bool) force error if too few groups
Returns: int array of items per group
external_input_utilsLibrary "external_input_utils"
Collection of external input utilities for conversion and other hacky functions
str_to_src(value) str_to_src - Convert the string value to the coresponding source series. It can be used to limit the "input.source" choices provided to the end user.
The most interesting part is that it can be used to overcome the "one input.source call limitation" for external inputs to your script
Parameters:
value : - The string equivalent to the source to be converted
Returns: series of the coresponding source
eval_cond(input, operator, value, defval) eval_cond - Evaluate the condition given an operator
Parameters:
input : - The input to be compared with. It can be an external input or a regular one
operator : - The string operator that describe the coparison operation
value : - The value to compare with the input. This can be a serries or a constant
defval : - The boolean value to return when 'noop' is selected
Returns: series of bool the result of the operation evaluation
[TEMPLATE] Code Block Comments█ OVERVIEW
Here I present to the community at large a collection of code comment blocks that I think will be useful, especially for larger script projects bordering on 2,000 lines or above of code.
█ PLANNED FUTURE UPDATES
Work with the community to expand this template to be even more useful with the inclusion of useful global colour sets, variables, tooltips, groups, etc.
better script thumbnail.
full-screen table or label outlining the script's use-cases.
utilsLibrary "utils"
ma_smooth(alg, src, len) Calculates various moving averages
Parameters:
alg : Smoothing algorithm to use
src : Source data
len : Length of moving average