How To Identify Argument Type Of Number Using OverloadsExample overload functions accept loading of _value for types float, int, or string, then positively identifies the actual argument type of that specific loaded _value.
String
How To Identify Type Of NumberExample function accepts loading of _value for types float, int, or string, then identifies whether the loaded _value is a string number, string, or number.
jsonLibrary "json"
Convert JSON strings to tradingview
▦ FEATURES ▦
█ Json to array █ Get json key names █ Get json key values █ Size of json
get_json_keys_names(raw_json) Returns string array with all key names
Parameters:
raw_json : (string) Raw JSON string
Returns: (string array) Array with all key names
get_values_by_id_name(raw_json, key_name) Returns string array with values of the input key name
Parameters:
raw_json : (string) Raw JSON string
key_name : (string) Name of the key to be fetched
Returns: (string array) Array with values of the input key name
size_of_json_string(raw_json) Returns size of raw JSON string
Parameters:
raw_json : (string) Raw JSON string
Returns: Size of n_of_values, size of n_of_keys_names
CRCHud - HUD Library (Heads Up Display)Library "CRCHud"
Library of functions which will contain functions that allow reusable HUD (Heads up Display) components to used from within other scripts
add_cell_change() - Adds a new cell to designated table which displays the data source value, the line color, data title, and automatically calculated %percent change stats based on lookback value supplied (default - previous bar)
DiscordWebhookFunctionLibrary "DiscordWebhookFunction"
discordMarkdown(_str, _italic, _bold, _code, _strike, _under) Convert string to markdown formatting User can combine any function at the same time.
Parameters:
_str : String input
_italic : Italic
_bold : Bold
_code : Code markdown
_strike : Strikethrough
_under : Underline
Returns: string Markdown formatted string.
discordWebhookJSON(_username, _avatarImgUrl, _contentText, _bodyTitle, _descText, _bodyUrl, _embedCol, _timestamp, _authorName, _authorUrl, _authorIconUrl, _footerText, _footerIconUrl, _thumbImgUrl, _imageUrl) Convert data to JSON format for Discord Webhook Integration.
Parameters:
_username : Override bot (webhook) username string / name,
_avatarImgUrl : Override bot (webhook) avatar by image URL,
_contentText : Main content page message,
_bodyTitle : Custom Webhook's embed message body title,
_descText : Webhook's embed message body description,
_bodyUrl : Webhook's embed body direct link URL,
_embedCol : Webhook's embed color,
_timestamp : Timestamp,
_authorName : Webhook's embed author name / title,
_authorUrl : Webhook's embed author direct link URL,
_authorIconUrl : Webhook's embed author icon by image URL,
_footerText : Webhook's embed footer text / title,
_footerIconUrl : Webhook's embed footer icon by image URL,
_thumbImgUrl : Webhook's embed thumbnail image URL,
_imageUrl : Webhook's embed body image URL.
Returns: string Single-line JSON format
MathComplexEvaluateLibrary "MathComplexEvaluate"
TODO: add library description here
is_op(char) Check if char is a operator.
Parameters:
char : string, 1 character string.
Returns: bool.
operator(op, left, right) operation between left and right values.
Parameters:
op : string, operator string character.
left : float, left value of operation.
right : float, right value of operation.
operator_precedence(op) level of precedence of operator.
Parameters:
op : string, operator 1 char string.
Returns: int.
eval() evaluate a string with references to a array of arguments.
| @param tokens string, arithmetic operations with references to indices in arguments, ex:"0+1*0+2*2+3" arguments
| @param arguments float array, arguments.
| @returns float, solution.
FunctionDatestringLibrary "FunctionDatestring"
Methods to stringify date/time, altho there is already builtin support for it.
datetime(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
date_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
time_(unixtime) a stringified date stamp at specified unix time.
Parameters:
unixtime : int unix timestamp.
Returns: string
To Integer FunctionCustom toInteger() function accepts and truncates the following forms: const, input, simple, and series of the following types: float, integer, and string.
Special thanks and credit to BeeHolder for idea on using str.format("{0}", string) as workaround for accepting and handling string types!
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
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)
String Manipulation Framework [PineCoders FAQ]█ OVERVIEW
This script provides string manipulation functions to help Pine coders.
█ FUNCTIONS PROVIDED
f_strLeft(_str, _n)
Function returning the leftmost `_n` characters in `_str`.
f_strRight(_str, _n)
Function returning the rightmost `_n` characters in `_str`.
f_strMid(_str, _from, _to)
Function returning the substring of `_str` from character position `_from` to `_to` inclusively.
f_strLeftOf(_str, _of)
Function returning the sub-string of `_str` to the left of the `_of` separating character.
f_strRightOf(_str, _of)
Function returning the sub-string of `_str` to the right of the `_of` separating character.
f_strCharPos(_str, _chr)
Function returning the position of the first occurrence of `_chr` in `_str`, where the first character position is 0. Returns -1 if the character is not found.
f_strReplace(_src, _pos, _str)
Function that replaces a character at position `_pos` in the `_src` string with the `_str` character or string.
f_tickFormat()
Function returning a format string usable with `tostring()` to round a value to the symbol's tick precision.
f_tostringPad(_val, _fmt)
Function returning a string representation of a numeric `_val` using a special `_fmt` string allowing all strings to be of the same width, to help align columns of values.
`f_tostringPad()`
Using the functions should be straightforward, but `f_tostringPad()` requires more explanations. Its purpose is to help coders produce columns of fixed-width string representations of numbers which can be used to produce columns of numbers that vertically align neatly in labels, something that comes in handy when, for example, you need to center columns, yet still produce numbers of various lengths that nonetheless align.
While the formatting string used with this function resembles the one used in tostring() , it has a few additional characteristics:
• The question mark (" ? ") is used to indicate that padding is needed.
• If negative numbers must be handled by the function, the first character of the formatting string must be a minus sign ("-"),
otherwise the unary minus sign of negative numbers will be stripped out.
• You will produce more predictable results by using "0" rather than "#" in the formatting string.
You can experiment with `f_tostringPad()` formatting strings by changing the one used in the script's inputs and see the results on the chart.
These are some valid examples of formatting strings that can be used with `f_tostringPad()`:
"???0": forces strings to be four units wide, in all-positive "int" format.
"-???0": forces strings to be four units wide, plus room for a unary minus sign in the first position, in "int" format.
"???0.0": forces strings to be four units wide to the left of the point, all-positive, with a decimal point and then a mantissa rounded to a single digit.
"-???0.0?": same as above, but adds a unary minus sign for negative values, and adds a space after the single-digit mantissa.
"?????????0.0": forces the left part of the float to occupy the space of 10 digits, with a decimal point and then a mantissa rounded to a single digit.
█ CHART
The information displayed by this indicator uses the values in the script's Inputs, so you can use them to play around.
The chart shows the following information:
• Column 0 : The numeric input values in a centered column, converted to strings using tostring() without a formatting argument.
• Column 1 : Shows the values formatted using `f_tostringPad()` with the formatting string from the inputs.
• Column 2 : Shows the values formatted using `f_tostringPad()` but with only the part of the formatting string left of the decimal point, if it contains one.
• Column 3 : Shows the values formatted using `f_tostringPad()` but with the part of the formatting string left of the decimal point,
to which is added the right part of the `f_tostringPad()` formatting string, to obtain the precision in ticks of the symbol the chart is on.
• Column 4 : Shows the result of using the other string manipulation functions in the script on the source string supplied in the inputs.
It also demonstrates how to split up a label in two distinct parts so that you can vertically align columns when the leftmost part contains strings with varying lengths.
You will see in our code how we construct this column in two steps.
█ LIMITATIONS
The Pine runtime is optimized for number crunching. Too many string manipulations will take a toll on the performance of your scripts, as can readily be seen with the running time of this script. To minimize the impact of using string manipulation functions in your scripts, consider limiting their calculation to the first or last bar of the dataset when possible. This can be achieved by using the var keyword when declaring variables containing the result of your string manipulations, or by enclosing blocks of code in if blocks using barstate.isfirst or barstate.islast .
█ NOTES
To understand the challenges we face when trying to align strings vertically, it is useful to know that:
• As is the case in many other places in the TadingView UI and other docs, the Pine runtime uses the MS Trebuchet font to display label text.
• Trebuchet uses proportionally-spaced letters (a "W" takes more horizontal space than an "I"), but fixed-space digits (a "1" takes the same horizontal space as a "3").
Digits all use a figure space width, and it is this property that allows us to align numbers vertically.
The fact that letters are proportionally spaced is the reason why we can't vertically align columns using a "legend" + ":" `+ value structure when the "legend" part varies in width.
• The unary minus sign is the width of a punctuation space . We use this property to pad the beginning of numbers
when you use a "-" as the first character of the `f_tostringPad()` formatting string.
Our script was written using the PineCoders Coding Conventions for Pine .
The description was formatted using the techniques explained in the How We Write and Format Script Descriptions PineCoders publication.
█ THANKS
Thanks to LonesomeTheBlue for the `f_strReplace()` function.
Look first. Then leap.