Strings█ OVERVIEW
This library provides string manipulation functions to complement the Pine Script™ `str.*()` built-in functions.
█ CONCEPTS
At the time our String Manipulation Framework was published, there was little in the way of built-in functions to manipulate strings. Since then, we have witnessed several meaningful developments on this front by the nimble Pine team. The newly released functions (including the ones in this blog post ) have deprecated most of our functions. This library captures the small handful of functions we think are still pertinent. It is worth noting that, thanks to the new string built-ins in Pine Script™, these functions greatly outperform their earlier counterparts, both performance-wise and because they can return values of simple form, which are a necessity in some circumstances, such as when used as arguments to some parameters of request.security() .
█ NOTES
`leftOf()` and `rightOf()`
Using the functions in this library is straightforward. The `leftOf()` and `rightOf()` functions extract the part of a string that is to the left or to the right of another string or character. This can be useful to separate the exchange and symbol components of user-entered tickers, for example. The separation is done with the underused str.match() , which can use regular expressions (or regex) to scan a string and separate characters based on a search pattern. The possibilities with regex are virtually endless; they can be used in “find and replace” applications, or to validate phone numbers, emails, passwords, credit card numbers, dates, etc. Note that Pine supports the same regex features as Java .
String operations in Pine Script™
The Pine Script™ runtime is optimized for number crunching. You can thus optimize script performance by limiting operations on strings whenever possible. This includes declaring strings with the var keyword, and containing re-assignments to local if blocks using barstate.islast , for example.
Look first. Then leap.
█ FUNCTIONS
leftOf(str, separator, occurrence)
Extracts the part of the `str` string that is left of the nth `occurrence` of the `separator` string.
Parameters:
str : (series string) Source string.
separator : (series string) Separator string.
occurrence : (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence).
Returns: (string) The extracted string.
rightOf(str, separator, occurrence)
Extracts the part of the `str` string that is right of the nth `occurrence` of the `separator` string.
Parameters:
str : (series string) Source string.
separator : (series string) Separator string.
occurrence : (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence).
Returns: (string) The extracted string.
Strings
_lib_MilitzerThis is a collection of functions either found on the internet, or made by me.
This is only public so my other scripts that reference this can also be public.
If you find anything useful for you here, be my guest.
lib_MilitzerLibrary "lib_Militzer"
// This is a collection of functions either found on the internet, or made by me.
// This is only public so my other scripts that reference this can also be public.
// But if you find anything useful here, be my guest.
print()
strToInt()
timeframeToMinutes()
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
ArrayOperationsLibrary "ArrayOperations"
Array element wise basic operations.
add(sample_a, sample_b) Adds sample_b to sample_a and returns a new array.
Parameters:
sample_a : values to be added to.
sample_b : values to add.
Returns: array with added results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
subtract(sample_a, sample_b) Subtracts sample_b from sample_a and returns a new array.
sample_a : values to be subtracted from.
sample_b : values to subtract.
Returns: array with subtracted results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
multiply(sample_a, sample_b) multiply sample_a by sample_b and returns a new array.
sample_a : values to multiply.
sample_b : values to multiply with.
Returns: array with multiplied results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
divide(sample_a, sample_b) Divide sample_a by sample_b and returns a new array.
sample_a : values to divide.
sample_b : values to divide with.
Returns: array with divided results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
power(sample_a, sample_b) power sample_a by sample_b and returns a new array.
sample_a : values to power.
sample_b : values to power with.
Returns: float array with power results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
remainder(sample_a, sample_b) Remainder sample_a by sample_b and returns a new array.
sample_a : values to remainder.
sample_b : values to remainder with.
Returns: array with remainder results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
equal(sample_a, sample_b) Check element wise sample_a equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
not_equal(sample_a, sample_b) Check element wise sample_a not equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
over_or_equal(sample_a, sample_b) Check element wise sample_a over or equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
under_or_equal(sample_a, sample_b) Check element wise sample_a under or equals sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
over(sample_a, sample_b) Check element wise sample_a over sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
under(sample_a, sample_b) Check element wise sample_a under sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
and_(sample_a, sample_b) Check element wise sample_a and sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
or_(sample_a, sample_b) Check element wise sample_a or sample_b and returns a new array.
sample_a : values to check.
sample_b : values to check.
Returns: int array with results.
- sample_a provides type format for output.
- arrays do not need to be symmetric.
- sample_a must have same or more elements than sample_b
all(sample) Check element wise if all numeric samples are true (!= 0).
sample : values to check.
Returns: int.
any(sample) Check element wise if any numeric samples are true (!= 0).
sample : values to check.
Returns: int.
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)
Thange VaultLibrary "ThangeVault"
Thange Vault is a collection of utility functions required by the Thange Woodwind Playbook.
debug(msg) Print debug information
Parameters:
msg : message to be logged on console
Returns: nothing
tickFormat() Create a string template to restrict stop-loss, take-profit level precision to ticks.
Returns: A string format template
hashmapsA simple hashmap implementation for pinescript.
It gets your string array and transforms it into a hashmap.
Before using it you need to initialize your array with the size you need for your specific case since the size is not dynamic.
To use it, first you need to import it the following way:
> import marspumpkin/hashmaps/1
Then, initialize your array with the size needed for your specific case:
> hashmap = array.new_string(10000)
After that you can call:
> hashmaps.put() and hashmaps.get()
Passing in the array(hashmap), key and value.
I hope this helps you in your pinescript journey.
psonPineScript Object Notation
A workaround not having objects in pinescript.
This is a Json-look-alike interpreter.
Format: "attr=value:attr1=value1:attr2=value2".
You can add new attributes, get the value in those attributes, set new values to existing attributes and check if an attribute exists.
Dictionary/Object LibraryThis Library is aimed to mitigate the limitation of Pinescript having only one structured data type which is only arrays.
It lacks data types like Dictionaries(in Python) or Object (in JS) that are standard for other languages. Tuples do exist, but it hardly solves any problem.
Working only with Arrays could be overwhelming if your codebase is large. I looked for alternatives to arrays but couldn't find any library.
So I coded it myself and it's been working good for me. So I wanted to share it with you all.
What does it do:
==================
If you are familiar with Python or Javascript, this library tries to immimate Object/Dictonary like structure with Key Value Pairs.
For Example:
object= {name:"John Doe", age: 28 , org: "PineCoders"}
And then it also tries to immitate the Array of Objects (I call it Stack)
like this:
stack= Array({name:"John Doe", age: 28 , org: "PineCoders"},
{name:"Adam Smith", age: 32 , org: "PineCoders"},
{name:"Paragjyoti Deka", age: 25 , org: "PineCoders"})
So there are basically two ideas: Objects and Stacks.
But it looks whole different in Pinescript for obvious reasons.
Limitation:
The major limitation I couldn't overcome was that, for all of the values: both input and return values for properties will be of string type.
This is due to the limiation of Pinecsript that there is no way to return a value on a if-else statement dynamically with different data types.
And as the input data type must be explicitly defined when exporting the library functions, only string inputs are allowed.
Now that doesn't mean you won't be able to use integer, float or boolens, you just need to pass the string value for it using str.tostring() method.
And the output for the getter functions will be in strings as well. But I have added some type conversion methods that you could use from this library itself.
From String to Float, String To Integer and String to Boolean: these three methods are included in this library.
So basically the whole library is based on a manipulatiion of Array of strings under the hood.
///////////////
Usage
///////////////
Import the library using this statement:
import paragjyoti2012/STR_Dict_Lib/4 as DictLib
Objects
First define an object using this method:
for eample:
object1= DictLib.init("name=John,age=26,org=")
This is similar to
object1= {name:"John",age:"26", org:""} in JS or Python
Just like we did here in for "org", you can set initital value to "". But remember to pass string values, even for a numerical properties, like here in "age".
You can use "age="+str.tostring(age). If you find it tedious, you can always add properties later on using .set() method.
So it could also be initiated like this
object= DictLib.init("name=John")
and later on
DictLib.set(object1,"age", str.toString(age))
DictLib.set(object1,"org", "PineCoders")
The getter function looks like this
age= DictLib.get(object1,"age")
name=DictLib.get(object1,"name")
The first argument for all methods .get, .set, and .remove is the pointer (name of the object).
///////////////////////////
Array Of Objects (Stacks)
///////////////////////////
As I mentioned earlier, I call the array of objects as Stack.
Here's how to initialize a Stack.
stack= DictLib.initStack(object1)
The .initStack() method takes an object pointer as argument. It simply converts the array into a string and pushes it into the newly created stack.
Rest of all the methods for Stacks, takes the stack pointer as it's first arument.
For example:
DictLib.pushStack(stack,object2)
The second argument here is the object pointer. It adds the object to it's stack. Although it might feel like a two dimentional array, it's actually an one dimentional array with string values.
Under the hood, it looks like this
////////////////////
Methods
////////////////////
For Objects
-------------------
init() : Initializes the object.
params: (string) e.g
returns: The object ( )
example:
object1=DictLib.init("name=John,age=26,org=")
...................
get() : Returns the value for given property
params: (string object_pointer, string property)
returns: string
example:
age= DictLib.get(object1,"age")
.......................
set() : Adds a new property or updates an existing property
params: (string object_pointer, string property, string value)
returns: void
example:
DictLib.set(object1,"age", str.tostring(29))
........................
remove() : Removes a property from the object
params : (string object_pointer, string property)
returns: void
example:
DictLib.set(object1,"org")
........................
For Array Of Objects (Stacks)
-------------------------------
initStack() : Initializes the stack.
params: (string object_pointer) e.g
returns: The Stack
example:
stack= DictLib.initStack(object1)
...................
pushToStack() : Adds an object at at last index of the stack
params: (string stack_pointer, string object_pointer)
returns: void
example:
DictLib.pushToStack(stack,object2)
.......................
popFromStack() : Removes the last object from the stack
params: (string stack_pointer)
returns: void
example:
DictLib.popFromStack(stack)
.......................
insertToStack() : Adds an object at at the given index of the stack
params: (string stack_pointer, string object_pointer, int index)
returns: void
example:
DictLib.insertToStack(stack,object3,1)
.......................
removeFromStack() : Removes the object from the given index of the stack
params: (string stack_pointer, int index)
returns: void
example:
DictLib.removeFromStack(stack,2)
.......................
getElement () : Returns the value for given property from an object in the stack (index must be given)
params: (string stack_pointer, int index, string property)
returns: string
example:
ageFromObject1= DictLib.getElement(stack,0,"age")
.......................
setElement() : Updates an existing property of an object in the stack (index must be given)
params: (string stack_pointer, int index, string property, string value)
returns: void
example:
DictLib.setElement(stack,0,"age", str.tostring(32))
........................
includesElement() : Checks if any object exists in the stack with the given property-value pair
params : (string stack_pointer, string property, string value)
returns : Boolean
example:
doesExist= DictLib.includesElement(stack,"org","PineCoders")
........................
searchStack() : Search for a property-value pair in the stack and returns it's index
params: (stringp stack_pointer, string property, string value)
returns: int (-1 if doesn't exist)
example:
index= DictLib.searchElement(stack,"org","PineCoders")
///////////////////////
Type Conversion Methods
///////////////////////
strToFloat() : Converts String value to Float
params: (string value)
returns: float
example:
floatVal= DictLib.strToFloat("57.96")
.............................
strToInt() : Converts String value to Integer
params: (string value)
returns: int
example:
intVal= DictLib.strToFloat("45")
.............................
strToBool() : Converts String value to Boolean
params: (string value)
returns: boolean
example:
boolVal= DictLib.strToBool("true")
.............................
Points to remember
...............
1. Always pass string values as arguments.
2. The return values will be of type string, so convert them before to avoid typecasting conflict.
3. Horses can't vomit.
More Informations
====================
Yes, You can store this objects and stacks for persisting through the iterations of a script across successive bars.
You just need to set the variable using "var" keyword. Remember this objects and stacks are just arrays,
so any methods and properties an array have it pinescript, would be applicable for objects and stacks.
It can also be used in security functions without any issues for MTF Analysis.
If you have any suggestions or feedback, please comment on the thread, I would surely be happy to help.
CRC.lib Characters and StringsLibrary "CRCChars"
arrow_up() : ▲
arrow_down() : ▼
warning() : ⚠
checkmark() : ✅
no_entry() : 🚫
ConverterTFLibrary "ConverterTF"
I have found a bug Regarding the timeframe display, on the chart I have found that the display is numeric, for example 4Hr timeframe instead of '4H', but it turns out to be '240', which I want it to be displayed in abbreviated form. And in all other timeframes it's the same. So this library was created to solve those problems. It converts a timeframe from a numeric string type to an integer type by selecting a timeframe manually and displaying it on the chart.
CTF()
str = "240"
X.GetTF( str )
Example
str = input.timeframe(title='Time frame', defval='240')
TimeF = CTF(str)
L=label.new(bar_index, high, 'Before>> Timeframe '+str+' After>> Timeframe '+TimeF,style=label.style_label_down,size=size.large)
label.delete(L )
Custom timeframes can handle this issue as well.
An example from the use. You will find it on the bottom right hand side.
Hopefully it will be helpful to the Tradingview community. :)
Signal_Data_2021_09_09__2021_11_18Library "Signal_Data_2021_09_09__2021_11_18"
Functions to support my timing signals system
import_start_time(harmonic) get the start time for each harmonic signal
Parameters:
harmonic : is an integer identifying the harmonic
Returns: the starting timestamp of the harmonic data
import_signal(index, harmonic) access point for pre-processed data imported here by copy paste
Parameters:
index : is the current data index, use 0 to initialize
harmonic : is the data set to index, use 0 to initialize
Returns: the data from the indicated harmonic array starting at index, and the starting timestamp of that data
UnicodeReplacementFunctionLibrary "UnicodeReplacementFunction"
Unicode Characters Replacement function for strings.
replaceFont(_str, _fontType) Unicode Character Replace Function
Parameters:
_str : String input
_fontType : Font Type Selector
Returns: Replaced Char String with any custom font type choosed
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
FunctionArrayReduceLibrary "FunctionArrayReduce"
A limited method to reduce a array using a mathematical formula.
float_(formula, samples, arguments, initial_value) Method to reduce a array using a mathematical formula.
Parameters:
formula : string, the mathematical formula, accepts some default name codes (index, output, previous, current, integer index of arguments array).
samples : float array, the data to process.
arguments : float array, the extra arguments of the formula.
initial_value : float, default=0, a initial base value for the process.
Returns: float.
Notes:
** if initial value is specified as "na" it will default to the first element of samples.
smfLibrary "smf"
f_strLeft(string, int) Function returning the leftmost `_n` characters in `_str`.
Parameters:
string : _str: source string.
int : _n : number of leftmost characters to return.
f_strRight(string, int) Function returning the rightmost `_n` characters in `_str`.
Parameters:
string : _str: source string.
int : _n : number of rightmost characters to return.
f_strMid(string, int, int) Function returning the substring of `_str` from character position `_from` to `_to` inclusively.
Parameters:
string : _str : source string.
int : _from: left character position. The first character's position is 0.
int : _to : right character position.
f_strLeftOf(string, string) Function returning the sub-string of `_str` to the left of the `_of` separating character.
Parameters:
string : _str: string to separate.
string : _op : separator character.
f_strRightOf(string, string) Function returning the sub-string of `_str` to the right of the `_of` separating character.
Parameters:
string : _str: string to separate.
string : _op : separator character.
f_strCharPos(string, string) 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.
Parameters:
string : _str: string to search.
string : _chr: character to search for in `_str`.
f_strReplace(string, int, string) Function that replaces a character at position `_pos` in the `_src` string with the `_str` character or string.
Parameters:
string : _src : source string.
int : _pos : position of character to be replaced. The first character's position is 0.
string : _str : replacement 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(float, string) 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.
Parameters:
float : _val: string to separate.
string : _fmt: formatting string similar to those used in the `tostring()` format string, with "?" used to indicate padding,
f_print() Function prints a label on dataset's last bar.
Bursa_SectorLibrary "Bursa_Sector"
: List of stocks classified by sector in Bursa Malaysia (As of Oct 2021)
getSector()
This function will get the sector of current stock that listed in Bursa Malaysia
StringEvaluationLibrary "StringEvaluation"
Methods to handle evaluation of strings.
is_comma(char) Check if char is a comma ".".
Parameters:
char : string, 1 character string.
Returns: bool.
is_op(char) Check if char is a operator.
Parameters:
char : string, 1 character string.
Returns: bool.
number(char) convert a single char string into valid number.
Parameters:
char : string, 1 character string.
Returns: float.
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.
cleanup(_str) Evaluate a string to clean up and retrieve only used chars
Parameters:
_str : string, arithmetic operations in a string.
Returns: string array, evaluated array.
generate_rpn(tokens) uses Shunting-Yard algorithm to generate a RPN (Reverse Polish notation)
array of strings from a array of strings containing arithmetic notation.
ex:.. ' ' --> ' '
Parameters:
tokens : string array, array with arithmetic notation.
Returns:
parse_rpn() evaluate a RPN (Reverse Polish notation) array of strings.
ex:.. 3 4 2 * 1 5 - 2 3 ^ ^ / +
| @param tokens string array, RPN ordered tokens, ex( ).
| @returns float, solution.
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.