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)
Strings
DEMO ASCII Encode/DecodeDemo
Encode a string to an ascii array and decode the ascii array to a string.
Reads ascii 32 to 126.
Takes a long time to execute. You may get the "Loop is too long (> 200 ms)" execution error.
You can change the loop to iterate fewer times thereby shorten the string length.
OR
you can limit the characters converted.
THIS IS AN ABSOLUTE KLUDGE.
Just showing how to do this.
Store several numbers in a stringA method to store a bunch of numbers in one string.
Using my method of translating a string to a number, we can put several values in one string and then pop them up when we need.
To store the values I use a semicolon as a separator, so the format of the string is next one:
NUMBER:NUMBER:NUMBER:NUMBER
I don't see any useful application of this method (maybe, to pass some additional info to the script in one string), but maybe it'll be helpful to someone.
String to NumberA small method to translate strings to numbers.
For example, we have a string:
s = "321"
To check if the last symbol is "1", we might just try to remove (or replace with an empty string) the symbol "1". If the string changed, then there was the symbol "1" in the string:
s2 = str.replace_all (s, "1", "")
now s2 is "32", so
s == s2 returns false.
But we can't find out what the position of the symbol "1" was and if there was only one symbol "1".
To be sure, we just add a special character (I use ';') to the end of the string, and then try to remove not just "1", but the string "1;":
s = "321;"
s2 = str.replace_all (s, "1;", "")
Now, if s != s2, then we might be sure, that last symbol of the string was "1". And then we might check for all digits and get information about what digit we have and at what position. Same for additional symbols: decimal point and minus.
Multi Bar OHLC Compare Panel (Floating Grid)Multi Bar OHLC Compare Panel by RagingRocketBull 2019
version 1.0
This indicator lets you compare OHLCV values from several specified bars. Bars can be dynamic/persistent.
You can also use it as an alternate OHLC panel if you don't like small font of the native TradingView panel.
It uses Pinescript v4 to output data dynamically as string labels in a horiz/vertical grid.
Features:
- Floating Panel with customizable horiz/vertical layout and grid spacing
- Support for up to 5 OHLC bars (highlighted with markers)
- Outputs Bar #/index, OHLCV, Bar Change Value/%, Exchange/Ticker, Timeframe, Timestamp strings
- Dynamic (fixed offset)/Persistent bars (fixed time)
- Show/Hide parts of strings
- Full output string customization, including text size, date/time format and delimiters
- 2 Anchor points for panel offset: cur bar high or range high
- Bar Change can change color
Usage:
- specify at least 1 bar index as OHLC source
- select anchor point to position the panel
- select horiz/vertical grid layout
- adjust horiz/vertical spacing
- customize output strings as needed
Notes:
- this indicator uses Pinescript v3 Compatibity Framework
- both bars 1,2 are required for log scale adjustment to work
- you can't attach the panel to screen's top/bottom and must use offset/anchor because, unlike plotshape, string labels don't support yloc=yloc.top/bottom, only yloc.above/belowbar
- you can't precisely align strings in a grid because there's no label.get_width/height to calculate mid/left points, only get_x/y/text. Alignment will break depending on string length, zoom and change color option on/off
- bar change is rendered as a separate label when change color is enabled (2 panels total) and merged into the main panel when disabled (single panel)
- you can't change the order of strings as playing with the natural order of things isn't the best of ideas
- you can modify the script to compare up to 50 OHLC bars, but do you need that much power? Of course, you do.
- you can't set color/style for string labels in Style UI, so a few extra settings were added.
- bar index is limited to 5000 for free accounts (10000 for paid), will show an error when exceeded, also when it exceeds the total number of bars in history
- in persistent bars mode all bars with index > 0 are considered persistent, bar 0 always remains a dynamic bar
- persistent bars' offset is reset: in replay mode on exit or when price reaches cur bar, or when panel layout is changed from h to v in both replay/realtime modes
- initial pos of each persistent bar relative to the first realtime bar anchor doesn't change during session - new persistent bars introduced during session are attached to the most recent cur bar anchor
P.S. Everything is proceeding as I have foreseen