FUNCTION: Limited Historical Data WorkaroundFUNCTION: Limited Historical Data Workaround
If you are working with bitcoin weekly charts, or any other ticker with a low amount of price history this function may help you out. For example you want to apply indicators to some shitcoin that just launched? This can help you.
It can be frustrating to use certain built-ins since they will only give an output once the full lookback length is available. This function allows you to avoid that situation and start plotting things with almost no history whatsoever!
In this example code we do it by utilizing a replacement for the built in pine SMA function. This function allows us to pass a series instead of just a simple int to the length variable of the SMA. This can be achieved with all the pine built ins and I believe @pinecoders has a publication already detailing many of them with full coded examples.
Then we replace the length of the SMA with the custom history function. It checks to see if the current bar index is less than the length of the function. Then if it is, it changes the length to the bar index allowing us to get plots and series earlier than otherwise possible.
Pinescript
Symbol InfoFor those who likes clean chart:
Adjustable Symbol ticker and timeframe( AKA watermark) script is here.
1: You can place Symbol ticker and timeframe info anywhere on the chart.
Also you can hide one of them or both.
Position:
Horizontal options: Left Center Right
Vertical options: Top Middle Bottom
Size: Tiny Smal Normal Large Huge Auto
Color is adjustable. Background is optional too.
2: Even more cool part is you can add 2 different custom texts that can switch. (Idea from Pinecoders original script)
You don't have to use text function and reposition it everytime, your message will always stays at one place.
Let the chart deliver your message.
I put my favourite trading slangs there:
1. Do Your Own Research (DYOR)
2. Not a Financial Advice ( NFA)
UtilityFunctionsLibrary "UtilityFunctions"
Utility functions written by me
printLabelOnLastBar_string(string)
Prints string in a label on the last bar
Parameters:
string : value to print
Returns: void
printLabelOnLastBar_float(float)
Prints float in a label on the last bar
Parameters:
float : value to print
Returns: void
printSeriesInReverseOnLabels(series)
Prints a float series in labels in reverse (the first value is on the last candle, the second value is on the second to last candle, etc.)
Parameters:
series : float values to print
Returns: void
isPeriodDailyBased(string)
Returns true/false if the period is Daily based (1D, 3D, ...)
Parameters:
string : timeframe period
Returns: true/false
get_multiplier(string)
Gets the mutliplier of the timeframe passed compared to the current timeframe. If current TF is 5m and the passed timeframe period is 30m, the result will be 6
Parameters:
string : timeframe param
Returns: simple float of the multiplier
SUPERTREND MIXED ICHI-DMI-DONCHIAN-VOL-GAP-HLBox@RLSUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL
by RegisL76 (lebourg.regis@free.fr)
This script is based on several trend indicators.
* ICHIMOKU (KINKO HYO)
* DMI (Directional Movement Index)
* SUPERTREND ICHIMOKU + SUPERTREND DMI
* DONCHIAN CANAL Optimized with Colored Bars
* HMA Hull
* Fair Value GAP
* VOLUME/ MA Volume
* PRICE / MA Price
* HHLL BOXES
All these indications are visible simultaneously on a single graph. A data table summarizes all the important information to make a good trade decision.
ICHIMOKU Indicator:
The ICHIMOKU indicator is visualized in the traditional way.
ICHIMOKU standard setting values are respected but modifiable. (Traditional defaults = .
An oriented visual symbol, near the last value, indicates the progression (Ascending, Descending or neutral) of the TENKAN-SEN and the KIJUN-SEN as well as the period used.
The CLOUD (KUMO) and the CHIKOU-SPAN are present and are essential for the complete analysis of the ICHIMOKU.
At the top of the graph are visually represented the crossings of the TENKAN and the KIJUN.
Vertical lines, accompanied by labels, make it possible to quickly visualize the particularities of the ICHIMOKU.
A line displays the current bar.
A line visualizes the end of the CLOUD (KUMO) which is shifted 25 bars into the future.
A line visualizes the end of the chikou-span, which is shifted 25 bars in the past.
DIRECTIONAL MOVEMENT INDEX (DMI) : Treated conventionally : DI+, DI-, ADX and associated with a SUPERTREND DMI.
A visual symbol at the bottom of the graph indicates DI+ and DI- crossings
A line of oriented and colored symbols (DMI Line) at the top of the chart indicates the direction and strength of the trend.
SUPERTREND ICHIMOKU + SUPERTREND DMI :
Trend following by SUPERTREND calculation.
DONCHIAN CHANNEL: Treated conventionally. (And optimized by colored bars when overshooting either up or down.
The lines, high and low of the last values of the channel are represented to quickly visualize the level of the RANGE.
SUPERTREND HMA (HULL) Treated conventionally.
The HMA line visually indicates, according to color and direction, the market trend.
A visual symbol at the bottom of the chart indicates opportunities to sell and buy.
VOLUME:
Calculation of the MOBILE AVERAGE of the volume with comparison of the volume compared to the moving average of the volume.
The indications are colored and commented according to the comparison.
PRICE: Calculation of the MOBILE AVERAGE of the price with comparison of the price compared to the moving average of the price.
The indications are colored and commented according to the comparison.
HHLL BOXES:
Visualizes in the form of a box, for a given period, the max high and min low values of the price.
The configuration allows taking into account the high and low wicks of the price or the opening and closing values.
FAIR VALUE GAP :
This indicator displays 'GAP' levels over the current time period and an optional higher time period.
The script takes into account the high/low values of the current bar and compares with the 2 previous bars.
The "gap" is generated from the lack of overlap between these bars. Bearish or bullish gaps are determined by whether the gap is above or below HmaPrice, as they tend to fill, and can be used as targets.
NOTE: FAIR VALUE GAP has no values displayed in the table and/or label.
Important information (DATA) relating to each indicator is displayed in real time in a table and/or a label.
Each information is commented and colored according to direction, value, comparison etc.
Each piece of information indicates the values of the current bar and the previous value (in "FULL" mode).
The other possible modes for viewing the table and/or the label allow a more synthetic view of the information ("CONDENSED" and "MINIMAL" modes).
In order not to overload the vision of the chart too much, the visualization box of the RANGE DONCHIAN, the vertical lines of the shifted marks of the ICHIMOKU, as well as the boxes of the HHLL Boxes indicator are only visualized intermittently (managed by an adjustable time delay ).
The "HISTORICAL INFO READING" configuration parameter set to zero (by default) makes it possible to read all the information of the current bar in progress (Bar #0). All other values allow to read the information of a historical bar. The value 1 reads the information of the bar preceding the current bar (-1). The value 10 makes it possible to read the information of the tenth bar behind (-10) compared to the current bar, etc.
At the bottom of the DATAS table and label, lights, red, green or white indicate quickly summarize the trend from the various indicators.
Each light represents the number of indicators with the same trend at a given time.
Green for a bullish trend, red for a bearish trend and white for a neutral trend.
The conditions for determining a trend are for each indicator:
SUPERTREND ICHIMOHU + DMI: the 2 Super trends together are either bullish or bearish.
Otherwise the signal is neutral.
DMI: 2 main conditions:
BULLISH if DI+ >= DI- and ADX >25.
BEARISH if DI+ < DI- and ADX >25.
NEUTRAL if the 2 conditions are not met.
ICHIMOKU: 3 main conditions:
BULLISH if PRICE above the cloud and TENKAN > KIJUN and GREEN CLOUD AHEAD.
BEARISH if PRICE below the cloud and TENKAN < KIJUN and RED CLOUD AHEAD.
The other additional conditions (Data) complete the analysis and are present for informational purposes of the trend and depend on the context.
DONCHIAN CHANNEL: 1 main condition:
BULLISH: the price has crossed above the HIGH DC line.
BEARISH: the price has gone below the LOW DC line.
NEUTRAL if the price is between the HIGH DC and LOW DC lines
The 2 other complementary conditions (Datas) complete the analysis:
HIGH DC and LOW DC are increasing, falling or stable.
SUPERTREND HMA HULL: The script determines several trend levels:
STRONG BUY, BUY, STRONG SELL, SELL AND NEUTRAL.
VOLUME: 3 trend levels:
VOLUME > MOVING AVERAGE,
VOLUME < MOVING AVERAGE,
VOLUME = MOVING AVERAGE.
PRICE: 3 trend levels:
PRICE > MOVING AVERAGE,
PRICE < MOVING AVERAGE,
PRICE = MOVING AVERAGE.
If you are using this indicator/strategy and you are satisfied with the results, you can possibly make a donation (a coffee, a pizza or more...) via paypal to: lebourg.regis@free.fr.
Thanks in advance !!!
Have good winning Trades.
**************************************************************************************************************************
SUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL
by RegisL76 (lebourg.regis@free.fr)
Ce script est basé sur plusieurs indicateurs de tendance.
* ICHIMOKU (KINKO HYO)
* DMI (Directional Movement Index)
* SUPERTREND ICHIMOKU + SUPERTREND DMI
* DONCHIAN CANAL Optimized with Colored Bars
* HMA Hull
* Fair Value GAP
* VOLUME/ MA Volume
* PRIX / MA Prix
* HHLL BOXES
Toutes ces indications sont visibles simultanément sur un seul et même graphique.
Un tableau de données récapitule toutes les informations importantes pour prendre une bonne décision de Trade.
I- Indicateur ICHIMOKU :
L’indicateur ICHIMOKU est visualisé de manière traditionnelle
Les valeurs de réglage standard ICHIMOKU sont respectées mais modifiables. (Valeurs traditionnelles par défaut =
Un symbole visuel orienté, à proximité de la dernière valeur, indique la progression (Montant, Descendant ou neutre) de la TENKAN-SEN et de la KIJUN-SEN ainsi que la période utilisée.
Le NUAGE (KUMO) et la CHIKOU-SPAN sont bien présents et sont primordiaux pour l'analyse complète de l'ICHIMOKU.
En haut du graphique sont représentés visuellement les croisements de la TENKAN et de la KIJUN.
Des lignes verticales, accompagnées d'étiquettes, permettent de visualiser rapidement les particularités de l'ICHIMOKU.
Une ligne visualise la barre en cours.
Une ligne visualise l'extrémité du NUAGE (KUMO) qui est décalé de 25 barres dans le futur.
Une ligne visualise l'extrémité de la chikou-span, qui est décalée de 25 barres dans le passé.
II-DIRECTIONAL MOVEMENT INDEX (DMI)
Traité de manière conventionnelle : DI+, DI-, ADX et associé à un SUPERTREND DMI
Un symbole visuel en bas du graphique indique les croisements DI+ et DI-
Une ligne de symboles orientés et colorés (DMI Line) en haut du graphique, indique la direction et la puissance de la tendance.
III SUPERTREND ICHIMOKU + SUPERTREND DMI
Suivi de tendance par calcul SUPERTREND
IV- DONCHIAN CANAL :
Traité de manière conventionnelle.
(Et optimisé par des barres colorées en cas de dépassement soit vers le haut, soit vers le bas.
Les lignes, haute et basse des dernières valeurs du canal sont représentées pour visualiser rapidement la fourchette du RANGE.
V- SUPERTREND HMA (HULL)
Traité de manière conventionnelle.
La ligne HMA indique visuellement, selon la couleur et l'orientation, la tendance du marché.
Un symbole visuel en bas du graphique indique les opportunités de vente et d'achat.
*VI VOLUME :
Calcul de la MOYENNE MOBILE du volume avec comparaison du volume par rapport à la moyenne mobile du volume.
Les indications sont colorées et commentées en fonction de la comparaison.
*VII PRIX :
Calcul de la MOYENNE MOBILE du prix avec comparaison du prix par rapport à la moyenne mobile du prix.
Les indications sont colorées et commentées en fonction de la comparaison.
*VIII HHLL BOXES :
Visualise sous forme de boite, pour une période donnée, les valeurs max hautes et min basses du prix.
La configuration permet de prendre en compte les mèches hautes et basses du prix ou bien les valeurs d'ouverture et de fermeture.
IX - FAIR VALUE GAP
Cet indicateur affiche les niveaux de 'GAP' sur la période temporelle actuelle ET une période temporelle facultative supérieure.
Le script prend en compte les valeurs haut/bas de la barre actuelle et compare avec les 2 barres précédentes.
Le "gap" est généré à partir du manque de recouvrement entre ces barres.
Les écarts baissiers ou haussiers sont déterminés selon que l'écart est supérieurs ou inférieur à HmaPrice, car ils ont tendance à être comblés, et peuvent être utilisés comme cibles.
NOTA : FAIR VALUE GAP n'a pas de valeurs affichées dans la table et/ou l'étiquette.
Les informations importantes (DATAS) relatives à chaque indicateur sont visualisées en temps réel dans une table et/ou une étiquette.
Chaque information est commentée et colorée en fonction de la direction, de la valeur, de la comparaison etc.
Chaque information indique la valeurs de la barre en cours et la valeur précédente ( en mode "COMPLET").
Les autres modes possibles pour visualiser la table et/ou l'étiquette, permettent une vue plus synthétique des informations (modes "CONDENSÉ" et "MINIMAL").
Afin de ne pas trop surcharger la vision du graphique, la boite de visualisation du RANGE DONCHIAN, les lignes verticales des marques décalées de l'ICHIMOKU, ainsi que les boites de l'indicateur HHLL Boxes ne sont visualisées que de manière intermittente (géré par une temporisation réglable ).
Le paramètre de configuration "HISTORICAL INFO READING" réglé sur zéro (par défaut) permet de lire toutes les informations de la barre actuelle en cours (Barre #0).
Toutes autres valeurs permet de lire les informations d'une barre historique. La valeur 1 permet de lire les informations de la barre précédant la barre en cours (-1).
La valeur 10 permet de lire les information de la dixième barre en arrière (-10) par rapport à la barre en cours, etc.
Dans le bas de la table et de l'étiquette de DATAS, des voyants, rouge, vert ou blanc indique de manière rapide la synthèse de la tendance issue des différents indicateurs.
Chaque voyant représente le nombre d'indicateur ayant la même tendance à un instant donné. Vert pour une tendance Bullish, rouge pour une tendance Bearish et blanc pour une tendance neutre.
Les conditions pour déterminer une tendance sont pour chaque indicateur :
SUPERTREND ICHIMOHU + DMI : les 2 Super trends sont ensemble soit bullish soit Bearish. Sinon le signal est neutre.
DMI : 2 conditions principales :
BULLISH si DI+ >= DI- et ADX >25.
BEARISH si DI+ < DI- et ADX >25.
NEUTRE si les 2 conditions ne sont pas remplies.
ICHIMOKU : 3 conditions principales :
BULLISH si PRIX au dessus du nuage et TENKAN > KIJUN et NUAGE VERT DEVANT.
BEARISH si PRIX en dessous du nuage et TENKAN < KIJUN et NUAGE ROUGE DEVANT.
Les autres conditions complémentaires (Datas) complètent l'analyse et sont présents à titre informatif de la tendance et dépendent du contexte.
CANAL DONCHIAN : 1 condition principale :
BULLISH : le prix est passé au dessus de la ligne HIGH DC.
BEARISH : le prix est passé au dessous de la ligne LOW DC.
NEUTRE si le prix se situe entre les lignes HIGH DC et LOW DC
Les 2 autres conditions complémentaires (Datas) complètent l'analyse : HIGH DC et LOW DC sont croissants, descendants ou stables.
SUPERTREND HMA HULL :
Le script détermine plusieurs niveaux de tendance :
STRONG BUY, BUY, STRONG SELL, SELL ET NEUTRE.
VOLUME : 3 niveaux de tendance :
VOLUME > MOYENNE MOBILE, VOLUME < MOYENNE MOBILE, VOLUME = MOYENNE MOBILE.
PRIX : 3 niveaux de tendance :
PRIX > MOYENNE MOBILE, PRIX < MOYENNE MOBILE, PRIX = MOYENNE MOBILE.
Si vous utilisez cet indicateur/ stratégie et que vous êtes satisfait des résultats,
vous pouvez éventuellement me faire un don (un café, une pizza ou plus ...) via paypal à : lebourg.regis@free.fr.
Merci d'avance !!!
Ayez de bons Trades gagnants.
No Active BarThis is probably the only script on TradingView that's clinically proven to lower your blood pressure!***
This script in conjunction with some chart settings changes can completely hide the active candle, only showing historic candles, thus, reducing risk of cardiac arrest and or panic attack.
What to do:
0. Make sure you are using a candlestick chart or this script won't work properly
1. Right click the chart and select "Settings..."
2. Select "Symbol" under the "Chart Settings" menu
3. Disable every item EXCEPT for the "Body"
4. Click on the boxes next to "Body" to access the color picker then change both box's transparency settings down to 0
(the script only colors closed bars, so the active bar will be present just transparent)
5. Right click on the price scale on the far left or far right side of the screen and hover the mouse over "Labels". If any selections have a check mark next to them click them to disable them (especially the "Ask & Bid" price setting since it tracks current price)
That's it! Instead of wicks the High & Low prices are plotted above and below the candles using a step line. It looks a bit strange at first but you'll get used to it. Check out the indicator settings to change the color and style of the High & Low lines.
***The statement could prove true for some but is mostly complete bullshit
Level 1 - Learn to code simply - PineScriptThe goal of this script is honestly to help everyone learn about trading with bots and algos.
At least, to get started.
Level 1:
10 lines of code.
learn to plot 2 moving averages on your chart.
learn to create a signal from a crossover.
learn the very basics of Pine Script algo.
SymMatrixTableSimple Example Table for Displaying Price, RSI, Volume of multiple Tickers on selected Timeframe
Displays Price, RSI and Volume of 3 Tickers and Timeframe selected by user input
Conditional Table Cell coloring
Price color green if > than previous candle close and red if < previous candle close
RSI color green if < 30 and red if > 70 (RSI14 by default)
Volume color green if above average volume and red if less than that (SMA20 volume by default)
Can turn on/off whole table, header columns, row indices, or select individual columns or rows to show/hide
// Example Mixed Type Matrix To Table //
access the simple example script by uncommenting the code at the end
Basically I wanted to have the headers and indices as strings and the rest of the matrix for the table body as floats, then conditional coloring on the table cells
And also the functionality to turn rows and columns on/off from table through checkboxes of user input
Before I was storing each of the values separately in arrays that didn't have a centralized way of controlling table structure
so now the structure is :
- string header array, string index array
- float matrix for table body
- color matrix with bool conditions for coloring table cells
- bool checkboxes for controlling table display
Study forloop Star Triangle'Study forloop' pinescript Program to print star Triangle
The Program Logic
For example, the following Pinescript programme will need two nested for loops. The outer forloop is for rows and the inner forloop is for columns or stars. to create a triangle shape.
Invisible FriendLooking into a question from user Alex100, i realized many people do want some kind of values displayed on chart when they hover the mouse over different bars.
As pinescript does not have any feature like pop up box, the only way is to plot a line and than see indicator values at top left. So when mouse is moved around the value displayed changes. As we just need the value, we do not want to clutter the chart with another line.
Using display.none will hide the value from indicator value also
Using color.white will also color the indicator value to white, making it invisible
So the solution is very simple, and requires a bit of creativity. We create an invisible line, in any color we like :)
This indicator is a tutorial on how to display indicator values without the line showing up and also this can be implemented as displaying data for each bar on mouse hover.
-----
Check My Public Creations In The Meantime:
Buy Monday Exit Tuesday with StopLoss and TakeProfit
Close Combination Lock Style Visual Appeal Indicator
High-Low Box between Earnings with ability to Add Custom Boxes
EMA Cross + Divergence strategy (Div. signals by The Divergent)A sample strategy demonstrating the usage of The Divergent divergence indicator and The Divergent Library .
The Divergent is an advanced divergence indicator which you can easily incorporate into your own strategies.
In order to use this strategy (and to use the signals in your own strategy), you need to have the Pro version of The Divergent applied to your chart.
For more information, please see the comments inlined in the code.
The Divergent LibraryLibrary "TheDivergentLibrary"
The Divergent Library is only useful when combined with the Pro version of The Divergent - Advanced divergence indicator . This is because the Basic (free) version of The Divergent does not expose the "Divergence Signal" value.
Usage instructions:
1. Create a new chart
2. Add The Divergent (Pro) indicator to your chart
3. Create a new strategy, import this library, add a "source" input, link it to "The Divergent: Divergence Signal", and use the library to decode the divergence signals from The Divergent (You can find example strategy code published in our profile)
4. Act on the divergences signalled by The Divergent
---
isRegularBullishEnabled(context) Returns a boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bullish divergence detection is enabled in The Divergent.
isHiddenBullishEnabled(context) Returns a boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bullish divergence detection is enabled in The Divergent.
isRegularBearishEnabled(context) Returns a boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Regular Bearish divergence detection is enabled in The Divergent.
isHiddenBearishEnabled(context) Returns a boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating whether Hidden Bearish divergence detection is enabled in The Divergent.
getPivotDetectionSource(context) Returns the 'Pivot Detection Source' setting of The Divergent. The returned value can be either "Oscillator" or "Price".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Oscillator" or "Price".
getPivotDetectionMode(context) Returns the 'Pivot Detection Mode' setting of The Divergent. The returned value can be either "Bodies" or "Wicks".
Parameters:
context : The context of The Divergent Library.
Returns: One of the following string values: "Bodies" or "Wicks".
isLinked(context) Returns a boolean value indicating the link status to The Divergent indicator.
Parameters:
context : The context of The Divergent Library.
Returns: A boolean value indicating the link status to The Divergent indicator.
init(firstBarSignal, displayLinkStatus, debug) Initialises The Divergent Library's context with the signal produced by The Divergent on the first bar. The value returned from this function is called the "context of The Divergent Library". Some of the other functions of this library requires you to pass in this context.
Parameters:
firstBarSignal : The signal from The Divergent indicator on the first bar.
displayLinkStatus : A boolean value indicating whether the Link Status window should be displayed in the bottom left corner of the chart. Defaults to true.
debug : A boolean value indicating whether the Link Status window should display debug information. Defaults to false.
Returns: A bool array containing the context of The Divergent Library.
processSignal(signal) Processes a signal from The Divergent and returns a 5-tuple with the decoded signal: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd]. `divergenceType` can be one of the following values: na → No divergence was detected, 1 → Regular Bullish, 2 → Regular Bullish early, 3 → Hidden Bullish, 4 → Hidden Bullish early, 5 → Regular Bearish, 6 → Regular Bearish early, 7 → Hidden Bearish, 8 → Hidden Bearish early.
Parameters:
signal : The signal from The Divergent indicator.
Returns: A 5-tuple with the following values: [ int divergenceType, int priceBarIndexStart, int priceBarIndexEnd, int oscillatorBarIndexStart, int oscillatorBarIndexEnd].
Sentiment Estimator [AstrideUnicorn]Sentiment Estimator is an indicator that estimates market sentiment using only its pricing data. It counts bullish and bearish candles in a rolling window and calculates their relative values as percentages of the total amount of candles in the window. Market sentiment shows the direction in which the market is biased to move or the current trend direction. Extreme values of the market sentiment are contrarian signals. When the market sentiment is too bullish, it is time to sell and vice versa.
HOW TO USE
Sentiment Estimator plots a pair of green and red circles for each candle. They represent bullish and bearish sentiments, respectively.
The vertical positions of the circles show corresponding sentiment values in percentage units. For example, if a green circle's height is 60, the market is 60% bullish. In this case, the red circle's height will be 40, as bullish and bearish parts of the market sentiment sum to 100%.
The blue line plotted at the 50% level shows the neutral sentiment level. If a green circle is above the blue line, the prevailing market sentiment at that time is bullish, and the market is biased to move up. If a red one is above, the market has predominantly bearish sentiment and is prone to move down.
The red level shows extreme sentiment level. If a green or red circle is above this line, it means that the market is extremely bullish or bearish, respectively. It is a contrarian signal, and one can expect a reversal soon. In this case, a blue label with the text "reversal expected" is shown.
SETTINGS
Timeframe - allows choosing a timeframe other than the chart's one for the indicator calculation.
Look-Back Window - sets the historical window length used to perform the calculations. You can adjust the window to get the best results for a particular market or timeframe.
RKs Notepad++ Pine Script V5█ OVERVIEW
After reading all the new names and renames that Pine Script V5 brought to us, I knew that my old Notepad++ User Defined Language (UDL) would need a big update, so I decided to do a complete remake using the same Dark color scheme theme of the Pine Editor.
Then, I create a Notepad++ Theme and the Auto-Completion file with the Parameter hints for every built-in function to make everything look nicer
█ IMPORTANT
This is not an indicator!!
These are 3 XML files to copy and paste inside the Notepad++ folder.
You can use any Notepad Software to create the XML files.
The main Notepad++ folder is normally on %AppData%\Notepad++\
To avoid mistakes, always make a Backup of your files before anything.
█ INSTALLATION
Just follow these steps:
1. open a New Document File;
2. Copy everything between ↓↓↓ and ↑↑↑ symbols to this new document;
3. Remove the "//" of every single line;
4. Save each document with the correct name in the right folder;
5. Restart the Notepad++
█ NOTES:
If you have some problem installing, ask me, and I will try to help you.
But, in any case, here is the link to these files on my GitHub:
2 Dimensional Array using one floating point entry This is an attempt to create a two dimensional floating point array from the pine single dimension array.
It enables some useful array functions like sorting, when you are trying to keep track of price and location in time or bars and you would like to sort the array.
Other array functions on this array will not work, like average and other statistical functions - they will provide bad results. I would suggest continuing to use a single dimensional array for each element where that kind of array function is required.
I wrote this simply as a mean of using the sort functions when I had to sort price and try to keep the bar location or time in synch.
Other array functions could be written to manipulate this kind of array, leave that to others. The goal here was to avoid using for loops which would be a performance impact on large arrays.
The basic concept is to create one floating point number from two, put that into an array, and then be able to pull the compound value out and parse out the individual components.
I imagine it could also accommodate a 3 or 4 dimensional array with some work, as long as you had some idea of how many digits are consumed by each element. For example you may be interested in storing price, RSI, x_loc values and then be able to sort and parse them out.
Indicator PanelHello All,
This script shows Indicator panel in a Table. Table.new() is a new feature and released today! Thanks a lot to Pine Team to add this new great feature! This new feature is a game changer!
The script shows indicator values for each symbol and changes background color of each cell by using current and last values of the indicators for each symbol. if current value is greater than last value then backgroung color is green, if lower than last value then red, if they are equals then gray.
You can choose the indicators to display. Number of columns in the table is dynamic and is changed by number of the indicators.
You can choose 5 different Symbols, 6 Indicators and 2 Simple or Exponential Moving averages, you can set type of moving averages and the lengths. You can also set the lengths for each Indicators.
Indicators:
- RSI
- MACD ( MACD and Signal and Histogram )
- DMI ( +DI and -DI + and ADX )
- CCI
- MFI
- Momentum
- MA with Length 50 (length can be set)
- MA with Length 200 (length can be set)
In this example RSI, MACD and MA 200 were chosen, you can see how table size changes dynamically:
Enjoy!
Dead Simple - 3 greens or 3 reds each bigger than the last High probability reversal pattern best used for scalping on lower time frame charts like the 15 second chart. very basic script for those just starting to learn pine
Pinescript - Common Label & Line Array Functions Library by RRBPinescript - Common Label & Line Array Functions Library by RagingRocketBull 2021
Version 1.0
This script provides a library of common array functions for arrays of label and line objects with live testing of all functions.
Using this library you can easily create, update, delete, join label/line object arrays, and get/set properties of individual label/line object array items.
You can find the full list of supported label/line array functions below.
There are several libraries:
- Common String Functions Library
- Standard Array Functions Library
- Common Fixed Type Array Functions Library
- Common Label & Line Array Functions Library
- Common Variable Type Array Functions Library
Features:
- 30 array functions in categories create/update/delete/join/get/set with support for both label/line objects (45+ including all implementations)
- Create, Update label/line object arrays from list/array params
- GET/SET properties of individual label/line array items by index
- Join label/line objects/arrays into a single string for output
- Supports User Input of x,y coords of 5 different types: abs/rel/rel%/inc/inc% list/array, auto transforms x,y input into list/array based on type, base and xloc, translates rel into abs bar indexes
- Supports User Input of lists with shortened names of string properties, auto expands all standard string properties to their full names for use in functions
- 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: hide all excluded and show only allowed functions using a list of function names
- Output Panel customization options: set custom style, color, text size, and line spacing
Usage:
- select create function - create label/line arrays from lists or arrays (optional). Doesn't affect the update functions. The only change in output should be function name regardless of the selected implementation.
- specify num_objects for both label/line arrays (default is 7)
- specify common anchor point settings x,y base/type for both label/line arrays and GET/SET items in Common Settings
- fill lists with items to use as inputs for create label/line array functions in Create Label/Line Arrays section
- specify label/line array item index and properties to SET in corresponding sections
- select label/line SET function to see the changes applied live
Code Structure:
- translate x,y depending on x,y type, base and xloc as specified in UI (required for all functions)
- expand all shortened standard property names to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- create param arrays from string lists (required for create/update* from arrays and set* functions, not needed for create/update* from lists)
- create label/line array from string lists (property names are auto expanded) or param arrays (requires already expanded properties)
- update entire label/line array or
- get/set label/line array item properties by index
Transforming/Expanding Input values:
- for this script to work on any chart regardless of price/scale, all x*,y* are specified as % increase relative to x0,y0 base levels by default, but user can enter abs x,price values specific for that chart if necessary.
- all lists can be empty, contain 1 or several items, have the same/different lengths. Array Length = min(min(len(list*)), mum_objects) is used to create label/line objects. Missing list items are replaced with default property values.
- when a list contains only 1 item it is duplicated (label name/tooltip is also auto incremented) to match the calculated Array Length
- since this script processes user input, all x,y values must be translated to abs bar indexes before passing them to functions. Your script may provide all data internally and doesn't require this step.
- at first int x, float y arrays are created from user string lists, transformed as described below and returned as x,y arrays.
- translated x,y arrays can then be passed to create from arrays function or can be converted back to x,y string lists for the create from lists function if necessary.
- all translation logic is separated from create/update/set functions for the following reasons:
- to avoid redundant code/dependency on ext functions/reduce local scopes and to be able to translate everything only once in one place - should be faster
- to simplify internal logic of all functions
- because your script may provide all data internally without user input and won't need the translation step
- there are 5 types available for both x,y: abs, rel, rel%, inc, inc%. In addition to that, x can be: bar index or time, y is always price.
- abs - absolute bar index/time from start bar0 (x) or price (y) from 0, is >= 0
- rel - relative bar index/time from cur bar n (x) or price from y0 base level, is >= 0
- rel% - relative % increase of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc - relative increment (step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- inc% - relative % increment (% step) for each new level of bar index/time (x) or price (y) from corresponding base level (x0 or y0), can be <=> 0
- x base level >= 0
- y base level can be 0 (empty) or open, close, high, low of cur bar
- single item x1_list = "50" translates into:
- for x type abs: "50, 50, 50 ..." num_objects times regardless of xloc => x = 50
- for x type rel: "50, 50, 50 ... " num_objects times => x = x_base + 50
- for x type rel%: "50%, 50%, 50% ... " num_objects times => x_base * (1 + 0.5)
- for x type inc: "0, 50, 100 ... " num_objects times => x_base + 50 * i
- for x type inc%: "0%, 50%, 100% ... " num_objects times => x_base * (1 + 0.5 * i)
- when xloc = xloc.bar_index each rel*/inc* value in the above list is then subtracted from n: n - x to convert rel to abs bar index, values of abs type are not affected
- x1_list = "0, 50, 100, ..." of type rel is the same as "50" of type inc
- x1_list = "50, 50, 50, ..." of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "50"
- single item y1_list = "2" translates into (ragardless of yloc):
- for y type abs: "2, 2, 2 ..." num_objects times => y = 2
- for y type rel: "2, 2, 2 ... " num_objects times => y = y_base + 2
- for y type rel%: "2%, 2%, 2% ... " num_objects times => y = y_base * (1 + 0.02)
- for y type inc: "0, 2, 4 ... " num_objects times => y = y_base + 2 * i
- for y type inc%: "0%, 2%, 4% ... " num_objects times => y = y_base * (1 + 0.02 * i)
- when yloc != yloc.price all calculated values above are simply ignored
- y1_list = "0, 2, 4" of type rel% is the same as "2" with type inc%
- y1_list = "2, 2, 2" of type abs/rel/rel% produces a sequence of the same values and can be shortened to just "2"
- you can enter shortened property names in lists. To lookup supported shortened names use corresponding dropdowns in Set Label/Line Array Item Properties sections
- all shortened standard property names must be expanded to full names (required for create/update* from arrays and set* functions, not needed for create/update* from lists) to prevent errors in label.new and line.new
- examples of shortened property names that can be used in lists: bar_index, large, solid, label_right, white, left, left, price
- expanded to their corresponding full names: xloc.bar_index, size.large, line.style_solid, label.style_label_right, color.white, text.align_left, extend.left, yloc.price
- all expanding logic is separated from create/update* from arrays and set* functions for the same reasons as above, and because param arrays already have different types, implying the use of final values.
- all expanding logic is included in the create/update* from lists functions because it seemed more natural to process string lists from user input directly inside the function, since they are already strings.
Creating Label/Line Objects:
- use study max_lines_count and max_labels_count params to increase the max number of label/line objects to 500 (+3) if necessary. Default number of label/line objects is 50 (+3)
- all functions use standard param sequence from methods in reference, except style always comes before colors.
- standard label/line.get* functions only return a few properties, you can't read style, color, width etc.
- label.new(na, na, "") will still create a label with x = n-301, y = NaN, text = "" because max default scope for a var is 300 bars back.
- there are 2 types of color na, label color requires color(na) instead of color_na to prevent error. text_color and line_color can be color_na
- for line to be visible both x1, x2 ends must be visible on screen, also when y1 == y2 => abs(x1 - x2) >= 2 bars => line is visible
- xloc.bar_index line uses abs x1, x2 indexes and can only be within 0 and n ends, where n <= 5000 bars (free accounts) or 10000 bars (paid accounts) limit, can't be plotted into the future
- xloc.bar_time line uses abs x1, x2 times, can't go past bar0 time but can continue past cur bar time into the future, doesn't have a length limit in bars.
- xloc.bar_time line with length = exact number of bars can be plotted only within bar0 and cur bar, can't be plotted into the future reliably because of future gaps due to sessions on some charts
- xloc.bar_index line can't be created on bar 0 with fixed length value because there's only 1 bar of horiz length
- it can be created on cur bar using fixed length x < n <= 5000 or
- created on bar0 using na and then assigned final x* values on cur bar using set_x*
- created on bar0 using n - fixed_length x and then updated on cur bar using set_x*, where n <= 5000
- default orientation of lines (for style_arrow* and extend) is from left to right (from bar 50 to bar 0), it reverses when x1 and x2 are swapped
- price is a function, not a line object property
Variable Type Arrays:
- 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
- create_any_array2 uses this loophole to return an int_arr pointer of a var type array
- this works for all array types defined with/without var keyword and doesn't work for string arrays defined with var keyword for some reason
- you can't do this with var type vars, only var type arrays because arrays are pointers passed by reference, while vars are actual values passed by value.
- 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 type result
- get_var_types solves this problem by generating a list of dummy values of every possible type including the source type, tricking the compiler into allowing a single valid branch to execute without error, while ignoring all dummy results
Notes:
- uses Pinescript v3 Compatibility Framework
- uses Common String Functions Library, Common Fixed Type Array Functions Library, Common Variable Type Array Functions Library
- has to be a separate script to reduce the number of local scopes/compiled file size, can't be merged with another library.
- lets you live test all label/line array functions for errors. If you see an error - change params in UI
- if you see "Loop too long" error - hide/unhide or reattach the script
- if you see "Chart references too many candles" error - change x type or value between abs/rel*. This can happen on charts with 5000+ bars when a rel bar index x is passed to label.new or line.new instead of abs bar index n - x
- create/update_label/line_array* use string lists, while create/update_label/line_array_from_arrays* use array params to create label/line arrays. "from_lists" is dropped to shorten the names of the most commonly used functions.
- create_label/line_array2,4 are preferable, 5,6 are listed for pure demonstration purposes only - don't use them, they don't improve anything but dramatically increase local scopes/compiled file size
- for this reason you would mainly be using create/update_label/line_array2,4 for list params or create/update_label/line_array_from_arrays2 for array params
- all update functions are executed after each create as proof of work and can be disabled. Only create functions are required. Use update functions when necessary - when list/array params are changed by your script.
- both lists and array item properties use the same x,y_type, x,y_base from common settings
- doesn't use pagination, a single str contains all output
- why is this so complicated? What are all these functions for?
- this script merges standard label/line object methods with standard array functions to create a powerful set of label/line object array functions to simplify manipulation of these arrays.
- this library also extends the functionality of Common Variable Type Array Functions Library providing support for label/line types in var type array functions (any_to_str6, join_any_array5)
- creating arrays from either lists or arrays adds a level of flexibility that comes with complexity. It's very likely that in your script you'd have to deal with both string lists as input, and arrays internally, once everything is converted.
- processing user input, allowing customization and targeting for any chart adds a whole new layer of complexity, all inputs must be translated and expanded before used in functions.
- different function implementations can increase/reduce local scopes and compiled file size. Select a version that best suits your needs. Creating complex scripts often requires rewriting your code multiple times to fit the limits, every line matters.
P.S. Don't rely too much on labels, for too often they are fables.
List of functions*:
* - functions from other libraries are not listed
1. Join Functions
Labels
- join_label_object(label_, d1, d2)
- join_label_array(arr, d1, d2)
- join_label_array2(arr, d1, d2, d3)
Lines
- join_line_object(line_, d1, d2)
- join_line_array(arr, d1, d2)
- join_line_array2(arr, d1, d2, d3)
Any Type
- any_to_str6(arr, index, type)
- join_any_array4(arr, d1, d2, type)
- join_any_array5(arr, d, type)
2. GET/SET Functions
Labels
- label_array_get_text(arr, index)
- label_array_get_xy(arr, index)
- label_array_get_fields(arr, index)
- label_array_set_text(arr, index, str)
- label_array_set_xy(arr, index, x, y)
- label_array_set_fields(arr, index, x, y, str)
- label_array_set_all_fields(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
- label_array_set_all_fields2(arr, index, x, y, str, xloc, yloc, label_style, label_color, text_color, text_size, text_align, tooltip)
Lines
- line_array_get_price(arr, index, bar)
- line_array_get_xy(arr, index)
- line_array_get_fields(arr, index)
- line_array_set_text(arr, index, width)
- line_array_set_xy(arr, index, x1, y1, x2, y2)
- line_array_set_fields(arr, index, x1, y1, x2, y2, width)
- line_array_set_all_fields(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
- line_array_set_all_fields2(arr, index, x1, y1, x2, y2, xloc, extend, line_style, line_color, width)
3. Create/Update/Delete Functions
Labels
- delete_label_array(label_arr)
- create_label_array(list1, list2, list3, list4, list5, d)
- create_label_array2(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array3(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array4(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array5(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array6(x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array2(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- update_label_array4(label_arr, x_list, y_list, str_list, xloc_list, yloc_list, style_list, color1_list, color2_list, size_list, align_list, tooltip_list, d)
- create_label_array_from_arrays2(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- create_label_array_from_arrays4(x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
- update_label_array_from_arrays2(label_arr, x_arr, y_arr, str_arr, xloc_arr, yloc_arr, style_arr, color1_arr, color2_arr, size_arr, align_arr, tooltip_arr, d)
Lines
- delete_line_array(line_arr)
- create_line_array(list1, list2, list3, list4, list5, list6, d)
- create_line_array2(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array3(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array4(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array5(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array6(x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array2(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- update_line_array4(line_arr, x1_list, y1_list, x2_list, y2_list, xloc_list, extend_list, style_list, color_list, width_list, d)
- create_line_array_from_arrays2(x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
- update_line_array_from_arrays2(line_arr, x1_arr, y1_arr, x2_arr, y2_arr, xloc_arr, extend_arr, style_arr, color_arr, width_arr, d)
Product function for ArraysHello,
This code may be useful for Pine script coders only.
Arrays were welcomed in Pine script, as they are a foundation for coding properly many useful things, like studies and strategies here in TradingView :)
TradingView recently released new functions for arrays, like array.median and more, but the "PRODUCT" function was still missing, so I created it. I've no doubt that array.product() will soon be proposed by the platform, but for the time being, one can use mine.
It does the same thing as the PRODUCT() function in Excel : it multiplies all the source values included in the specified lookback, and returns the product. This function can accept Series or Arrays as source input.
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)
FCMS - Arrays Exercise - High Low with Arrays - StudyThis is just a script to exercise the use of arrays on pine script.
I think we could say that every for loop we had in pine script before the arrays, is eligible to become an array.
Our script will get more efficient and more reliable.
As every "if" case is elegible to became a function
I confess I was addicted to use if, else if, else in my codes, but recently i've been updating my scripts and it's became more efficient
I couldn't find an array function that insert an value removing the oldest one, so I'm using this condition to "shift" the first value.
I'll update as soon as I find a better way to do it.
In any case, for this specific goal, we already have an built in function, as I let on script
Joined and Sliced String ArrayUsing the new Pine Script array built-ins to join string elements together for label text. The array is sliced to remove extraneous elements.
Simple Truncation FunctionMain utility: legibility in alerts where certain values are not truncated.
It may prove helpful if tostring() is unavailable for use as well.