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)
Analisis Candlestick
engulfing bullishengulfin bullish
The support and resistance lines of the previous candle are drawn. You can choose the lines in any length you want
B3_HH_LL_Break Bar PainterThis is a simple Highest High or Lowest Low Breakout Painter.
Defaults in the order that they may color bars - checks top color first:
where n = your input length
BLACK = Outside Bar HHLL(n)
RED = Lower Low LL(n)
GREEN = Higher High HH(n)
BLUE = Inside Bar HHLL(n)
You may customize the colors in the indicator's settings-cogwheel on the chart.
Enjoy!
d^.^b
Double DojiStrategy Kiss = 'Keep It Simple, Stupid' or 'Keep It Simple, Smart'
The script simply identifies 2 consecutive Doji candles, and calculates Target on both the sides for given Reward : Risk factor.
The High-Low to Open-Close ratio is set to default value 20. The Reward : Risk ratio is of default value 2.
Both can be set to values of your choice.
Accuracy best on Daily chart. Can be tried on any timeframe though.
Trading Rules: Buy at higher / Short at lower of the 2 candles, with other as Stop Loss.
If a Stop Loss is hit, go for reverse trade. If again a SL is hit, switch to other instrument.
Important: If trading in Futures and target is achieved, hedge the position by buying an option (subject to liquidity).
Reason is, the trend may condition to any extent and you would definitely not want to miss out the whole action.
Check the shared example. For a risk to 175 points, reward is 2200+ points (more than 12.5 times).
ICMCBased on basic Nimblr TA, Momentum Candles combined with Breakout/Breakdown can detect a change in trend direction.
Nimblr mainly categorizes candlesticks into Momentum (Body > 50%) and Indecision (Body < 50%) candlesticks.
⁕ shows Momentum Candles, others are Indecision Candles
↑ shows Breakout
↓ shows Breakdown
Yellow lines show the current Indecision candle and white lines the past Indecision candle.
Random Synthetic Asset GenerationThis script generates pseudo-random asset data . Due to the nature of the random generator, it is impossible to use this indicator as input for other indicators because the instance of the script that the indicator is applied to will automatically be different from the instance that is plotted on the chart. Therefore, the idea is to use this script in other scripts (to make it possible to backtest on random data, for example).
The script has four main input parameters.
Random Number Generator Method: It supports two methods for generating the pseudo-random numbers (one by Ricardo Santos and one by Wichmann-Hill).
Seed: You can specify the seed to use. Each unique seed will generate a unique set of pseudo-random data.
Intrabar Volatility: This basically sets how volatile the generated wicks will be (0 = no wicks).
Price Multiplier: This is just a multiplier for the generated price data, so that you can scale up or down the generated price data.
You can also change the colors of the bars.
In addition to this, the indicator also generates random volume. In order to make it possible to show both volume and price, you need to have two identical instances of the indicator. One on the chart, and one in its own panel. Then, go into the Style tab in the indicator settings on the instance in the panel. Untick Up-Candles and Down-Candles boxes, and tick the Volume box.
In a similar manner, you can also plot the true range data and the candle change data as well, by ticking one of those boxes instead.
Open/High/Low/Close (OHLC) Lines with Configurable TimeframeThis script draws open/high/low/close (OHLC) lines for the previous bar from the configured timeframe. This enables you to use higher timeframes, like a daily chart and OHLC lines of the previous week.
Configurable Settlement/FixingThis script draws a horizontal line starting at the open price of each configured settlement/fixing bar.
Past and Upcoming Forex and NYSE Start/End Bar HighlighterThis script highlights the start and end of past sessions and also for upcoming sessions of the current day. Additionally, the start/end bars of the current day can be marked with a text label.
Time zone parameters are available for all time parameters, so that local exchange times can be configured, without the need for manual time zone or daylight saving time (DST) adjustments. Tradingview’s internal time calculations take care of the conversion.
For ease of use, the script comes preconfigured with the start/end times of the Forex and NYSE trading sessions. If you need more highlighted bars, just add the script multiple times and adapt the configuration as needed.
All Candlestick Patterns StrategyThis strategy uses the tradingview built in candlestick recognition.
Trading Session Candles [NeoButane]█ OVERVIEW
Display candlesticks for the selected session, regular or extended.
█ CONFIGURATION
Options to change include displaying the regular or extended session, timezone, session hours, and session days.
█ CONCEPTS
Meant for charts with longer trading sessions or to view only extended hours trading action on US stocks that have afterhours available.
█ Notes
For trading days, '23456' refers to Monday to Friday.
Ether (Ethereum) CME Gaps [NeoButane]Detects gaps in trading for CME's "Ether" cash-settled futures. This will show gaps as they happen on the 24/7 charts that crypto exchanges use. It is not usable on CME's tickers themselves, as gaps in trading are not displayed.
This indicator will only display if viewing an ETH chart.
More information on the CME ETH futures here:
www.cmegroup.com
Based on:
What's different: CME's BTC and ETH markets trade the same hours, but one may hit a limit breaker while there may be a case where the other does not.
Vishwajit Nerkar [ stock genie ]this script points swing high, swing low and confuse candles on the chart.
Muqwishi Volumetric CandleIntroduction
Have you ever heard that each candle represents a battle between bulls (buyer) and bears (seller)? If you know the answer, apparently you understand what the price action means. What if I ask you, how much was bloody in each battle between bulls and bears?!. This indicator may give a clear picture of how to identify the candle’s strength by implementing the Standard Deviation on volume and reshape the candle.
The Muqwishi Volumetric Candles indicator works to weigh each candle instantaneously and updates its color level from lightness to darkness based on the rate of the volumetric standard deviation.
Here’s how the idea started with the conceptual design, then improved till achieved to the implemented design of a structured candle.
The conceptual design mentioned for reviewing how the idea started. However, I want you to understand the “implemented design” in which the indicator has been built to address it. As I stated structurally for the implemented design section, wick and border are identified by the user through “Chart Properties” unlike core and body is measured by the indicator.
The candle’s body is ”Dynamic” that colored based on the amount of volume standard deviation in which the low volume standard deviation is a lighter candle’s color and the high volume standard deviation is a darker candle’s color. The core is “Static” color represents zero volume standard deviation which the volume at the average level. In the case where the core is darker than the body means the volume standard deviation is lower than the average volume level, and when the core is lighter than the body mean the volume standard deviation is higher than the average volume level, and when the core’s color has the same body’s color means the volume is in the average level. The image is the best guide to understand the idea.
Rarely seeing a volume standard deviation below -2σ, even though the volume is apparently dead. However, it’s possible to see more than 3.9σ, and mostly it has the same effect as 3.9σ. Personally, any candle above 1.5σ is taking my attention, and more than 2σ I look around seeking for reasons to not take a trade.
§§ Note, if you have misunderstood the standard deviation concept, there are many great sources to understand it such as Wikipedia, YouTube,... etc. In a basic example, How much is your height relative to the height of average people in your city!!?. Similarly, how much is the amount of volume relative to the average volume of a number series of previous bars?!.
Indicator Overview
Before I get into this section, this is NOT meant to be an educational or recommendation. Just showing you how I use this indicator based on an experience.
The chart above has been remarked as an example of how I apply it. Again, it’s a personal preference, and it doesn’t mean this’s an efficient way.
Indicator Setting
➤ Ensure to visualize the indicator to the front for recognition of the candle’s core.
For more information check the image: drive.google.com
➤ Indicator’s title.
Generates two outputs. The first one is the coordinate location for the char “Core”, don’t pay attention to it. The second one colored in blue is referring to the measurement of the volume standard deviation as your cursor point move at any candle on the chart. For more information check the image: drive.google.com
➤ Indicator’s inputs.
■ Length: Number of previous bars covered in the calculation. Prefer between 14-20.
■ Long Candle Color: Choose a color for bullish candles.
■ Short Candle Color: Choose a color for bearish candles.
■ Color Mode: Kinda color style.
● Lightness: From lightness to darkness colored as low volume SD to high volume SD.
● Saturation: From narrow range to wide range colored as low volume SD to high volume SD.
■ Reverse Mode: Yes → Darkness to Lightness colored as low SD to high SD.
■ Show Core: No → Hide cores.
Summarize
■ Users should have a fundamental knowledge of Standard Deviation.
■ The candle’s body is dynamic colored. Got light as low volume standard deviation, and Dark as high volume standard deviation occurred.
■ The Candle’s core is static colored. Represents the average volume which Standard Deviation equals zero.
■ This’s not a trading signal. It works to visualize the level of transactions made per candle.
Final Comments
■ My goal was to achieve the conceptual design, but there’re many obstacles that go beyond the coding ability.
■ Let me know if you have any questions, comments, and any improvements to the project.
■ I hope every time you found this indicator useful and scaled up your trading skills, please present support through PayPal that linked in the signature box below. That will help to get me excited and post many ideas.
■ Trade Safe. ✌
Rate ConverterThis is a simple rate converter that can convert almost anything into almost anything else. It supports cryptocurrencies, currencies and most commodities.
On the chart we see the following:
USD (US Dollar) into EUR (Euro) as a candle stick chart
WTICO (West Texas Intermediate Crude Oil) into ISK (Icelandic Krona) as a bar chart
ADA (Cardano) into JMD (Jamaican Dollar) as a line chart
XPT (Platinum) into XAG (Silver) as a scatter plot
It supports plotting the rates as japanese candlesticks, bars, lines, or as a scatter plot.
NSDT Auto Fib Support / Resistance LevelsThis script automatically plots support and resistance lines using the fib numbers as the amount of candles to lookback. Each line is colored differently to easily identify the support/resistance pair (i.e. 23%, 38%, 61%, etc..) with the 50% (Green) and 78% (Red) a thicker line. All variables are editable. Added alert capability.
Previous Close To Current High Percentage Per CandleGet the percentage of previous candle price to current high candle price.
This script will make your life easier to get percentage without you calculating it.
Hope you enjoy the tool and let me know if there is any feedback or improvement request.
Thank you very much. :D
--------------------------------
Formula:
Previous To High Percentage Per Candle = (high - previous / previous) * 100%
--------------------------------
London Gold Fix TimesThis script highlights the London Gold Fix times (en.wikipedia.org) in your charts.
Wick Stop ZonesCount how many wicks bottom out in each price zone. Specify the following inputs.
Lookback: How far back from the latest candle to look for wick intersects.
Zone Size: The price range size for zone. Wicks tips that fall into each zone will be counted.
Minimum Intersects: Specifies how many wick tips must intersect with the zone before the zone is allowed to plot.