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)
Function
Function - Custom SwitchMethod to do a custom switch that can handle int/float/bool/string type conditions using arrays.
Examples of Rolling Average Using Automated AnchoringIn this study, I present a method to expose NaN values to development environment.
This exposure allows NaN values to be used by methods in scripts.
I also show how to use values, even NaN values, as anchors from which statistics can be computed from.
I demonstrate how to do this with constants and variables in methods for computing the cumulative/rolling average of a series.
I also show how to calculate the cumulative/rolling average from the start of a ticker series using the aforementioned methods.
Each method has a description on how some of their parts work as well as their constraints.
Method #1 - Can only be used for computing the rolling average on the ticker series.
Method #2 - The simple moving average from the Pine Script reference.
- Can be used to calculate the rolling average of the ticker series and number values of a series.
- This method seems to cause an error when there are many bars in the series.
Method #3 - The most versatile method due to the use of computing the rolling average using an array.
- Timeout will occur when computing the rolling average of an entire ticker series which is long.
- Timeout has not occurred when computing a rolling average of a series from NaN or non-NaN anchor points even when the series is long.
This is an attempt to get around the constraints of the built-in sma(source, length) function in which length cannot be dynamically adjusted.
Other Pine Script functions have that constraint which we can get around by defining our own functions.
Function: Dinamic string InterpreterEXPERIMENTAL:
a arithmetic string interpreter that allows for using basic operations on input strings.
note: float values not supported currently.
Remember Rules Label - incl. Text Function with different colorsHi BIG PLAYERS
Each of us makes mistakes and exceptions confirm the rule.
However, if you disregard the rules of trading, you lose your money - without any ifs and buts!
I have therefore created a reminder label for myself, which trading approaches I always want to stick to. These rules serve me as a guideline when I should trade.
Through the permanent reminder I set myself the goal of not trading too early and impatiently. The biggest problem of all traders is overtrading: the constant swaying back and forth between greed and fear. This must always be kept in mind. Because trading is in principle very simple: stick to your own rules. Keep a logbook and for my sake, record every trade as a screenshot in a PowerPoint presentation. Then you can see your mistakes in the past trades and recognize your background, why loss trades have arisen - you can also determine profit trades: As a rule, profits arise when you strictly adhere to your trading rules.
If you compare a company with a trader, then it is generally a similar procedure.
company view
a company plans its annual development with budget and forecast.
a company compares monthly between actual values and plan values and draws conclusions from the differences.
trader view
a trader should handle and plan his trade with all rules.
a trader should compare the result after the trade with the planned trade and discuss conclusions from possible differences.
I hope I could help other traders with this.
Kind regards
NXT2017
Mod and Round To Tick FunctionI have not found this function anywhere on Tradingview but it can be very useful in setting orders in a strategy and non-integer boundaries for certain indicator designs. Its a bit underwhelming, but in other languages you can call a mod() function and the output will be the remainder of the integer.
If you want to set an order at a specific tick value, particularly in futures, you can't set it at a specific tick when using calculated values like ATR or Standard Deviation without a function like this.
It can also be used to clean up certain band/envelope style indicators if you want to have a straight line, but don't want to simply round to an integer.
Credit for the round to tick aspect goes to the eternal fountain of resources, the Backtesting & Trading Engine script from @pinecoders
This is just another tool to throw in the box for when you might need it.
function: Array DownsamplingA low cost function to down sample a array.
specially useful for pattern recognition algorithms.
Test: Chain casting multiple functions performanceExperimental:
A simple test to check performance impact of chaining functions in pinescript.
Test calling frequency impact.
Test: Chain casting functions performanceExperimental:
A simple test to check performance impact of chaining functions in pinescript.
Function Polynomial RegressionDescription:
A function that returns a polynomial regression and deviation information for a data set.
Inputs:
_X: Array containing x data points.
_Y: Array containing y data points.
Outputs:
_predictions: Array with adjusted _Y values.
_max_dev: Max deviation from the mean.
_min_dev: Min deviation from the mean.
_stdev/_sizeX: Average deviation from the mean.
Resources:
en.wikipedia.org
rosettacode.org
Function - Linear RegressionDescription:
A Function that returns a linear regression channel using (X,Y) vector points.
Inputs:
_X: Array containing x data points.¹
_Y: Array containing y data points.¹
Note:
¹: _X and _Y size must match.
Outputs:
_predictions: Array with adjusted _Y values at _X.
_max_dev: Max deviation from the mean.
_min_dev: Min deviation from the mean.
_stdev/_sizeX: Average deviation from the mean.
Resources:
www.statisticshowto.com
en.wikipedia.org
Function K-Means ClusteringDescription:
A Function that returns cluster centers for given data (X,Y) vector points.
Inputs:
_X: Array containing x data points.¹
_Y: Array containing y data points.¹
_number_of_clusters: number of clusters.
Note:
¹: _X and _Y size must match.
Outputs:
_centers_x: Array containing x data points.
_centers_y: Array containing y data points.
Resources:
rosettacode.org
en.wikipedia.org
Function: Multi Dimension IndexerDescription:
A Function that returns the flat index of a N dimensions array.
Inputs:
_indices: Array containing dimension indices.¹
_limits: Array containing dimension size.¹
Note:
¹: _indices and _limits size must match. indices must be within dimension size.
Outputs:
_offset: the flat 1D index.
Resources:
eli.thegreenplace.net
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.
Nth-Occurrence Custom barssince() Function by Cryptorhythms [CR]Nth-Occurrence Custom barssince() Function by Cryptorhythms
Description
The vanilla barssince() function in pine only finds the number of bars since the most recent occurrence of the condition. This version allows you to specify an Nth occurrence back to check the bars since! Its also a nice little one liner.
I really hope you enjoy it and if you're looking for more, this is our 79th script on TV, so there is plenty to choose from!
Let me know in the comments if you create anything useful from this or think of anyway to improve it!
[e2] Fibonacci slicerFibonacci slicer function.
The script is a simple calculator that accepts any 2 input values and divides the distance between those values using Fibonacci proportions.
- Easy for script integration (lines 21-35).
- The function accepts any 2 values and their order doesn't matter.
- Correctly divides negative-negative, negative-positive, positive-negative and positive-positive values.
- Calculates 7 levels derived from the Golden ratio (1.618033).
[RS]Example: function instantiationEXPERIMENTAL:
Practical example of how to create a shared function instance.
Early/Delayed Signal FunctionEarly/Delayed Signal Function (before the bar close or after)
Usually, signals are considered to be valid at the bar close .
Some traders may prefer to have a chance to enter earlier .
It is of great risk , and the Strategy Tester is unable to provide consistent backtest data with regards to this.
But for those who want to integrate such a choice in their strategies, here is the Early Signal Function .
The function takes 2 parameters
- the signal that is considered valid at the bar close , of type bool
- the early time value in seconds, the time before the signal is valid, of type int
it returns a value of type bool - a New Entry Signal
The resulting conditions used for alerts would be:
- newLongCondition = earlySignal_f(myLongSignal, earlyTime)
- newShrtCondition = earlySignal_f(myShrtSignal, earlyTime)
Note: the signals can also be delayed - use a negative value for early time
Function Decimal To Binary/Binary To DecimalNOTE: Experimental. Pinescript implementation of Decimal to Binary and Binary to Decimal that is intended for use in the development of a neural network proof of concept.
Intended for use in as subcomponent in the development of a more complex/highly experimental prototype.
Protection/logic for edge cases above 11111111/255 (8bits) is NOT implemented.
Do NOT use this in any trading system or component without edge case testing/unit tests.
// Decimal to Binary, Binary to Decimal Reference:
// diwasfamily.com
// www.wikihow.com
//
// www.khanacademy.org
Function : Stochastic Money Flow IndexThis function is similar to the stochastic rsi function.
The only difference is that Money Flow Index is used instead of rsi.
Oversold and overbought values were changed to 80 and 20.
Because the MFI's overbought and overbought zones are 20 and 80.
In MFI, I think that it can be more beneficial in liquid markets than stochastic rsi since volume is taken into account in contrast to RSI.
Regards.