The Z-score The Z-score, also known as the standard score, is a statistical measurement that describes a value's relationship to the mean of a group of values. It's measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
The concept of Z-score was introduced by statistician Carl Friedrich Gauss as part of his "method of the least squares," which was an important step in the development of the normal distribution and Z-score tables. It's a key concept in statistics and is used in various statistical tests.
In financial analysis, Z-scores are used to determine whether a data point is usual or unusual. You can think of it as a measure of how many standard deviations an element is from the mean. For instance, a Z-score of 1.0 would denote a value that is one standard deviation from the mean. Z-scores are also used to predict probabilities, with Z-scores having a distribution that is expected to be normal.
In trading, a Z-score is used to determine how often a trading system may produce a string of winners or losers. It can help a trader to understand whether the losses or profits they see are something that the system would most likely produce, or if it's a once in a blue moon situation. This helps traders make decisions about when to start or stop a system.
I just wanted to play a bit with the Z-score I guess.
Feel free to share your findings if you discover additional applications for this strategy or identify timeframes where it appears to perform more optimally.
How it works:
This strategy is based on a statistical concept called Z-score, which measures the number of standard deviations a data point is from the mean. In other words, it helps determine how unusual or usual a data point is.
In the context of this strategy, Z-score is applied to a 10-period EMA (Exponential Moving Average) of Heikin-Ashi candlestick close prices. The Z-score is calculated over a look-back period of 25 bars.
The EMA of the Z-score is then calculated over a 20-bar period, and the upper and lower thresholds (bounds for buy and sell signals) are defined using the 90th and 10th percentiles of this EMA score.
Long positions are taken when the Z-score crosses above the lower threshold or crosses above the mid-line (50th percentile). An additional long entry is made when the Z-score crosses above the highest value the EMA has been in the past 100 periods.
Short positions are initiated when the EMA crosses below the upper threshold, lower threshold or the highest value the EMA has been in the past 100 periods.
Positions are closed when opposing entry conditions are met, for example, a long position is closed when the short entry condition is true, and vice versa.
Set your desired start date for the strategy. This can be modified in the timestamp("YYYY MM DD") function at the top of the script.
Functions
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
Vector ScalerVector Scaler is like Stochastic but it uses a different method to scale the input. The method is very similar to vector normalization but instead of keeping the "vector" we just sum the three points and average them. The blue line is the signal line and the orange line is the smoothed signal line. I have added the "J" line from the KDJ indicator to help spot divergences. Differential mode uses the delta of the input for the calculations. Here are some pictures to help illustrate how this works relative to other popular indicators.
Vector Scaler vs Stochastic
Vector Scaler vs Smooth Stochastic RSI
average set to 100
average set to 200
FUNCTION: Limited Historical Data WorkaroundFUNCTION: Limited Historical Data Workaround
If you are working with bitcoin weekly charts, or any other ticker with a low amount of price history this function may help you out. For example you want to apply indicators to some shitcoin that just launched? This can help you.
It can be frustrating to use certain built-ins since they will only give an output once the full lookback length is available. This function allows you to avoid that situation and start plotting things with almost no history whatsoever!
In this example code we do it by utilizing a replacement for the built in pine SMA function. This function allows us to pass a series instead of just a simple int to the length variable of the SMA. This can be achieved with all the pine built ins and I believe @pinecoders has a publication already detailing many of them with full coded examples.
Then we replace the length of the SMA with the custom history function. It checks to see if the current bar index is less than the length of the function. Then if it is, it changes the length to the bar index allowing us to get plots and series earlier than otherwise possible.
Pinescript - Common Label & Line Array Functions Library by RRBPinescript - Common Label & Line Array Functions Library by RagingRocketBull 2021
Version 1.0
This script provides a library of common array functions for arrays of label and line objects with live testing of all functions.
Using this library you can easily create, update, delete, join label/line object arrays, and get/set properties of individual label/line object array items.
You can find the full list of supported label/line array functions below.
There are several libraries:
- Common String Functions Library
- Standard Array Functions Library
- Common Fixed Type Array Functions Library
- Common Label & Line Array Functions Library
- Common Variable Type Array Functions Library
Features:
- 30 array functions in categories create/update/delete/join/get/set with support for both label/line objects (45+ including all implementations)
- Create, Update label/line object arrays from list/array params
- GET/SET properties of individual label/line array items by index
- Join label/line objects/arrays into a single string for output
- Supports User Input of x,y coords of 5 different types: abs/rel/rel%/inc/inc% list/array, auto transforms x,y input into list/array based on type, base and xloc, translates rel into abs bar indexes
- Supports User Input of lists with shortened names of string properties, auto expands all standard string properties to their full names for use in functions
- Live Output for all/selected functions based on User Input. Test any function for possible errors you may encounter before using in script.
- Output filters: hide all excluded and show only allowed functions using a list of function names
- Output Panel customization options: set custom style, color, text size, and line spacing
Usage:
- select create function - create label/line arrays from lists or arrays (optional). Doesn't affect the update functions. The only change in output should be function name regardless of the selected implementation.
- specify num_objects for both label/line arrays (default is 7)
- specify common anchor point settings x,y base/type for both label/line arrays and GET/SET items in Common Settings
- fill lists with items to use as inputs for create label/line array functions in Create Label/Line Arrays section
- specify label/line array item index and properties to SET in corresponding sections
- select label/line SET function to see the changes applied live
Code Structure:
- translate x,y depending on x,y type, base and xloc as specified in UI (required for all functions)
- expand all shortened standard property names to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- create param arrays from string lists (required for create/update* from arrays and set* functions, not needed for create/update* from lists)
- create label/line array from string lists (property names are auto expanded) or param arrays (requires already expanded properties)
- update entire label/line array or
- get/set label/line array item properties by index
Transforming/Expanding Input values:
- for this script to work on any chart regardless of price/scale, all x*,y* are specified as % increase relative to x0,y0 base levels by default, but user can enter abs x,price values specific for that chart if necessary.
- all lists can be empty, contain 1 or several items, have the same/different lengths. Array Length = min(min(len(list*)), mum_objects) is used to create label/line objects. Missing list items are replaced with default property values.
- when a list contains only 1 item it is duplicated (label name/tooltip is also auto incremented) to match the calculated Array Length
- since this script processes user input, all x,y values must be translated to abs bar indexes before passing them to functions. Your script may provide all data internally and doesn't require this step.
- at first int x, float y arrays are created from user string lists, transformed as described below and returned as x,y arrays.
- translated x,y arrays can then be passed to create from arrays function or can be converted back to x,y string lists for the create from lists function if necessary.
- all translation logic is separated from create/update/set functions for the following reasons:
- to avoid redundant code/dependency on ext functions/reduce local scopes and to be able to translate everything only once in one place - should be faster
- to simplify internal logic of all functions
- because your script may provide all data internally without user input and won't need the translation step
- there are 5 types available for both x,y: abs, rel, rel%, inc, inc%. In addition to that, x can be: bar index or time, y is always price.
- abs - absolute bar index/time from start bar0 (x) or price (y) from 0, is >= 0
- rel - relative bar index/time from cur bar n (x) or price from y0 base level, is >= 0
- rel% - relative % increase of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc - relative increment (step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc% - relative % increment (% step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- x base level >= 0
- y base level can be 0 (empty) or open, close, high, low of cur bar
- single item x1_list = "50" translates into:
- for x type abs: "50, 50, 50 ..." num_objects times regardless of xloc => x = 50
- for x type rel: "50, 50, 50 ... " num_objects times => x = x_base + 50
- for x type rel%: "50%, 50%, 50% ... " num_objects times => x_base * (1 + 0.5)
- for x type inc: "0, 50, 100 ... " num_objects times => x_base + 50 * i
- for x type inc%: "0%, 50%, 100% ... " num_objects times => x_base * (1 + 0.5 * i)
- when xloc = xloc.bar_index each rel*/inc* value in the above list is then subtracted from n: n - x to convert rel to abs bar index, values of abs type are not affected
- x1_list = "0, 50, 100, ..." of type rel is the same as "50" of type inc
- x1_list = "50, 50, 50, ..." of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "50"
- single item y1_list = "2" translates into (ragardless of yloc):
- for y type abs: "2, 2, 2 ..." num_objects times => y = 2
- for y type rel: "2, 2, 2 ... " num_objects times => y = y_base + 2
- for y type rel%: "2%, 2%, 2% ... " num_objects times => y = y_base * (1 + 0.02)
- for y type inc: "0, 2, 4 ... " num_objects times => y = y_base + 2 * i
- for y type inc%: "0%, 2%, 4% ... " num_objects times => y = y_base * (1 + 0.02 * i)
- when yloc != yloc.price all calculated values above are simply ignored
- y1_list = "0, 2, 4" of type rel% is the same as "2" with type inc%
- y1_list = "2, 2, 2" of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "2"
- you can enter shortened property names in lists. To lookup supported shortened names use corresponding dropdowns in Set Label/Line Array Item Properties sections
- all shortened standard property names must be expanded to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- examples of shortened property names that can be used in lists: bar_index, large, solid, label_right, white, left, left, price
- expanded to their corresponding full names: xloc.bar_index, size.large, line.style_solid, label.style_label_right, color.white, text.align_left, extend.left, yloc.price
- all expanding logic is separated from create/update* from arrays and set* functions for the same reasons as above, and because param arrays already have different types, implying the use of final values.
- all expanding logic is included in the create/update* from lists functions because it seemed more natural to process string lists from user input directly inside the function, since they are already strings.
Creating Label/Line Objects:
- use study max_lines_count and max_labels_count params to increase the max number of label/line objects to 500 (+3) if necessary. Default number of label/line objects is 50 (+3)
- all functions use standard param sequence from methods in reference, except style always comes before colors.
- standard label/line.get* functions only return a few properties, you can't read style, color, width etc.
- label.new(na, na, "") will still create a label with x = n-301, y = NaN, text = "" because max default scope for a var is 300 bars back.
- there are 2 types of color na, label color requires color(na) instead of color_na to prevent error. text_color and line_color can be color_na
- for line to be visible both x1, x2 ends must be visible on screen, also when y1 == y2 => abs(x1 - x2) >= 2 bars => line is visible
- xloc.bar_index line uses abs x1, x2 indexes and can only be within 0 and n ends, where n <= 5000 bars (free accounts) or 10000 bars (paid accounts) limit, can't be plotted into the future
- xloc.bar_time line uses abs x1, x2 times, can't go past bar0 time but can continue past cur bar time into the future, doesn't have a length limit in bars.
- xloc.bar_time line with length = exact number of bars can be plotted only within bar0 and cur bar, can't be plotted into the future reliably because of future gaps due to sessions on some charts
- xloc.bar_index line can't be created on bar 0 with fixed length value because there's only 1 bar of horiz length
- it can be created on cur bar using fixed length x < n <= 5000 or
- created on bar0 using na and then assigned final x* values on cur bar using set_x*
- created on bar0 using n - fixed_length x and then updated on cur bar using set_x*, where n <= 5000
- default orientation of lines (for style_arrow* and extend) is from left to right (from bar 50 to bar 0), it reverses when x1 and x2 are swapped
- price is a function, not a line object property
Variable Type Arrays:
- you can't create an if/function that returns var type value/array - compiler uses strict types and doesn't allow that
- however you can assign array of any type to another array of any type creating an arr pointer of invalid type that must be reassigned to a matching array type before used in any expression to prevent error
- create_any_array2 uses this loophole to return an int_arr pointer of a var type array
- this works for all array types defined with/without var keyword and doesn't work for string arrays defined with var keyword for some reason
- you can't do this with var type vars, only var type arrays because arrays are pointers passed by reference, while vars are actual values passed by value.
- you can only pass a var type value/array param to a function if all functions inside support every type - otherwise error
- alternatively values of every type must be passed simultaneously and processed separately by corresponding if branches/functions supporting these particular types returning a common single type result
- get_var_types solves this problem by generating a list of dummy values of every possible type including the source type, tricking the compiler into allowing a single valid branch to execute without error, while ignoring all dummy results
Notes:
- uses Pinescript v3 Compatibility Framework
- uses Common String Functions Library, Common Fixed Type Array Functions Library, Common Variable Type Array Functions Library
- has to be a separate script to reduce the number of local scopes/compiled file size, can't be merged with another library.
- lets you live test all label/line array functions for errors. If you see an error - change params in UI
- if you see "Loop too long" error - hide/unhide or reattach the script
- if you see "Chart references too many candles" error - change x type or value between abs/rel*. This can happen on charts with 5000+ bars when a rel bar index x is passed to label.new or line.new instead of abs bar index n - x
- create/update_label/line_array* use string lists, while create/update_label/line_array_from_arrays* use array params to create label/line arrays. "from_lists" is dropped to shorten the names of the most commonly used functions.
- create_label/line_array2,4 are preferable, 5,6 are listed for pure demonstration purposes only - don't use them, they don't improve anything but dramatically increase local scopes/compiled file size
- for this reason you would mainly be using create/update_label/line_array2,4 for list params or create/update_label/line_array_from_arrays2 for array params
- all update functions are executed after each create as proof of work and can be disabled. Only create functions are required. Use update functions when necessary - when list/array params are changed by your script.
- both lists and array item properties use the same x,y_type, x,y_base from common settings
- doesn't use pagination, a single str contains all output
- why is this so complicated? What are all these functions for?
- this script merges standard label/line object methods with standard array functions to create a powerful set of label/line object array functions to simplify manipulation of these arrays.
- this library also extends the functionality of Common Variable Type Array Functions Library providing support for label/line types in var type array functions (any_to_str6, join_any_array5)
- creating arrays from either lists or arrays adds a level of flexibility that comes with complexity. It's very likely that in your script you'd have to deal with both string lists as input, and arrays internally, once everything is converted.
- processing user input, allowing customization and targeting for any chart adds a whole new layer of complexity, all inputs must be translated and expanded before used in functions.
- different function implementations can increase/reduce local scopes and compiled file size. Select a version that best suits your needs. Creating complex scripts often requires rewriting your code multiple times to fit the limits, every line matters.
P.S. Don't rely too much on labels, for too often they are fables.
List of functions*:
* - functions from other libraries are not listed
1. Join Functions
Labels
- join_label_object(label_, d1, d2)
- join_label_array(arr, d1, d2)
- join_label_array2(arr, d1, d2, d3)
Lines
- join_line_object(line_, d1, d2)
- join_line_array(arr, d1, d2)
- join_line_array2(arr, d1, d2, d3)
Any Type
- any_to_str6(arr, index, type)
- join_any_array4(arr, d1, d2, type)
- join_any_array5(arr, d, type)
2. GET/SET Functions
Labels
- label_array_get_text(arr, index)
- label_array_get_xy(arr, index)
- label_array_get_fields(arr, index)
- label_array_set_text(arr, index, str)
- label_array_set_xy(arr, index, x, y)
- label_array_set_fields(arr, index, x, y, str)
- label_array_set_all_fields(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
- label_array_set_all_fields2(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
Lines
- line_array_get_price(arr, index, bar)
- line_array_get_xy(arr, index)
- line_array_get_fields(arr, index)
- line_array_set_text(arr, index, width)
- line_array_set_xy(arr, index, x1, y1, x2, y2)
- line_array_set_fields(arr, index, x1, y1, x2, y2, width)
- line_array_set_all_fields(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
- line_array_set_all_fields2(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
3. Create/Update/Delete Functions
Labels
- delete_label_array(label_arr)
- create_label_array(list1, list2, list3, list4, list5, d)
- create_label_array2(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array3(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array4(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array5(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array6(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array2(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array4(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array_from_arrays2(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- create_label_array_from_arrays4(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- update_label_array_from_arrays2(label_arr, x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
Lines
- delete_line_array(line_arr)
- create_line_array(list1, list2, list3, list4, list5, list6, d)
- create_line_array2(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array3(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array4(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array5(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array6(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array2(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array4(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array_from_arrays2(x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
- update_line_array_from_arrays2(line_arr, x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
Function Square WaveThis is a script to draw a square wave on the chart, with an indicator for current price.
Markets undergoing Dow Jones or Wyckoff Accumulation/Distribution cycles tend to move in such waves, and if the period of the cycles are detected, a signal for accumulation/distribution phases can be created as an early warning.
Useful inputs:
- Average True Range as the wave height.
- Assumed Wave period as the wave duration.
I divided the current price wave by 2 to make the indicator more visually friendly.
GLHF
- DPT
Function Sawtooth WaveThis is an indicator to draw a sawtooth wave on the chart.
It can be a useful perspective, as decaying markets tend to oscillate in reverse sawtooth waves, and bullish markets can oscillate in conventional sawtooth waves. With the right inputs, it can be an early warning signal for potential movements.
Something I've noted is that large waves cause a ripple effect and sets the frequency for the market until a change occurs. Sawtooth waves may help in capturing ripple waves.
Useful inputs are:
- Average True Range as wave height (amplitude)
- Periodicity of market as wave duration (frequency)
(Inputs will change the wave from conventional to reverse)
I hope that it is helpful.
GLHF
- DPT
Pinescript - Standard Array Functions Library by RRBStandard Array Functions Library by RagingRocketBull 2021
Version 1.0
This script provides a library of every standard Pinescript array function for live testing with all supported array types.
You can find the full list of supported standard array functions below.
There are several libraries:
- Common String Functions Library
- Common Array Functions Library
- Standard Array Functions Library
Features:
- Supports all standard array functions (30+) with all possible array types* (* - except array.new* functions and label, line array types)
- Live Output for all/selected functions based on User Input. Test any function for possible errors you may encounter before using in script.
- Output filters: show errors, hide all excluded and show only allowed functions using a list of function names
- Console customization options: set custom text size, color, page length, line spacing
Notes:
- uses Pinescript v3 Compatibility Framework
- uses Common String Functions Library
- has to be a separate script to reduce the number of local scopes in Common Array Function Library, there's no way to merge these scripts into a single library.
- lets you live test all standard array functions for errors. If you see an error - change params in UI
- array types that are not supported by certain functions and producing a compilation error were disabled with "error" showing up as result
- if you see "Loop too long" error - hide/unhide or reattach the script
- doesn't use pagination, a single str contains all output
- for most array functions to work (except push), an array must be defined with at least 1 pre-existing dummy element 0.
- array.slice and array.fill require from_index < to_index otherwise error
- array.join only supports string arrays, and delimiter must be a const string, can't be var/input. Use join_any_array to join any array type into string. You can also use tostring() to join int, float arrays.
- array.sort only supports int, float arrays. Use sort_any_array from the Common Array Function Library to sort any array type.
- array.sort only sorts values, doesn't preserve indexes. Use sort_any_array from the Common Array Function Library to sort any array while preserving indexes.
- array.concat appends string arrays in reverse order, other array types are appended correctly
- array.covariance requires 2 int, float arrays of the same size
- tostring(flag) works only for internal bool vars, flag expression can't depend on any inputs of any type, use bool_to_str instead
- you can't create an if/function that returns var type value/array - compiler uses strict types and doesn't allow that
- however you can assign array of any type to another array of any type creating an arr pointer of invalid type that must be reassigned to a matching array type before used in any expression to prevent error
- source_array and create_any_array2 use this loophole to return an int_arr pointer of a var type array
- this works for all array types defined with/without var keyword. This doesn't work for string arrays defined with var keyword for some reason
- you can't do this with var type vars, this can be done only with var type arrays because they are pointers passed by reference, while vars are the actual values passed by value.
- wrapper functions solve the problem of returning var array types. This is the only way of doing it when the top level arr type is undefined.
- you can only pass a var type value/array param to a function if all functions inside support every type - otherwise error
- alternatively values of every type must be passed simultaneously and processed separately by corresponding if branches/functions supporting these particular types returning a common single result type
- get_var_types solves this problem by generating a list of dummy values of every possible type including the source type, allowing a single valid branch to execute without error
- examples of functions supporting all array types: array.size, array.get, array.push. Examples of functions with limited type support: array.sort, array.join, array.max, tostring
- unlike var params/global vars, you can modify array params and global arrays directly from inside functions using standard array functions, but you can't use := (it only works for local arrays)
- inside function always work with array.copy to prevent accidental array modification
- you can't compare arrays
- there's no na equivalent for arrays, na(arr) doesn't work
P.S. A wide array of skills calls for an even wider array of responsibilities
List of functions:
- array.avg(arr)
- array.clear(arr)
- array.concat(arr1, arr2)
- array.copy(arr)
- array.covariance(arr1, arr2)
- array.fill(arr, value, index_from, index_to)
- array.get(arr, index)
- array.includes(arr, value)
- array.indexof(arr, value)
- array.insert(arr, index, value)
- array.join(arr, delimiter)
- array.lastindexof(arr, value)
- array.max(arr)
- array.median(arr)
- array.min(arr)
- array.mode(arr)
- array.pop(arr)
- array.push(arr, value)
- array.range(arr)
- array.remove(arr, index)
- array.reverse(arr)
- array.set(arr, index, value)
- array.shift(arr)
- array.size(arr)
- array.slice(arr, index_from, index_to)
- array.sort(arr, order)
- array.standardize()
- array.stdev(arr)
- array.sum(arr)
- array.unshift(arr, value)
- array.variance(arr)
Pinescript - Common String Functions Library by RRBCommon String Functions Library by RagingRocketBull 2021
Version 1.0
Pinescript now has strong support for arrays with many powerful functions, but still lacks built-in string functions. Luckily you can easily process and manipulate strings using arrays.
This script provides a library of common string functions for everyday use, such as: indexOf, substr, replace, ascii_code, str_to_int etc. There are 100+ unique functions (130 including all implementations)
It should serve as building blocks to speed up the development of your custom scripts. You should also be able to learn how Pinescript arrays works and how you can process strings.
Similar libraries for Array and Statistical Functions are in the works. You can find the full list of functions below.
Features:
- 100+ unique string functions (130 including all implementations) in categories: lookup, testing, conversion, modification, extraction, type conversion, date and time, console output
- Live Output for all/selected functions based on User Input. Test any function before using in script.
- Live Unit Test Output for several functions based on pre-defined inputs.
- Output filters: show unique functions/all implementations, grouping
- Console customization options: set custom text size, color, page length
- Support for Pages - auto splits output into pages with fixed length, use pages in your scripts
- Several easy to use console output functions to speed up debugging/output.
WARNING:
- Compilation Time: 1 min
Notes:
- uses Pinescript v3 Compatibility Framework
- this script is packed to the max and sets a new record in testing of Pinescript's limits: 500 local scopes, 4000+ lines, 180kb+ source size. It's not possible to add more ifs/fors/functions without reducing functionality
- to fit the max limit of local scopes = 500 all ifs were replaced with ?: where possible, the number of function calls was reduced, some calls replaced with inline function code
- ifs are faster (especially when lots of them are used in a for cycle), more readable, but ifs/fors/functions increase local scopes (+1) and compiled file size, have max nesting limit = 10.
- ?: are slower (especially in for cycles), hard to read when nested, don't affect local scopes, reduce compiled file size, can't contain plots, for statements (break/continue) and sets of statements
- for most array functions to work (except push), an array must be defined with at least 1 pre-existing dummy element 0.
- if you see "String too long" error - enable Show Pages, reduce Max Chars Per Page < Max String Length limit = 4096.
- if you see "Loop too long" error - hide/unhide or reattach the script
- some functions have several implementations that can be faster/slower, use internal code/ext functions
- 1 is manual string processing using for cycles (array.get) and ext functions - provided in case you want to implement your own logic, may sometimes be slower
- 2 is a 2nd alternate implementation mostly done using built-in functions (array.indexof, array.slice, array.insert, array.remove, str.replace_all),
attempts to minimize local scopes and dependency on ext functions, should generally be faster
- 3 is a 3rd alternate (array.includes, array.fill) or a more advanced implementation (datetime3_str) with lots of params, giving you the most control over output
- most functions have dependencies, such as const names, global arrays, inputs, other functions.
P.S. Strings of Time may be closed unto themselves or have loose ends; they can vibrate, stretch, join or split.
Function Groups:
1. Char Functions
- repeat(str, num)
- ascii_char(code)
- ascii_code(char)
- is_digit(char)
- is_letter(char)
- digit_to_int(char)
- is_space_char(char)
2. Char Test and Lookup Functions
- char_at(str, pos)
- char_code_at(str, pos)
- indexOf_char(str, char)
- lastIndexOf_char(str, char)
- nth_indexOf_char(str, char, num)
- includes_char(str, char)
3. String Lookup Functions
- indexOf(str, target)
- lastIndexOf(str, target)
- nth_indexOf(str, target, num)
- indexesOf(str, target)
- numIndexesOf(str, target)
4. String Conversion Functions
- lowercase(str)
- uppercase(str)
5. String Modification and Extraction Functions
- split(str, separator)
- insert(str, pos, new_str)
- remove(str, pos, length)
- insert_char(str, pos, char)
- remove_char(str, pos)
- reverse(str)
- fill_char(str, char, start_pos, end_pos)
- replace(str, target, new_str)
- replace_first(str, target, new_str)
- replace_last(str, target, new_str)
- replace_nth(str, target, new_str, num)
- replace_left(str, new_str)
- replace_right(str, new_str)
- replace_middle(str, pos, new_str)
- left(str, num)
- right(str, num)
- first_char(str)
- last_char(str)
- truncate(str, max_len)
- truncate_middle2(str, trunc_str, pos, max_len)
- truncate_from2(str, trunc_str, pos, max_len, side)
- concat(str1, str2, trunc_str, max_len, mode)
- concat_from(str1, str2, trunc_str, max_len, side, mode)
- trim(str)
- substr(str, pos, length)
- substring(str, start_pos, end_pos)
- strip(str, mask, target, is_allowed)
- extract_groups(str)
- extract_numbers(str, d1, d2, mode)
- str_to_float(str, d1, d2)
- str_to_int(str)
- extract_ranges(str, d1, d2, d3, type)
6. String Test Functions
- includes(str, target)
- starts_with(str, target)
- ends_with(str, target)
- str_compare(str1, str2)
7. Type Conversion Functions
- tf_check2(tf)
- tf_to_mins()
- convert_tf(tf)
- period_to_mins(tf)
- convert_tf2(tf)
- convert_tf3(tf)
- bool_to_str(flag)
- get_src(src_str)
- get_size(size_str)
- get_style(style)
- get_bool(bool_str)
- get_int(str)
- get_float(str, d1, d2)
- get_color(str, def_color)
- color_tr2(col_str, transp)
- get_month(str)
- month_name(num, format)
- weekday_name(num, format)
- dayofweek_name(t)
8. Date and Time Functions
- date_str(t, d)
- time_str(t, d)
- datetime_str(t, d1, d2)
- date2_str(t, d, type)
- time2_str(t, d, type)
- datetime2_str(t, d1, d2, format1, format2)
- date3_str(t, template)
- time3_str(t, template)
- datetime3_str(t, template)
9. Console Output & Helper Functions
- echo1(con, str)
- echo2(x, y, con, str)
- echo3(v_shift, con, str, msg_color, text_size)
- echo4(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo5(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo6(x, y, con, str)
- echo7(v_shift, con, str, msg_color, text_size)
- echo8(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- echo9(x, y, con, str, msg_style, msg_color, text_size, text_align, msg_xloc)
- new_page(str, line_str, trunc_str, header_str, footer_str, length, page_count, page, mode)
New Alerts Allow for Dynamic Messageswww.tradingview.com
Following the last example from the link above, I added a function return to plot the calculated RSI value for each ticker.
For this, I added the expression of the rsi bult-in function in the security call, to send as a return to the plot function.
Ps. I purposely inverted the crossunder/crossover calls for testing here.
FUNCTION: Specify lengths in time (or bars) This is a function to give measures in time rather than bars...
I often want to measure in things in time rather than bars and change the sample rate (the candle size)
without reconfiguring my settings. This is a handy function for setting you input lengths in time units
(or bars when you want that)
For example
I want a 3 hour moving average, regardless of whether I have 5 minute candles or 30 min candles...
I want a 200 day moving average, regardless of whether I have 1 day or 1 week candles...
This is designed for you to put in your own scripts for your own purpose, but you can use this as is for time constant moving averages
or as an indicator on an indicator.
This shows the same moving averages 45 min / 3 hours in aqua / fuchsia and 1 day / 1 week in red / green
First row: On an extended session chart with 10m, 30m and 60m candles (all of them use the same settings (day length is 16 hours) everything else default.
Second row: On a standard session chart with 10m, 30m and 60m candles (all of them use the same settings everything else default.
Dumb Indicator 21 - Function's Candlestick Bar's StyleThe idea is help traders to see the patterns and levels from a different point o view.
This script create candlestick using the opening, high, low and close price as source on your favorite function.
It's very simple to use:
Select a function in the drop box list, the number of bars length, check or uncheck the boxes to treat source as logarithm, smooth, and if you want to plot the SMA from the results.
To make a deeper analysis, you can select to plot the candles in Stochastic or in Percent Rank way.
The Stochastic and Percent Rank plot will show how far the price is close to highest or lowest value of the source from the last "Stochastic Length" number of bars.
Some functions with different names can plot the same results.
This indicator works on every kind of market, but you will need to find the best function and length to use.
Please, if you find anything good with this, share to everyone.
Real Candles Heikin Ashi (HA) Candle functionsThis script plots both real and HA candles regardless or which are used on the chart in TV settings.
(and has the functions for you to use.)
Lots of people seem to misunderstand backtesting (or scam people) based on HA candles.
Backtesting with HA candles leads to impossible trades. ALWAYS backtest with real candles.
That doesn't mean you might not want to look at HA candle values to make trading decisions.
Add the code below to calculate HA candles from real and use that in your HA trading algo,
but test it on real charts.
[e2] Color Gradient Function20 step red/green gradient function
The color gradient function allow colorize any source in 5% steps.
Define the source, minimum and maximum value (constant or , for example, bb (or any other channel)).