Position Tool█   OVERVIEW 
This script is an interactive measurement tool that can be used to evaluate or keep track of trades. Like the long and short position drawing tools, it calculates a risk reward ratio and a risk-adjusted position size from the entry, stop and take profit levels, but it also does much more:
 • It can be used to configure long or short trades.
 • All monetary values can be expressed in any number of currencies.
 • The value of tick/pip movement (which varies with the position's size) is displayed in the currency you have selected.
 • The CAGR ( Compound Annual Growth Rate ) for the trade can be displayed.
 • It does live tracking of the position.
 • You can configure alerts on entries and exits.
█  HOW TO USE IT 
Load the indicator on an active chart (see  here  if you don't know how).
When you first load this script on a chart, you will enter an interactive selection mode where the script asks you to pick three points in price and time on your chart by clicking on the chart. Directions will appear in a blue box at the bottom of the screen with each click of the mouse. The first selection is the entry point for the trade you are considering, which takes into account both the time and level you choose, the next are the take profit and stop levels. Once you have selected all three points, the script will draw trade zones and labels containing the trade metrics. The script determines if the trade is a long or short from the position of the take profit and stop loss levels in relation to the entry price. If the take profit level is above the entry price, the stop must be below and vice versa, otherwise an error occurs.
You can change levels by dragging the handles that appear when you select the indicator, or by entering new values in the script's settings. The only way to re-enter interactive mode is to re-add the indicator to your chart.
Once you place the position tool on a chart, it will appear at the same levels on all symbols you use. If your scale is not set to "Scale price chart only", the position tool's levels will be taken into account when scaling the chart, which can cause the symbol's bars to be compressed. If your scale is set to "Scale price chart only", the position tool will still be there, but it will not impact the scale of the chart's bars, so you won't see it if it sits outside the symbol's price scale.
If you select the position tool on your chart and delete it, this will also delete the indicator from the chart. You will need to re-add it if you want to draw another position tool. You can add multiple instances of the indicator if you need a position tool on more than one of your charts.
█   FEATURES 
 Display 
The position tool displays the following information for entries:
 • The entry's price level with an '@' sign before it.
 •  Open or Closed P&L : For an open trade, the "Open P&L" displays the difference in money value between the entry level and the chart's current price. 
  For a closed trade, the "Closed P&L" displays the realized P&L on the trade.
 •  Quantity : The trade size, which takes into account the risk tolerance you set in the script's settings.
 •  RR : The reward to risk ratio expresses the relationship of the distance between the entry and the take profit level vs the entry and the stop level.
  Example: A $100 stop with a $100 target will have a ratio of 1:1, whereas a $200 target with the same stop will have a 2:1 ratio.
 •  Per tick/pip : Represents the money value of a tick or pip movement.
 •  CAGR : The Compound Annual Growth Rate will be displayed on the main order label on trades that exceed one day in duration. 
  This value is calculated the same way as in our  CAGR Custom Range  indicator. 
  If the trade duration is less than one day, the metric will not be present in the display.
The stop and take profit levels display:
 • Their price level with an '@' sign before it.
 • Their distance from the entry in money value, percentage and ticks/pips.
 • The projected end money value of the position if the level is reached. These values are calculated based on the trade size and the currency.
 Currency adjustments 
This indicator modifies the trade label's colors and values based on the final Profit and Loss (P&L), which considers the dynamic exchange rate between base and conversion currencies in its calculations when the conversion currency is a specified value other than the default. Depending on the cross rate between the base and account currencies, this process can yield a negative P&L on an otherwise successful simulated trade.
For instance, if your account is in currency XYZ, you might buy 10 Apple shares at $150 each, with the XYZ to USD exchange rate being 2:1. This purchase would cost you 3000 units of XYZ. Suppose that later on, the shares appreciate to $170 each, and you decide to sell. One might expect this trade to result in profit. However, if the exchange rate has now equalized to 1:1, the return on selling the shares, calculated in XYZ, would only be 1700 units, resulting in a loss of 1300 units XYZ.
The indicator will mark the P&L and the target labels in red in such cases, regardless of whether the market price reached the profit target, as the trade produced a net loss due to reduced funds after currency conversion. Conversely, an otherwise unsuccessful position can result in a net profit in the account currency due to conversion rate fluctuations. The final losses or gains appear in the label metrics, and the corresponding color coding reflects the trade's success or failure.
 Settings 
The settings in the "Trade sizing" section are used to calculate the position size and the monetary value of trades. Two types of risk can be chosen from the menu; a percentage based risk calculation, or a fixed money value. The risk is used to calculate the quantity of units to purchase to achieve that level of risk exposure. Example: An account size of $1000 and 10% risk will have a projected end amount of $900 if the stop loss is hit. The quantity is a product of this relationship; a projected number of units to allow for the equivalent of $100 of risk exposure over the change in price from the entry to the stop value.
The "Trade levels" allow you to manually set the entry, take profit and stop levels of an existing position tool on your chart.
You can control the appearance of the tool and the values it displays in the settings following these first two sections.
 Alerts 
Three alerts that will trigger when you configure an alert on this indicator. The first will send an alert when the entry price is breached by price action if that price has not already been breached in the previous price history. This is dependant on the entry location you select when placing the indicator on the chart. The other two alerts will trigger when either the stop loss or the take profit level is breached to signal that a trade exit has occurred. 
█   NOTES FOR Pine Script™ CODERS 
 • Interactive inputs are implemented for  input.time()  and  input.price() . These specialized input functions allow users to interact with a script. 
  You can create one interactive input for both time and price values by using the same `inline` argument in a pair of  input.time()  and  input.price()  function calls.
 • We use the `cagr()` function from our  ta  library.
 • The script uses the  runtime.error()  function to throw an error if the stop and limit prices are not placed on opposing sides of the entry price.
 • We use the `currency` parameter in a  request.security()  call to convert currencies.
 Look first. Then leap.  
Cari dalam skrip untuk "one一季度财报"
Trend/Retracement - ZigZag - New wayZigZag  for Trend and Retracements -  New way 
It's another way to plot ZigZag based on lookback period for trend and % of trend lookback period to plot retracements.
█   OVERVIEW  
Plot ZigZag, Trend lines, Retracements, Support levels, Resistance levels
█  Objective: 
Draw ZigZag lines along with unbroken support and resistance levels. ZigZag lines are drawn for main trend and the retracements.
Main Trend – This is calculated based on lookback period. 
Retracements – Retracements are calculated as 25% of main trend.
Support and Resistance line: The indicator draws 2 types of support and resistance lines
    1.	Un-broken – Once formed (plotted), these are the support and resistance which are not yet broken
    2.	Tested – One can also choose to see support and resistance lines which are tested but not broken. Tested support/resistance are those levels which are touched by high/low price but close price has not crossed the level.
█  How main trend point is calculated: 
E.g.
Chart timeframe = 15m 
Lookback period  = 250 
Retracement = 25% of main trend ( 25% of 250 = 62 )
A price point on a chart is considered as trend point if distance between current price and previous highest price is 250 candles
A price point is considered as a retracement if distance between current price and previous highest price is 62 candles. Please note retracements are calculated only after finding a main trend point. 
█  Input parameters: 
 Zigzag Parameters  
 
     Use predefined Lookback – If checked pre-defined timeframe-based lookback parameters are used. 
     Trend lookback candles – If ‘Use predefined Lookback’ is unchecked then this value is used as lookback period.
     Retracement % of look back candles– If ‘Use predefined Lookback’ is unchecked then this value is used for calculating retracement lookback period
     Mark retracements – If unchecked only main trend lines are plotted
     Plot support/resistance – To plot support/resistance levels
     Show support/resistance tested lines – If checked tested support/resistance liens are shown on the chart
 
█  TF based Lookback period config   (Defaults are set as specified below, One can change these defaults to use different lookback periods)
The defaults set here are used based on the chart timeframe.  e.g. if chart timeframe is changed from say 15m to 60m then 60m chart defaults (i.e. trend lookback = 90) are used to plot the trend and the retracements. At the bottom-right of the chart, parameters used for plotting are displayed all the time.
 
     Timeframe in minute – Default = 5m
     Trend lookback candles – Default = 375 (~ 5 days of data)
 
     Timeframe in minute – Default = 15m
     Trend lookback candles – Default = 250 (~10 days of data)
     Timeframe in minute – Default = 60m
     Trend lookback candles = Default = 90 (~ 15 days of data)
     Trend lookback candles for timeframe 'D' – Default =  30 (~1 month data)
     Trend lookback candles for timeframe 'W' – Default = 21 (~6 months data)
     Trend lookback candles for timeframe 'M' – Default = 12 (~1year data)
     Retracement % of look back candles – Default = 25%
 
█  When and where one can use this indicator (Refer to chart examples) 
 
       To view support and resistance based on lookback period
       To view ZigZag lines
       One can use it to find chart patterns easily 
       Trend and retracement lines can help in drawing Elliott waves.
 
█ Chart examples: 
1. Chart patterns can be easily identified - One can disable the candle charts which will help to identify and draw chart patterns easily
  
2. Trend and retracement lines can also help is analyzing charts (e.g. Elliott Waves can be marked based on trend lines)
  
3. Tested but not broken support and resistance lines can be viewed
  
4. You can select 'NOT' to plot tested support and resistance lines
  
5. Uncheck  the Mark retracements to plot main trend lines (Retracements are not marked)
  
two_leg_spread_diffThis script helps you discern the relative change of each leg in a two-legged spread over a given period. The main plot is a difference in log return over the number of bars identified by the "lag" parameter. E.g. if "lag" is 10 and leg one has increased 3% over the past ten bars, while leg two has only increased 1%, the plot value is 2%. The main plot is also colored blue when leg one increases while leg two decreases on a given bar, and red if the opposite is true. This feature identifies periods where the correlation between the two legs diminishes. The one and two standard deviation of the main plot is also plotted in faint background lines. Additionally, a table indicates the percentage in which the main plot is within one standard deviation (acc 1) and two standard deviations (acc 2). Note that the standard deviation updates on each bar, so the current standard deviation is not the one used to calculate the accuracy. Rather, if there are N bars, N different standard deviation readings have been used to compute the accuracy statistics.
The inputs are:
- timeframe: the timeframe of the chart
- leg1_sym: the symbol of the first leg
- leg2_sym: the symbol of the second leg
- lag: the number of bars back to reference for computing the log return of each leg
- anchor_to_session_start: for intraday charts only, this overwrites the "lag" input so that the "lag" always sets the point of comparison to the session start. This setting is used to compute the relative change over a single session.
GT 5.1 Strategy═════════════════════════════════════════════════════════════════════════
█ OVERVIEW
People often look an indicator in their technical analysis to enter a position. We may also need to look at the signals of one or more indicators to verify the signals given by some indicators. In this context, I developed a strategy to test whether it really works by choosing some of the indicators that capture trend changes with the same characteristics. Also, since the subject is to catch the trend change, I thought it would be right to include an indicator using the heikin ashi logic. By averaging and smoothing the market noise, Heiken Ashi makes it easier to detect the direction of the trend helps to see possible reversal points on the chart. However, it should be noted that Heiken Ashi is a lagging indicator.
I picked 5 different indicators (but their purpose are similar) and combined them to produce buy and sell signals based on your choice(not repaint). First of all let's get some information about our indicators. So you will understand me why i picked these indicators and what is the meaning of their signals.
  
1 — Coral Trend Indicator by LazyBear
Coral Trend Indicator is a linear combination of moving averages, all obtained by a triple or higher order exponential smoothing. The indicator comes with a trend indication which is based on the normalized slope of the plot. the usage of this indicator is simple. When the color of the line is green that means the market is in uptrend.  But when the color is red that means the market is in downtrend. 
  
As you see the original indicator it is simple to find is it in uptrend or downtrend. 
So i added a code to find when the color of the line change. When it turns green to red my script giving sell signals, when it turns red to green it gives buy signals.
  
I hide the candles to show you more clearly what is happening when you choose only Coral Strategy. But sometimes it is not enough only using itself. Even if green dots turn to red it continues in uptrend. So we need a to look another indicator to approve our signal. 
2 — SSL channel by ErwinBeckers
Known as the SSL , the Semaphore Signal Level channel is an indicator that combines moving averages to provide you with a clear visual signal of price movement dynamics. In short, it's designed to show you when a price trend is forming. This indicator creates a band by calculating the high and low values according to the determined period. Simply if you decide 10 as period, it calculates a 10-period moving average on the latest 10 highs. Calculate a 10-period moving average on the latest 10 lows. If the price falls below the low band, the downtrend begins, if the price closes above the high band, the uptrend begins. Lets look the original form of indicator and learn how it using.
  
If the red line is below and the green band is above, it means that we are in uptrend, and if it is on the opposite side, it means that we are in downtrend. Therefore, it would be logical to enter a position where the trend has changed. So i added a code to find when the crossover has occured. 
  
As you see in my strategy, it gives you signals when the trend has changed.  But sometimes it is not enough only using this indicator itself. So lets look 2 indicator together in one chart.
  
Look circle SSL is saying it is in downtrend but Coral is saying it has entered in uptrend. if we just look to coral signal it can misleads us. So it can be better to look another indicator for validating our signals. 
3 — Heikin Ashi RSI Oscillator by JayRogers
The Heikin-Ashi technique is used by technical traders to identify a given trend more easily. Heikin-Ashi has a smoother look because it is essentially taking an average of the movement. There is a tendency with Heikin-Ashi for the candles to stay red during a downtrend and green during an uptrend, whereas normal candlesticks alternate color even if the price is moving dominantly in one direction. This indicator actually recalculates the RSI indicator with the logic of heikin ashi. Due to smoothing, the bars are formed with a slight lag, reflecting the trend rather than the exact price movement. So lets look the original version to understand more clearly. If red bars turn to green bars it means uptrend may begin, if green bars turn to red it means downtrend may begin. 
  
As you see HARSI giving lots of signal some of them is really good but some of them are not very well. Because it gives so much signals  Now i will change time period and lets look same chart again.
  
Now results are better because of heikin ashi's logic. it is not suitable for day traders, it gives more accurate result when using the time period is longer. But it can be useful to use this indicator in short time periods using with other indicators. So you may catch the trend changes more accurately.
4 — MACD DEMA by ToFFF
This indicator uses a double EMA and MACD algorithm to analyze the direction of the trend. Though it might seem a tough task to manage the trades with the help of MACD DEMA once you know how the proper way to interpret the signal lines, it will be an easy task.
This indicator also smoothens the signal lines with the time series algorithm which eventually makes the higher time frame important. So, expecting better results in the lower time frame can result in big losses as the data reading from the MACD DEMA will not be accurate. In order to understand the function of this indicator, you have to know the functions of the EMA also.
The exponential moving average tends to give more priority to the recent price changes. So, expecting better results when the volatility is very high is a very risky approach to trade the market. Moreover, the MACD has some lagging issues compared to the EMA, so it is super important to use a trading method that focuses on the higher time frame only.  What does MACD 12 26 Close 9 mean? When the DEMA-9 crosses above the MACD(12,26), this is considered a bearish signal. It means the trend in the stock – its magnitude and/or momentum – is starting to shift course. When the MACD(12,26) crosses above the DEMA-9, this is considered a bullish signal. Lets see this indicator on Chart.
  
When the blue line crossover red line it is good time to buy. As you see from the chart i put arrows where the crossover are appeared.
When the red line crossover blue line it is good time to sell or exit from position. 
5 — WaveTrend Oscillator by LazyBear
This is a technical indicator that creates high and low bands between two values. It then creates a trend indicator that draws waves with highs and lows within these boundaries. WaveTrend is a widely used indicator for finding direction of an asset.
Calculation period: number of candles used to calculate WaveTrend, defaults to 10. Averaging period: number of candles used to average WaveTrend, defaults to 21.
As you see in chart when the lines crossover occured my strategy gives buy or sell signals.
═════════════════════════════════════════════════════════════════════════
█ HOW TO USE
I hope you understand how the indicators I mentioned above work and what they are used for. Now, I will explain in detail how to use the strategy I have created.
When you enter the settings section, you will see 5 types of indicators. If you want to use the signals of the indicators, simply tick the box next to the indicators.  Also, under each option there is an area where you can set the "lookback". This setting is a field that will make the signals overlap when you select more than one option. If you are going to trade with only one option, you should make sure that this field is 0. Otherwise, it may continue to generate as many signals as you choose.
Lets see in chart for easy understanding.
  
As you see chart, if i chose only HARSI with lookback 0 (HARSI and CORAL should be 1 minumum because of algorithm-we looking 1 bar before, others 0 because we are looking crossovers), it will give signals only when harsı bar's color changed. But when i changed Lookback as 7 it will be like this in chart.
  
Now i will choose 2 indicator with settings of their lookback 0.
  
As you see it will give signals when both of them occurs same time. But HARSI is an indicator giving very early signal so we can enter position 5-6 bars after the first bar color change. So i will change HARSI Lookback settings as 7. Lets look what happens when we use lookback option.
   
So it wil be useful to change lookback settings to find best signals in each time period and in each symbol. But it shouldnt be too high. Because you can be late to catch trend's starting. 
  
this is an image of MACD and WAVE trend used and lookback option are both 6.
Now lets see an example with 3 options are chosen with lookback option 11-1-5
  
Now lets talk about indicators settings. After strategy options you will see each indicators settings, you can change their settings as you desired. So each indicators signal will be changed according to your adjustment.
I left strategy options with default settings. You can change it manually as if you want.
═════════════════════════════════════════════════════════════════════════
█  LIMITATIONS: Don't rely on non-standard charts results. For example Heikin Ashi is a technical analysis method used with the traditional candlestick chart.Heikin Ashi vs. Candlestick Chart: The decisive visual difference between Heikin Ashi and the traditional chart is that Heikin Ashi flattens the traditional candlestick chart using a modified formula.
The primary advantage of Heikin Ashi is that it makes the chart  more reader-friendly and helps users identify and analyze trends .
Because Heikin Ashi provides averaged price information rather than real-time price and reacts slowly to volatility — not suitable for scalpers and high-frequency traders. I added HARSI indicator as a supportive signal because it is useful with using CORAL and SSL channel indicators. If you change your candle types to Heikin Ashi , your profit will change in good way but dont rely on it.
═════════════════════════════════════════════════════════════════════════
█  THANKS: 
Special thanks to authors of the scripts that i used.
@LazyBear and @ErwinBeckers and @JayRogers and @ToFFF
═════════════════════════════════════════════════════════════════════════
█  DISCLAIMER
Any trade decisions you make are entirely your own responsibility.
Lyapunov Hodrick-Prescott Oscillator w/ DSL [Loxx]Lyapunov Hodrick-Prescott Oscillator w/ DSL   is a Hodrick-Prescott Channel Filter that is modified using the Lyapunov stability algorithm to turn the filter into an oscillator. Signals are created using Discontinued Signal Lines. 
 What is the Lyapunov Stability?  
As soon as scientists realized that the evolution of physical systems can be described in terms of mathematical equations, the stability of the various dynamical regimes was recognized as a matter of primary importance. The interest for this question was not only motivated by general curiosity, but also by the need to know, in the XIX century, to what extent the behavior of suitable mechanical devices remains unchanged, once their configuration has been perturbed. As a result, illustrious scientists such as Lagrange, Poisson, Maxwell and others deeply thought about ways of quantifying the stability both in general and specific contexts. The first exact definition of stability was given by the Russian mathematician Aleksandr Lyapunov who addressed the problem in his PhD Thesis in 1892, where he introduced two methods, the first of which is based on the linearization of the equations of motion and has originated what has later been termed Lyapunov exponents (LE). (Lyapunov 1992)
The interest in it suddenly skyrocketed during the Cold War period when the so-called "Second Method of Lyapunov" (see below) was found to be applicable to the stability of aerospace guidance systems which typically contain strong nonlinearities not treatable by other methods. A large number of publications appeared then and since in the control and systems literature. More recently the concept of the Lyapunov exponent (related to Lyapunov's First Method of discussing stability) has received wide interest in connection with  chaos theory . Lyapunov stability methods have also been applied to finding equilibrium solutions in traffic assignment problems.
In practice, Lyapunov exponents can be computed by exploiting the natural tendency of an n-dimensional volume to align along the n most expanding subspace. From the expansion rate of an n-dimensional volume, one obtains the sum of the n largest Lyapunov exponents. Altogether, the procedure requires evolving n linearly independent perturbations and one is faced with the problem that all vectors tend to align along the same direction. However, as shown in the late '70s, this numerical instability can be counterbalanced by orthonormalizing the vectors with the help of the Gram-Schmidt procedure (Benettin et al. 1980, Shimada and Nagashima 1979) (or, equivalently with a QR decomposition). As a result, the LE λi, naturally ordered from the largest to the most negative one, can be computed: they are altogether referred to as the Lyapunov spectrum.
The Lyapunov exponent "λ"  , is useful for distinguishing among the various types of orbits. It works for discrete as well as continuous systems.
λ < 0
The orbit attracts to a stable fixed point or stable periodic orbit. Negative Lyapunov exponents are characteristic of dissipative or non-conservative systems (the damped harmonic oscillator for instance). Such systems exhibit asymptotic stability; the more negative the exponent, the greater the stability. Superstable fixed points and superstable periodic points have a Lyapunov exponent of λ = −∞. This is something akin to a critically damped oscillator in that the system heads towards its equilibrium point as quickly as possible.
 	 
λ = 0
The orbit is a neutral fixed point (or an eventually fixed point). A Lyapunov exponent of zero indicates that the system is in some sort of steady state mode. A physical system with this exponent is conservative. Such systems exhibit Lyapunov stability. Take the case of two identical simple harmonic oscillators with different amplitudes. Because the frequency is independent of the amplitude, a phase portrait of the two oscillators would be a pair of concentric circles. The orbits in this situation would maintain a constant separation, like two flecks of dust fixed in place on a rotating record.
 	 
λ > 0
The orbit is unstable and chaotic. Nearby points, no matter how close, will diverge to any arbitrary separation. All neighborhoods in the phase space will eventually be visited. These points are said to be unstable. For a discrete system, the orbits will look like snow on a television set. This does not preclude any organization as a pattern may emerge. Thus the snow may be a bit lumpy. For a continuous system, the phase space would be a tangled sea of wavy lines like a pot of spaghetti. A physical example can be found in Brownian motion. Although the system is deterministic, there is no order to the orbit that ensues.
For our purposes here, we transform the HP by applying Lyapunov Stability as follows:
 output = math.log(math.abs(HP  / HP )) 
You can read more about Lyapunov Stability here:   Measuring Chaos  
 What is. the Hodrick-Prescott Filter? 
The Hodrick-Prescott (HP) filter refers to a data-smoothing technique. The HP filter is commonly applied during analysis to remove short-term fluctuations associated with the business cycle. Removal of these short-term fluctuations reveals long-term trends.
The Hodrick-Prescott (HP) filter is a tool commonly used in macroeconomics. It is named after economists Robert Hodrick and Edward Prescott who first popularized this filter in economics in the 1990s. Hodrick was an economist who specialized in international finance. Prescott won the Nobel Memorial Prize, sharing it with another economist for their research in macroeconomics.
This filter determines the long-term trend of a time series by discounting the importance of short-term price fluctuations. In practice, the filter is used to smooth and detrend the Conference Board's Help Wanted Index (HWI) so it can be benchmarked against the Bureau of Labor Statistic's (BLS) JOLTS, an economic data series that may more accurately measure job vacancies in the U.S.
The HP filter is one of the most widely used tools in macroeconomic analysis. It tends to have favorable results if the noise is distributed normally, and when the analysis being conducted is historical.
 What are DSL Discontinued Signal Line? 
A lot of indicators are using signal lines in order to determine the trend (or some desired state of the indicator) easier. The idea of the signal line is easy : comparing the value to it's smoothed (slightly lagging) state, the idea of current momentum/state is made.
Discontinued signal line is inheriting that simple signal line idea and it is extending it : instead of having one signal line, more lines depending on the current value of the indicator.
"Signal" line is calculated the following way :
When a certain level is crossed into the desired direction, the EMA of that value is calculated for the desired signal line
When that level is crossed into the opposite direction, the previous "signal" line value is simply "inherited" and it becomes a kind of a level
This way it becomes a combination of signal lines and levels that are trying to combine both the good from both methods.
In simple terms, DSL uses the concept of a signal line and betters it by inheriting the previous signal line's value & makes it a level.
 Included: 
 
 Bar coloring
 Alerts
 Signals
 Loxx's Expanded Source Types
Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]Cycle-Period Adaptive, Linear Regression Slope Oscillator   is an osciallator that solves for the Linear Regression slope and turns it into an oscillator. This is a very simple calculation and uses one of Ehler's first implementations of his cycle period calculations. The output slope value is smoothed after calculation and before being drawn. This is a sort of momentum indicator and has a rich history with Forex traders around the world. 
 What is the Cycle Period? 
The spectral content of the data are measured in a bank of contiguous filters as described in "Measuring Cycle Periods" in the March 2008 issue of Stocks & Commodities Magazine. The filter having the strongest output is selected as the current dominant cycle period. The cycle period is measured as the number of bars contained in one full cycle period.
 What is Linear Regression?  
In statistics, linear regression is a linear approach for modeling the relationship between a scalar response and one or more explanatory variables. The case of one explanatory variable is called simple linear regression; for more than one, the process is called multiple linear regression.
 Included: 
 
 Bar coloring
 2 signal types
 Alerts
 Loxx's Expanded Source Types
 Loxx's Moving Averages
AveragerStrategy:
The indicator builds horizontal channels to help you make a buying decision.
Rules:
1. First purchase:
  1.1 If the price is in the green channel (3): feel free to buy in the amount of 3 lots.
  1.2 If the price is in the blue channel, then we look for moving averages to be closer to the corresponding channel lines.
    1.2.1 In channel 2, the blue MA is closer to the blue channel line (above the green one), the green MA is closer to the green channel line (below the blue one).
    1.2.2 In channel 4, the blue moving average is closer to the blue channel line (below the green one), the green moving average is closer to the green channel line (above the blue one). If the conditions are met, we make a purchase in the number of lots indicated in the channel label (2 or 4 lots).
  1.3 We do not make the first purchase in the red channels (1, 2, 5).
2. Subsequent purchases/sales:
  2.1 When the price moves from one channel to another, we keep the number of lots in accordance with the channel labels. If the price went into the lower channel, we buy 1 more lot, if it goes into the upper channel, we sell 1 lot.
3. Suitable timeframes: from 1H to 1W. Best of all shows the result on the 1D timeframe.
Labels (except 0) contain information about the number of lots and the average price of the channel for placing pending orders ONLY for sale. We always buy manually.
The strategy is not an individual recommendation.
-----
Стратегия:
Индикатор строит горизонтальные каналы, помогающие принять решение о покупке.
Правила:
1. Первая покупка:
  1.1 Если цена находится в зеленом канале (3): смело покупаем в количестве 3 лота.
  1.2 Если цена в синем канале, то смотрим, чтобы скользящие средние были ближе к соответствующим линиям канала.
    1.2.1 В канале 2 синяя скользящая - ближе к синей линии канала (выше зеленой), зеленая скользящая - ближе к зеленой линии канала (ниже синей).
    1.2.2 В канале 4 синяя скользящая - ближе к синей линии канала (ниже зеленой), зеленая скользящая - ближе к зеленой линии канала (выше синей). Если условия соблюдены, делаем покупку в количестве лотов, указанному в лейбле канала (2 или 4 лота).
  1.3 В красных каналах (1, 2, 5) первую покупку не совершаем.
2. Последующие покупки/продажи:
  2.1 При переходе цены из одного канала в другой держим количество лотов в соответствии с лейблами канала. Если цена ушла в нижний канал - докупаем 1 лот, если в верхний - продаем 1 лот.
3. Подходящие таймфреймы: от 1Ч до 1Н. Лучше всего показывает результат на 1Д таймфрейме.
Лейблы (кроме 0) содержат информацию о количестве лотов и среднюю цену канала для выставления отложенных ордеров ТОЛЬКО на продажу. Докупаем всегда вручную.
Стратегия не является индивидуальной рекомендацией.
CFB-Adaptive Velocity Histogram [Loxx]CFB-Adaptive Velocity Histogram   is a velocity indicator with One-More-Moving-Average Adaptive Smoothing of input source value and Jurik's Composite-Fractal-Behavior-Adaptive Price-Trend-Period input with Dynamic Zones. All Juirk smoothing allows for both single and double Jurik smoothing passes. Velocity is adjusted to pips but there is no input value for the user. This indicator is tuned for Forex but can be used on any time series data.
 What is Composite Fractal Behavior ( CFB )? 
All around you mechanisms adjust themselves to their environment. From simple thermostats that react to air temperature to computer chips in modern cars that respond to changes in engine temperature, r.p.m.'s, torque, and throttle position. It was only a matter of time before fast desktop computers applied the mathematics of self-adjustment to systems that trade the financial markets.
Unlike basic systems with fixed formulas, an adaptive system adjusts its own equations. For example, start with a basic channel breakout system that uses the highest closing price of the last N bars as a threshold for detecting breakouts on the up side. An adaptive and improved version of this system would adjust N according to market conditions, such as momentum, price volatility or acceleration.
Since many systems are based directly or indirectly on cycles, another useful measure of market condition is the periodic length of a price chart's dominant cycle, (DC), that cycle with the greatest influence on price action.
The utility of this new DC measure was noted by author Murray Ruggiero in the January '96 issue of Futures Magazine. In it. Mr. Ruggiero used it to adaptive adjust the value of N in a channel breakout system. He then simulated trading 15 years of D-Mark futures in order to compare its performance to a similar system that had a fixed optimal value of N. The adaptive version produced 20% more profit!
This DC index utilized the popular MESA algorithm (a formulation by John Ehlers adapted from Burg's maximum entropy algorithm, MEM). Unfortunately, the DC approach is problematic when the market has no real dominant cycle momentum, because the mathematics will produce a value whether or not one actually exists! Therefore, we developed a proprietary indicator that does not presuppose the presence of market cycles. It's called CFB (Composite Fractal Behavior) and it works well whether or not the market is cyclic.
CFB examines price action for a particular fractal pattern, categorizes them by size, and then outputs a composite fractal size index. This index is smooth, timely and accurate
Essentially, CFB reveals the length of the market's trending action time frame. Long trending activity produces a large CFB index and short choppy action produces a small index value. Investors have found many applications for CFB which involve scaling other existing technical indicators adaptively, on a bar-to-bar basis.
 What is Jurik Volty used in the Juirk Filter? 
One of the lesser known qualities of Juirk smoothing is that the Jurik smoothing process is adaptive. "Jurik Volty" (a sort of market volatility ) is what makes Jurik smoothing adaptive. The Jurik Volty calculation can be used as both a standalone indicator and to smooth other indicators that you wish to make adaptive.
 What is the Jurik Moving Average? 
Have you noticed how moving averages add some lag (delay) to your signals? ... especially when price gaps up or down in a big move, and you are waiting for your moving average to catch up? Wait no more! JMA eliminates this problem forever and gives you the best of both worlds: low lag and smooth lines.
Ideally, you would like a filtered signal to be both smooth and lag-free. Lag causes delays in your trades, and increasing lag in your indicators typically result in lower profits. In other words, late comers get what's left on the table after the feast has already begun.
 What are Dynamic Zones? 
As explained in "Stocks & Commodities V15:7 (306-310): Dynamic Zones by Leo Zamansky, Ph .D., and David Stendahl"
Most indicators use a fixed zone for buy and sell signals. Here’ s a concept based on zones that are responsive to past levels of the indicator.
One approach to active investing employs the use of oscillators to exploit tradable market trends. This investing style follows a very simple form of logic: Enter the market only when an oscillator has moved far above or below traditional trading lev- els. However, these oscillator- driven systems lack the ability to evolve with the market because they use fixed buy and sell zones. Traders typically use one set of buy and sell zones for a bull market and substantially different zones for a bear market. And therein lies the problem.
Once traders begin introducing their market opinions into trading equations, by changing the zones, they negate the system’s mechanical nature. The objective is to have a system automatically define its own buy and sell zones and thereby profitably trade in any market — bull or bear. Dynamic zones offer a solution to the problem of fixed buy and sell zones for any oscillator-driven system.
An indicator’s extreme levels can be quantified using statistical methods. These extreme levels are calculated for a certain period and serve as the buy and sell zones for a trading system. The repetition of this statistical process for every value of the indicator creates values that become the dynamic zones. The zones are calculated in such a way that the probability of the indicator value rising above, or falling below, the dynamic zones is equal to a given probability input set by the trader.
To better understand dynamic zones, let's first describe them mathematically and then explain their use. The dynamic zones definition:
Find V such that:
For dynamic zone buy: P{X <= V}=P1
For dynamic zone sell: P{X >= V}=P2
where P1 and P2 are the probabilities set by the trader, X is the value of the indicator for the selected period and V represents the value of the dynamic zone.
The probability input P1 and P2 can be adjusted by the trader to encompass as much or as little data as the trader would like. The smaller the probability, the fewer data values above and below the dynamic zones. This translates into a wider range between the buy and sell zones. If a 10% probability is used for P1 and P2, only those data values that make up the top 10% and bottom 10% for an indicator are used in the construction of the zones. Of the values, 80% will fall between the two extreme levels. Because dynamic zone levels are penetrated so infrequently, when this happens, traders know that the market has truly moved into overbought or oversold territory.
Calculating the Dynamic Zones
The algorithm for the dynamic zones is a series of steps. First, decide the value of the lookback period t. Next, decide the value of the probability Pbuy for buy zone and value of the probability Psell for the sell zone.
For i=1, to the last lookback period, build the distribution f(x) of the price during the lookback period i. Then find the value Vi1 such that the probability of the price less than or equal to Vi1 during the lookback period i is equal to Pbuy. Find the value Vi2 such that the probability of the price greater or equal to Vi2 during the lookback period i is equal to Psell. The sequence of Vi1 for all periods gives the buy zone. The sequence of Vi2 for all periods gives the sell zone.
In the algorithm description, we have: Build the distribution f(x) of the price during the lookback period i. The distribution here is empirical namely, how many times a given value of x appeared during the lookback period. The problem is to find such x that the probability of a price being greater or equal to x will be equal to a probability selected by the user. Probability is the area under the distribution curve. The task is to find such value of x that the area under the distribution curve to the right of x will be equal to the probability selected by the user. That x is the dynamic zone.
 Included: 
 
 Bar coloring
 3 signal variations w/ alerts
 Divergences w/ alerts
 Loxx's Expanded Source Types
 
+ Multi-timeframe Multiple Moving Average LinesThis is a pretty simple script that plots lines for various moving averages (what I think are the most commonly used across all markets) of varying lengths of timeframes of the user's choosing. Timeframes range from 5 minutes up to one month, so regardless if you're a scalper or a swing trader there should be something here for you.
There are 8 lines (that can be turned on/off individually), which may seem like a lot, but if you use two averages and want to display four different timeframes for each, you can do that. The nice thing is that because the lines start plotting from the current bar they won't clutter up the screen. And obviously having moving averages from different timeframes on your chart makes price action more difficult to read (I mean sure, you can make them invisible, but who wants to do that all the time).
For each line there are two labels. One with the moving average type, and the other with its specific timeframe. I can't include the moving average length because it's not a string input. If anyone has a workaround for this, let me know, otherwise I would simply recommend setting different colors depending on the length, or if you only use one or two lengths and one or two moving averages this shouldn't be an issue. I had to use two labels because for the label text I couldn't include more than one string input, this is why there is an input for the 'moving average type label distance.'' You will want to adjust this depending on if you are trading crypto, futures, or forex because in some cases there may still be label overlap.
Pretty much everything else is self-explanatory.
I've added alerts. I might need to modify them if I can, because it would be nice for them to state the name and timeframe of the moving average. But I think this will do for now.
Enjoy!
Jurik Velocity ("smoother moment") [Loxx]Jurik Velocity ("smoother moment")   is a very simple and very useful calculation. This indicator was created to expose this calculation to folks who might find it useful in their own indicators and strategies.
 What is velocity? 
Velocity is a vector quantity that refers to "the rate at which an object changes its position." Imagine a person moving rapidly - one step forward and one step back - always returning to the original starting position. While this might result in a frenzy of activity, it would result in a zero velocity. Because the person always returns to the original position, the motion would never result in a change in position. Since velocity is defined as the rate at which the position changes, this motion results in zero velocity. If a person in motion wishes to maximize their velocity, then that person must make every effort to maximize the amount that they are displaced from their original position. Every step must go into moving that person further from where he or she started. For certain, the person should never change directions and begin to return to the starting position.
Velocity is a vector quantity. As such, velocity is direction aware. When evaluating the velocity of an object, one must keep track of direction. It would not be enough to say that an object has a velocity of 55 mi/hr. One must include direction information in order to fully describe the velocity of the object. For instance, you must describe an object's velocity as being 55 mi/hr, east. This is one of the essential differences between speed and velocity. Speed is a scalar quantity and does not keep track of direction; velocity is a vector quantity and is direction aware.
 Included: 
-Toggle on/off bar coloring
Happy trading!
TASC 2022.07 Pairs Rotation With Ehlers Loops█ OVERVIEW
 TASC's July 2022 edition of Traders' Tips  includes an article by John Ehlers titled "Pairs Rotation With Ehlers Loops". This is the code that implements the  Ehlers Loops  applied to pairs rotation trading.
█ CONCEPTS
John Ehlers developed  Ehlers loops  as a tool to visualize the performance of one data stream versus another. Initially, he used this tool to chart price versus volume. However, Ehlers loops proved to be suitable for determining the timing of the  pairs rotation strategy . This strategy works by having a long position in only one of two securities, depending on which one is considered stronger at a given time. 
When the prices of two securities (filtered and scaled with a  standard deviation  for consistent presentation) are plotted against each other, the curvature and direction of rotation on the chart can help guide decisions on long positions. For example, when plotting a stock versus a referenced symbol, a vertical upward movement while rotating clockwise is a sign of going long the stock. Similarly, a horizontal movement to the right while rotating counterclockwise is the sign to go long the reference. A higher probability of a reversal is expected when the price moves more than one or two standard deviations.
█ CALCULATIONS
The script uses the following steps to calculate the Ehlers Loops:
 
 The price data of both securities in the pair are individually filtered using identical high-pass and SuperSmoother filters. This results in two  band-limited  data streams, having a nominally zero mean. The input parameters  Low-Pass Period  and  High-Pass Period  control the filter bandwidth and thus can modify the shape of the Ehlers Loops.
 Subsequently, the filtered data streams are scaled in terms of standard deviation by dividing each of them by their  root-mean-square  (RMS) values. These data streams are plotted as zero-mean oscillators.
 Finally, the scaled data streams are displayed one against another for the selected time interval (defined by the input parameter  Loop Segments ).  In the resulting  scatterplot, the thicker line corresponds to the later data points.  The fluctuations of the filtered price data of the chart symbol are plotted along the  y -axis, and the price changes of the referenced symbol are shown along the  x -axis. 
Adaptive Qualitative Quantitative Estimation (QQE) [Loxx]Adaptive QQE   is a fixed and cycle adaptive version of the popular Qualitative Quantitative Estimation (QQE) used by forex traders. This indicator includes varoius types of RSI caculations and adaptive cycle measurements to find tune your signal.
 Qualitative Quantitative Estimation (QQE): 
The Qualitative Quantitative Estimation (QQE) indicator works like a smoother version of the popular Relative Strength Index (RSI) indicator. QQE expands on RSI by adding two volatility based trailing stop lines. These trailing stop lines are composed of a fast and a slow moving Average True Range (ATR).
There are many indicators for many purposes. Some of them are complex and some are comparatively easy to handle. The QQE indicator is a really useful analytical tool and one of the most accurate indicators. It offers numerous strategies for using the buy and sell signals. Essentially, it can help detect trend reversal and enter the trade at the most optimal positions.
 Wilders' RSI: 
The Relative Strength Index ( RSI ) is a well versed momentum based oscillator which is used to measure the speed (velocity) as well as the change (magnitude) of directional price movements. Essentially RSI , when graphed, provides a visual mean to monitor both the current, as well as historical, strength and weakness of a particular market. The strength or weakness is based on closing prices over the duration of a specified trading period creating a reliable metric of price and momentum changes. Given the popularity of cash settled instruments (stock indexes) and leveraged financial products (the entire field of derivatives); RSI has proven to be a viable indicator of price movements.
 RSX RSI: 
RSI is a very popular technical indicator, because it takes into consideration market speed, direction and trend uniformity. However, the its widely criticized drawback is its noisy (jittery) appearance. The Jurk RSX retains all the useful features of RSI , but with one important exception: the noise is gone with no added lag.
 Rapid RSI: 
Rapid RSI Indicator, from Ian Copsey's article in the October 2006 issue of Stocks & Commodities magazine.
RapidRSI resembles Wilder's RSI , but uses a SMA instead of a WilderMA for internal smoothing of price change accumulators.
 VHF Adaptive Cycle: 
Vertical Horizontal Filter (VHF) was created by Adam White to identify trending and ranging markets. VHF measures the level of trend activity, similar to ADX DI. Vertical Horizontal Filter does not, itself, generate trading signals, but determines whether signals are taken from trend or momentum indicators. Using this trend information, one is then able to derive an average cycle length.
 Band-pass Adaptive Cycle: 
Even the most casual chart reader will be able to spot times when the market is cycling and other times when longer-term trends are in play. Cycling markets are ideal for swing trading however attempting to “trade the swing” in a trending market can be a recipe for disaster. Similarly, applying trend trading techniques during a cycling market can equally wreak havoc in your account. Cycle or trend modes can readily be identified in hindsight. But it would be useful to have an objective scientific approach to guide you as to the current market mode.
There are a number of tools already available to differentiate between cycle and trend modes. For example, measuring the trend slope over the cycle period to the amplitude of the cyclic swing is one possibility.
We begin by thinking of cycle mode in terms of frequency or its inverse, periodicity. Since the markets are fractal ; daily, weekly, and intraday charts are pretty much indistinguishable when time scales are removed. Thus it is useful to think of the cycle period in terms of its bar count. For example, a 20 bar cycle using daily data corresponds to a cycle period of approximately one month.
When viewed as a waveform, slow-varying price trends constitute the waveform's low frequency components and day-to-day fluctuations (noise) constitute the high frequency components. The objective in cycle mode is to filter out the unwanted components--both low frequency trends and the high frequency noise--and retain only the range of frequencies over the desired swing period. A filter for doing this is called a bandpass filter and the range of frequencies passed is the filter's bandwidth.
 Included: 
-Toggle on/off bar coloring
-Customize RSI signal using fixed, VHF Adaptive, and Band-pass Adaptive calculations
-Choose from three different RSI types
 Visuals: 
-Red/Green line is the moving average of RSI
-Thin white line is the fast trend
-Dotted yellow line is the slow trend
Happy trading!
Customizable Non-Repainting HTF MACD MFI Scalper Bot StrategyThis script was originally shared by  Wunderbit   as a free open source script for the community to work with.
WHAT THIS SCRIPT DOES:
It is intended for use on an algorithmic bot trading platform but can be used for scalping and manual trading.
This strategy is based on the trend-following momentum indicator . It includes the Money Flow index as an additional point for entry.
HOW IT DOES IT:
It uses a combination of MACD and MFI indicators to create entry signals. Parameters for each indicator have been surfaced for user configurability.
Take profits are fixed, but stop loss uses ATR configuration to minimize losses and close profitably.
HOW IS MY VERSION ORIGINAL:
I started trying to deploy this script myself in my algorithmic trading but ran into some issues which I have tried to address in this version.
 
 Delayed Signals : The script has been refactored to use a time frame drop down. The higher time frame can be run on a faster chart (recommended on one minute chart for fastest signal confirmation and relay to algotrading platform.)
 Repainting Issues : All indicators have been recoded to use the security function that checks to see if the current calculation is in realtime, if it is, then it uses the previous bar for calculation. If you are still experiencing repainting issues based on intended (or non intended use), please provide a report with screenshot and explanation so I can try to address.
 Filtering : I have added to additional filters an ABOVE EMA Filter and a BELOW RSI Filter (both can be turned on and off)
 Customizable Long and Close Messages : This allows someone to use the script for algorithmic trading without having to alter code. It also means you can use one indicator for all of your different alterts required for your bots.
 
HOW TO USE IT:
It is intended to be used in the 5-30 minute time frames, but you might be able to get a good configuration for higher time frames.  I welcome feedback from other users on what they have found.
Find a pair with high volatility (example  KUCOIN:ETH3LUSDT  ) - I have found it works particularly well with 3L and 3S tokens for crypto. although it the limitation is that confrigurations I have found to work typically have low R/R ratio, but very high win rate and profit factor.
Ideally set one minute chart for bots, but you can use other charts for manual trading. The signal will be delayed by one bar but I have found configurations that still test well.
Select a time frame in configuration for your indicator calculations.
Select the strategy config for time frame. I like to use 5 and 15 minutes for scalping scenarios, but I am interested in hearing back from other community memebers.
Optimize your indicator without filters (trendFilter and RSI Filter)
Use the TrendFilter and RSI Filter to further refine your signals for entry.  You will get less entries but you can increase your win ratio.
I will add screenshots and possibly a video provided that it passes community standards.
Limitations: this works rather well for short term, and does some good forward testing but back testing large data sets is a problem when switching from very small time frame to large time frame. For instance, finding a configuration that works on a one minute chart but then changing to a 1 hour chart means you lose some of your intra bar calclulations. There are some new features in pine script which might be able to address, this, but I have not had a chance to work on that issue.
Multiple MAs + No Trend Zone + ATR WidgetThis is my first Pine Script attempt. Nothing special, just an "all in one" for the most common things I use, and what I have found to be the most common in a lot of strategies.
Great for free and limited accounts as it combines 7 total indicators into one.
-- First 5 indicators are Independant Moving Averages:
-Each one can be set for length, as well as source and type (SMA, EMA, SMMA, WMA, VWMA) individually
-- Second type (6th) of indicator is one I find extremly useful for staying OUT of consolidation trading. It's called a "No Trend Zone" indicator I swipped from the Hoffman Startegy. Basically, its set for a small deviation (0.5) of a 35 EMA, which creates a "Band" around the 35 line. When you have this "Band" flat or with no discernable incline/decline, with price action OR some or multiple moving averages inside this banded zone, it typically indicates a zone of consolidation. This will help you identify when you may be in one of those zones, that way you don't get trapped "waiting for paint to dry" before the market starts to move again with your position, and keep you from entering should you be considering the market at that time.
The last indicator is my favorite, and one I will refine a little deeper soon.
-- The ATR widget finishes us out. This widget can be customized for colors, turned on or off, and automatically rounds the ATR (ATR period based on the chart timeframe) to a nice readable number for what you're trading. It has settings to show or not, the length, what rounding style to use (forex pip 0.0001, forex/stock/etf/indicies 0.01) where to show it on the pane, a Multiplier Factor (for stop loss calculations automatically) and the colors.
***NOTE ABOUT ATR WIDGET:
I am primarily a forex trader, so the defaults are for Forex 0.0001. If you see some odd numbers (like 55798 on a current chart), check the inputs tab on the settings, and change the "ATR Style" from "Forex 0.0001" to "Forex/Stock/ETF/Indicies 0.01", and you should arrive with the correct number.
Time█   OVERVIEW 
This library is a Pine Script™ programmer’s tool containing a variety of time related functions to calculate or measure time, or format time into string variables.
█   CONCEPTS 
 `formattedTime()`, `formattedDate()` and `formattedDay()` 
Pine Script™, like many other programming languages, uses timestamps in UNIX format, expressed as the number of milliseconds elapsed since 00:00:00 UTC, 1 January 1970. These three functions convert a UNIX timestamp to a formatted string for human consumption. 
These are examples of ways you can call the functions, and the ensuing results:
 CODE                                                            RESULT
formattedTime(timenow)                                  >>>     "00:40:35"
formattedTime(timenow, "short")                         >>>     "12:40 AM"
formattedTime(timenow, "full")                          >>>     "12:40:35 AM UTC"
formattedTime(1000 * 60 * 60 * 3.5, "HH:mm")            >>>     "03:30"
formattedDate(timenow, "short")                         >>>     "4/30/22"
formattedDate(timenow, "medium")                        >>>     "Apr 30, 2022"
formattedDate(timenow, "full")                          >>>     "Saturday, April 30, 2022"
formattedDay(timenow, "E")                              >>>     "Sat"
formattedDay(timenow, "dd.MM.yy")                       >>>     "30.04.22"
formattedDay(timenow, "yyyy.MM.dd G 'at' hh:mm:ss z")   >>>     "2022.04.30 AD at 12:40:35 UTC" 
These functions use  str.format()  and some of the special formatting codes it allows for. Pine Script™ documentation does not yet contain complete specifications on these codes, but in the meantime you can find some information in the  The Java™ Tutorials  and in Java documentation of its  MessageFormat class . Note that  str.format()  implements only a subset of the MessageFormat features in Java.
 `secondsSince()` 
The introduction of  varip  variables in Pine Script™ has made it possible to track the time for which a condition is true when a script is executing on a realtime bar. One obvious use case that comes to mind is to enable trades to exit only when the exit condition has been true for a period of time, whether that period is shorter that the chart's timeframe, or spans across multiple realtime bars.
For more information on this function and  varip  please see our  Using `varip` variables  publication. 
 `timeFrom( )` 
When plotting  lines ,  boxes , and  labels  one often needs to calculate an offset for past or future end points relative to the time a condition or point occurs in history. Using  xloc.bar_index  is often the easiest solution, but some situations require the use of  xloc.bar_time . We introduce  `timeFrom()`  to assist in calculating time-based offsets. The function calculates a timestamp using a negative (into the past) or positive (into the future) offset from the current bar's starting or closing time, or from the current time of day. The offset can be expressed in units of chart timeframe, or in seconds, minutes, hours, days, months or years. This function was ported from our  Time Offset Calculation Framework .
 `formattedNoOfPeriods()` and `secondsToTfString()`  
Our final two offerings aim to confront two remaining issues: 
 How much time is represented in a given timestamp? 
How can I produce a "simple string" timeframe usable with  request.security()  from a timeframe expressed in seconds? 
 `formattedNoOfPeriods()`  converts a time value in ms to a quantity of time units. This is useful for calculating a difference in time between 2 points and converting to a desired number of units of time. If no unit is supplied, the function automatically chooses a unit based on a predetermined time step. 
 `secondsToTfString()`  converts an input time in seconds to a target timeframe string in  timeframe.period  string format. This is useful for implementing stepped timeframes relative to the chart time, or calculating multiples of a given chart timeframe. Results from this function are in  simple  form, which means they are useable as `timeframe` arguments in functions like  request.security() . 
 
█   NOTES 
Although the example code is commented in detail, the size of the library justifies some further explanation as many concepts are demonstrated. Key points are as follows: 
 • Pivot points are used to draw lines from.  `timeFrom( )`  calculates the length of the lines in the specified unit of time.
  By default the script uses 20 units of the charts timeframe. Example: a 1hr chart has arrows 20 hours in length.
 • At the point of the arrows  `formattedNoOfPeriods()`  calculates the line length in the specified unit of time from the input menu. 
  If  “Use Input Time”  is disabled, a unit of time is automatically assigned. 
 • At each pivot point a label with a formatted date or time is placed with one of the three formatting helper functions to display the time or date the pivot occurred. 
 • A label on the last bar showcases  `secondsSince()` . The label goes through three stages of detection for a timed alert.
  If the difference between the high and the open in ticks exceeds the input value, a timer starts and will turn the label red once the input time is exceeded to simulate a time-delayed alert. 
 • In the bottom right of the screen  `secondsToTfString()`  posts the chart timeframe in a table. This can be multiplied from the input menu. 
 Look first. Then leap.  
█   FUNCTIONS 
 formattedTime(timeInMs, format)  
  Converts a UNIX timestamp (in milliseconds) to a formatted time string.
  Parameters:
     timeInMs : (series float) Timestamp to be formatted. 
     format : (series string) Format for the time. Optional. The default value is "HH:mm:ss".
  Returns: (string) A string containing the formatted time.
 formattedDate(timeInMs, format)  
  Converts a UNIX timestamp (in milliseconds) to a formatted date string.
  Parameters:
     timeInMs : (series float) Timestamp to be formatted. 
     format : (series string) Format for the date. Optional. The default value is "yyyy-MM-dd".
  Returns: (string) A string containing the formatted date.
 formattedDay(timeInMs, format)  
  Converts a UNIX timestamp (in milliseconds) to the name of the day of the week.
  Parameters:
     timeInMs : (series float) Timestamp to be formatted. 
     format : (series string) Format for the day of the week. Optional. The default value is "EEEE" (complete day name).
  Returns: (string) A string containing the day of the week.
 secondsSince(cond, resetCond)  
  The duration in milliseconds that a condition has been true.
  Parameters:
     cond : (series bool) Condition to time.       
     resetCond : (series bool) When `true`, the duration resets. 
  Returns: The duration in seconds for which `cond` is continuously true.
 timeFrom(from, qty, units)  
  Calculates a +/- time offset in variable units from the current bar's time or from the current time.
  Parameters:
     from : (series string) Starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
     qty : (series int) The +/- qty of units of offset required. A "series float" can be used but it will be cast to a "series int".
     units : (series string) String containing one of the seven allowed time units: "chart" (chart's timeframe), "seconds", "minutes", "hours", "days", "months", "years".
  Returns: (int) The resultant time offset `from` the `qty` of time in the specified `units`.
 formattedNoOfPeriods(ms, unit)  
  Converts a time value in ms to a quantity of time units.
  Parameters:
     ms : (series int) Value of time to be formatted. 
     unit : (series string) The target unit of time measurement. Options are "seconds", "minutes", "hours", "days", "weeks", "months". If not used one will be automatically assigned. 
  Returns: (string) A formatted string from the number of `ms` in the specified `unit` of time measurement
 secondsToTfString(tfInSeconds, mult)  
  Convert an input time in seconds to target string TF in `timeframe.period` string format.
  Parameters:
     tfInSeconds : (simple int) a timeframe in seconds to convert to a string.       
     mult : (simple float) Multiple of `tfInSeconds` to be calculated. Optional. 1 (no multiplier) is default. 
  Returns: (string) The `tfInSeconds` in `timeframe.period` format usable with `request.security()`.
HighTimeframeSamplingLibrary   "HighTimeframeSampling" 
Library for sampling high timeframe (HTF) data. Returns an array of historical values, an arbitrary historical value, or the highest/lowest value in a range, spending a single security() call.
An optional pass-through for the chart timeframe is included. Other than that case, the data is fixed and does not alter over the course of the HTF bar. It behaves consistently on historical and elapsed realtime bars.
The first version returns floating-point numbers only. I might extend it if there's interest.
🙏 Credits: This library is (yet another) attempt at a solution of the problems in using HTF data that were laid out by Pinecoders - to whom, especially to Luc F, many thanks are due - in "security() revisited" -  which I recommend you consult first. Go ahead, I'll wait.
     All code is my own.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        WHAT'S THE PROBLEM? OR, WHY NOT JUST USE SECURITY()  
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are many difficulties with using HTF data, and many potential solutions. It's not really possible to convey it only in words: you need to see it on a chart.
Before using this library, please refer to my other HTF library, HighTimeframeTiming:  which explains it extensively, compares many different solutions, and demonstrates (what I think are) the advantages of using this very library, namely, that it's stable, accurate, versatile and inexpensive. Then if you agree, come back here and choose your function.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                         MOAR EXPLANATION  
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
🧹 Housekeeping: To see which plot is which, turn line labels on: Settings > Scales > Indicator Name Label. Vertical lines at the top of the chart show the open of a HTF bar: grey for historical and white for real-time bars.
‼ LIMITATIONS: To avoid strange behaviour, use this library on liquid assets and at chart timeframes high enough to reliably produce updates at least once per bar period.
     A more conventional and universal limitation is that the library does not offer an unlimited view of historical bars. You need to define upfront how many HTF bars you want to store. Very large numbers might conceivably run into data or performance issues.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                      BRING ON THE FUNCTIONS  
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 @function f_HTF_Value(string _HTF, float _source, int _arrayLength, int _HTF_Offset, bool _useLiveDataOnChartTF=false) 
     Returns a floating-point number from a higher timeframe, with a historical operator within an abitrary (but limited) number of bars.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
@param int _HTF_Offset is the historical operator for the value you want to return. E.g., if you want the most recent fixed close, _source=close and _HTF_Offset = 0. If you want the one before that, _HTF_Offset=1, etc.
     The number of HTF bars to look back must be zero or more, and must be one less than the number of bars stored.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
     If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
     The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
     This means that on default settings, on the chart timeframe, it matches the raw source values from security(){0}.
     You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@returns a floating-point value that you requested from the higher timeframe.
 @function f_HTF_Array(string _HTF, float _source, int _arrayLength, bool _useLiveDataOnChartTF=false, int _startIn, int _endIn) 
     Returns an array of historical values from a higher timeframe, starting with the current bar. Optionally, returns a slice of the array. The array is in reverse chronological order, i.e., index 0 contains the most recent value.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to keep in the array.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
     If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
     The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
     This means that on default settings, on the chart timeframe, it matches raw source values from security().
     You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param int _startIn is the array index to begin taking a slice. Must be at least one less than the length of the array; if out of bounds it is corrected to 0.  
@param int _endIn is the array index BEFORE WHICH to end the slice. If the ending index of the array slice would take the slice past the end of the array, it is corrected to the end of the array. The ending index of the array slice must be greater than or equal to the starting index. If the end is less than the start, the whole array is returned. If the starting index is the same as the ending index, an empty array is returned. If either the starting or ending index is negative, the entire array is returned (which is the default behaviour; this is effectively a switch to bypass the slicing without taking up an extra parameter).
@returns an array of HTF values.
 @function f_HTF_Highest(string _HTF="", float _source, int _arrayLength, bool _useLiveDataOnChartTF=true, int _rangeIn) 
     Returns the highest value within a range consisting of a given number of bars back from the most recent bar.
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't have a range greater than this number.
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
     If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
     The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
     This means that on default settings, on the chart timeframe, it matches raw source values from security().
     You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
@returns a floating-point number representing the highest value in the range.
 @function f_HTF_Lowest(string _HTF="", float _source, int _arrayLength, bool _useLiveDataOnChartTF=true, int _rangeIn) 
     Returns the lowest value within a range consisting of a given number of bars back from the most recent bar. 
@param string _HTF is the string that represents the higher timeframe. It must be in a format that the request.security() function recognises. The input timeframe cannot be lower than the chart timeframe or an error is thrown.
@param float _source is the source value that you want to sample, e.g. close, open, etc., or you can use any floating-point number.
@param int _arrayLength is the number of HTF bars you want to store and must be greater than zero. You can't go back further in history than this number of bars (minus one, because the current/most recent available bar is also stored).
@param bool _useLiveDataOnChartTF uses live data on the chart timeframe.
     If the higher timeframe is the same as the chart timeframe, store the live value (i.e., from this very bar). For all truly higher timeframes, store the fixed value (i.e., from the previous bar).
     The default is to use live data for the chart timeframe, so that this function works intuitively, that is, it does not fix data unless it has to (i.e., because the data is from a higher timeframe).
     This means that on default settings, on the chart timeframe, it matches raw source values from security().
     You can override this behaviour by passing _useLiveDataOnChartTF as false. Then it will fix all data for all timeframes.
@param _rangeIn is the number of bars to include in the range of bars from which we want to find the highest value. It is NOT the historical operator of the last bar in the range. The range always starts at the current bar. A value of 1 doesn't make much sense but the function will generously return the only value it can anyway. A value less than 1 doesn't make sense and will return an error. A value that is higher than the number of stored values will be corrected to equal the number of stored values.
@returns a floating-point number representing the lowest value in the range.
Volatility Risk Premium GOLD & SILVER 1.0ENGLISH 
This indicator (V-R-P) calculates the (one month) Volatility Risk Premium for GOLD and SILVER. 
V-R-P is the premium hedgers pay for over Realized Volatility for GOLD and SILVER options.
The premium stems from hedgers paying to insure their portfolios, and manifests itself in the differential between the price at which options are sold (Implied Volatility) and the volatility GOLD and SILVER ultimately realize (Realized Volatility).
I am using 30-day Implied Volatility (IV) and 21-day Realized Volatility (HV) as the basis for my calculation, as one month of IV is based on 30 calendaristic days and one month of HV is based on 21 trading days.
At first, the indicator appears blank and a label instructs you to choose which index you want the V-R-P to plot on the chart. Use the indicator settings (the sprocket) to choose one of the precious metals (or both).
Together with the V-R-P line, the indicator will show its one year moving average within a range of +/- 15% (which you can change) for benchmarking purposes. We should consider this range the “normalized” V-R-P for the actual period.
The Zero Line is also marked on the indicator.
 Interpretation 
When V-R-P is within the “normalized” range, … well... volatility and uncertainty, as it’s seen by the option market, is “normal”. We have a “premium” of volatility which should be considered normal.
When V-R-P is above the “normalized” range, the volatility premium is high. This means that investors are willing to pay more for options because they see an increasing uncertainty in markets.
When V-R-P is below the “normalized” range but positive (above the Zero line), the premium investors are willing to pay for risk is low, meaning they see decreasing uncertainty and risks in the market, but not by much.
When V-R-P is negative (below the Zero line), we have COMPLACENCY. This means investors see upcoming risk as being lower than what happened in the market in the recent past (within the last 30 days).
 CONCEPTS :
 Volatility Risk Premium 
The volatility risk premium (V-R-P) is the notion that implied volatility (IV) tends to be higher than realized volatility (HV) as market participants tend to overestimate the likelihood of a significant market crash. 
This overestimation may account for an increase in demand for options as protection against an equity portfolio. Basically, this heightened perception of risk may lead to a higher willingness to pay for these options to hedge a portfolio. 
In other words, investors are willing to pay a premium for options to have protection against significant market crashes even if statistically the probability of these crashes is lesser or even negligible.
Therefore, the tendency of implied volatility is to be higher than realized volatility, thus V-R-P being positive.
 Realized/Historical Volatility 
Historical Volatility (HV) is the statistical measure of the dispersion of returns for an index over a given period of time.
Historical volatility is a well-known concept in finance, but there is confusion in how exactly it is calculated. Different sources may use slightly different historical volatility formulas.
For calculating Historical Volatility I am using the most common approach: annualized standard deviation of logarithmic returns, based on daily closing prices.
Implied Volatility
Implied Volatility (IV) is the market's forecast of a likely movement in the price of the index and it is expressed annualized, using percentages and standard deviations over a specified time horizon (usually 30 days).
IV is used to price options contracts where high implied volatility results in options with higher premiums and vice versa. Also, options supply and demand and time value are major determining factors for calculating Implied Volatility.
Implied Volatility usually increases in bearish markets and decreases when the market is bullish.
For determining GOLD and SILVER implied volatility I used their volatility indices: GVZ and VXSLV (30-day IV) provided by CBOE.
 Warning 
Please be aware that because CBOE doesn’t provide real-time data in Tradingview, my V-R-P calculation is also delayed, so you shouldn’t use it in the first 15 minutes after the opening.
This indicator is calibrated for a daily time frame.
----------------------------------------------------------------------
 ESPAŇOL 
Este indicador (V-R-P) calcula la Prima de Riesgo de Volatilidad (de un mes) para GOLD y SILVER.
V-R-P es la prima que pagan los hedgers sobre la Volatilidad Realizada para las opciones de GOLD y SILVER.
La prima proviene de los hedgers que pagan para asegurar sus carteras y se manifiesta en el diferencial entre el precio al que se venden las opciones (Volatilidad Implícita) y la volatilidad que finalmente se realiza en el ORO y la PLATA (Volatilidad Realizada).
Estoy utilizando la Volatilidad Implícita (IV) de 30 días y la Volatilidad Realizada (HV) de 21 días como base para mi cálculo, ya que un mes de IV se basa en 30 días calendario y un mes de HV se basa en 21 días de negociación.
Al principio, el indicador aparece en blanco y una etiqueta le indica que elija qué índice desea que el V-R-P represente en el gráfico. Use la configuración del indicador (la rueda dentada) para elegir uno de los metales preciosos (o ambos).
Junto con la línea V-R-P, el indicador mostrará su promedio móvil de un año dentro de un rango de +/- 15% (que puede cambiar) con fines de evaluación comparativa. Deberíamos considerar este rango como el V-R-P "normalizado" para el período real.
La línea Cero también está marcada en el indicador.
 Interpretación 
Cuando el V-R-P está dentro del rango "normalizado",... bueno... la volatilidad y la incertidumbre, como las ve el mercado de opciones, es "normal". Tenemos una “prima” de volatilidad que debería considerarse normal.
Cuando V-R-P está por encima del rango "normalizado", la prima de volatilidad es alta. Esto significa que los inversores están dispuestos a pagar más por las opciones porque ven una creciente incertidumbre en los mercados.
Cuando el V-R-P está por debajo del rango "normalizado" pero es positivo (por encima de la línea Cero), la prima que los inversores están dispuestos a pagar por el riesgo es baja, lo que significa que ven una disminución, pero no pronunciada, de la incertidumbre y los riesgos en el mercado.
Cuando V-R-P es negativo (por debajo de la línea Cero), tenemos COMPLACENCIA. Esto significa que los inversores ven el riesgo próximo como menor que lo que sucedió en el mercado en el pasado reciente (en los últimos 30 días).
 
 CONCEPTOS :
 Prima de Riesgo de Volatilidad 
La Prima de Riesgo de Volatilidad (V-R-P) es la noción de que la Volatilidad Implícita (IV) tiende a ser más alta que la Volatilidad Realizada (HV) ya que los participantes del mercado tienden a sobrestimar la probabilidad de una caída significativa del mercado.
Esta sobreestimación puede explicar un aumento en la demanda de opciones como protección contra una cartera de acciones. Básicamente, esta mayor percepción de riesgo puede conducir a una mayor disposición a pagar por estas opciones para cubrir una cartera.
En otras palabras, los inversores están dispuestos a pagar una prima por las opciones para tener protección contra caídas significativas del mercado, incluso si estadísticamente la probabilidad de estas caídas es menor o insignificante.
Por lo tanto, la tendencia de la Volatilidad Implícita es de ser mayor que la Volatilidad Realizada, por lo cual el V-R-P es positivo.
 Volatilidad Realizada/Histórica 
La Volatilidad Histórica (HV) es la medida estadística de la dispersión de los rendimientos de un índice durante un período de tiempo determinado.
La Volatilidad Histórica es un concepto bien conocido en finanzas, pero existe confusión sobre cómo se calcula exactamente. Varias fuentes pueden usar fórmulas de Volatilidad Histórica ligeramente diferentes.
Para calcular la Volatilidad Histórica, utilicé el enfoque más común: desviación estándar anualizada de rendimientos logarítmicos, basada en los precios de cierre diarios.
 Volatilidad Implícita 
La Volatilidad Implícita (IV) es la previsión del mercado de un posible movimiento en el precio del índice y se expresa anualizada, utilizando porcentajes y desviaciones estándar en un horizonte de tiempo específico (generalmente 30 días).
IV se utiliza para cotizar contratos de opciones donde la alta Volatilidad Implícita da como resultado opciones con primas más altas y viceversa. Además, la oferta y la demanda de opciones y el valor temporal son factores determinantes importantes para calcular la Volatilidad Implícita.
La Volatilidad Implícita generalmente aumenta en los mercados bajistas y disminuye cuando el mercado es alcista.
Para determinar la Volatilidad Implícita de GOLD y SILVER utilicé sus índices de volatilidad: GVZ y VXSLV (30 días IV) proporcionados por CBOE.
 Precaución 
Tenga en cuenta que debido a que CBOE no proporciona datos en tiempo real en Tradingview, mi cálculo de V-R-P también se retrasa, y por este motivo no se recomienda usar en los primeros 15 minutos desde la apertura.
Este indicador está calibrado para un marco de tiempo diario.
Volatility Risk Premium (VRP) 1.0ENGLISH 
This indicator (V-R-P) calculates the (one month) Volatility Risk Premium for S&P500 and Nasdaq-100. 
V-R-P is the premium hedgers pay for over Realized Volatility for S&P500 and Nasdaq-100 index options.
The premium stems from hedgers paying to insure their portfolios, and manifests itself in the differential between the price at which options are sold (Implied Volatility) and the volatility the S&P500 and Nasdaq-100 ultimately realize (Realized Volatility).
I am using 30-day Implied Volatility (IV) and 21-day Realized Volatility (HV) as the basis for my calculation, as one month of IV is based on 30 calendaristic days and one month of HV is based on 21 trading days.
At first, the indicator appears blank and a label instructs you to choose which index you want the V-R-P to plot on the chart. Use the indicator settings (the sprocket) to choose one of the indices (or both).
Together with the V-R-P line, the indicator will show its one year moving average within a range of +/- 15% (which you can change) for benchmarking purposes. We should consider this range the “normalized” V-R-P for the actual period.
The Zero Line is also marked on the indicator.
 Interpretation 
When V-R-P is within the “normalized” range, … well... volatility and uncertainty, as it’s seen by the option market, is “normal”. We have a “premium” of volatility which should be considered normal.
When V-R-P is above the “normalized” range, the volatility premium is high. This means that investors are willing to pay more for options because they see an increasing uncertainty in markets.
When V-R-P is below the “normalized” range but positive (above the Zero line), the premium investors are willing to pay for risk is low, meaning they see decreasing uncertainty and risks in the market, but not by much.
When V-R-P is negative (below the Zero line), we have COMPLACENCY. This means investors see upcoming risk as being lower than what happened in the market in the recent past (within the last 30 days).
 CONCEPTS: 
 Volatility Risk Premium 
The volatility risk premium (V-R-P) is the notion that implied volatility (IV) tends to be higher than realized volatility (HV) as market participants tend to overestimate the likelihood of a significant market crash.
This overestimation may account for an increase in demand for options as protection against an equity portfolio. Basically, this heightened perception of risk may lead to a higher willingness to pay for these options to hedge a portfolio. 
In other words, investors are willing to pay a premium for options to have protection against significant market crashes even if statistically the probability of these crashes is lesser or even negligible.
Therefore, the tendency of implied volatility is to be higher than realized volatility, thus V-R-P being positive.
 Realized/Historical Volatility 
Historical Volatility (HV) is the statistical measure of the dispersion of returns for an index over a given period of time.
Historical volatility is a well-known concept in finance, but there is confusion in how exactly it is calculated. Different sources may use slightly different historical volatility formulas.
For calculating Historical Volatility I am using the most common approach: annualized standard deviation of logarithmic returns, based on daily closing prices.
 Implied Volatility 
Implied Volatility (IV) is the market's forecast of a likely movement in the price of the index and it is expressed annualized, using percentages and standard deviations over a specified time horizon (usually 30 days).
IV is used to price options contracts where high implied volatility results in options with higher premiums and vice versa. Also, options supply and demand and time value are major determining factors for calculating Implied Volatility.
Implied Volatility usually increases in bearish markets and decreases when the market is bullish.
For determining S&P500 and Nasdaq-100 implied volatility I used their volatility indices: VIX and VXN (30-day IV) provided by CBOE.
 Warning 
 
 Please be aware that because CBOE doesn’t provide real-time data in Tradingview, my V-R-P calculation is also delayed, so you shouldn’t use it in the first 15 minutes after the opening.
 This indicator is calibrated for a daily time frame.
 
 ESPAŇOL 
Este indicador (V-R-P) calcula la Prima de Riesgo de Volatilidad (de un mes) para S&P500 y Nasdaq-100.
V-R-P es la prima que pagan los hedgers sobre la Volatilidad Realizada para las opciones de los índices S&P500 y Nasdaq-100.
La prima proviene de los hedgers que pagan para asegurar sus carteras y se manifiesta en el diferencial entre el precio al que se venden las opciones (Volatilidad Implícita) y la volatilidad que finalmente se realiza en el S&P500 y el Nasdaq-100 (Volatilidad Realizada).
Estoy utilizando la Volatilidad Implícita (IV) de 30 días y la Volatilidad Realizada (HV) de 21 días como base para mi cálculo, ya que un mes de IV se basa en 30 días calendario y un mes de HV se basa en 21 días de negociación.
Al principio, el indicador aparece en blanco y una etiqueta le indica que elija qué índice desea que el V-R-P represente en el gráfico. Use la configuración del indicador (la rueda dentada) para elegir uno de los índices (o ambos).
Junto con la línea V-R-P, el indicador mostrará su promedio móvil de un año dentro de un rango de +/- 15% (que puede cambiar) con fines de evaluación comparativa. Deberíamos considerar este rango como el V-R-P "normalizado" para el período real.
La línea Cero también está marcada en el indicador.
 Interpretación 
Cuando el V-R-P está dentro del rango "normalizado",... bueno... la volatilidad y la incertidumbre, como las ve el mercado de opciones, es "normal". Tenemos una “prima” de volatilidad que debería considerarse normal.
Cuando V-R-P está por encima del rango "normalizado", la prima de volatilidad es alta. Esto significa que los inversores están dispuestos a pagar más por las opciones porque ven una creciente incertidumbre en los mercados.
Cuando el V-R-P está por debajo del rango "normalizado" pero es positivo (por encima de la línea Cero), la prima que los inversores están dispuestos a pagar por el riesgo es baja, lo que significa que ven una disminución, pero no pronunciada, de la incertidumbre y los riesgos en el mercado.
Cuando V-R-P es negativo (por debajo de la línea Cero), tenemos COMPLACENCIA. Esto significa que los inversores ven el riesgo próximo como menor que lo que sucedió en el mercado en el pasado reciente (en los últimos 30 días).
 
 CONCEPTOS: 
 Prima de Riesgo de Volatilidad 
La Prima de Riesgo de Volatilidad (V-R-P) es la noción de que la Volatilidad Implícita (IV) tiende a ser más alta que la Volatilidad Realizada (HV) ya que los participantes del mercado tienden a sobrestimar la probabilidad de una caída significativa del mercado.
Esta sobreestimación puede explicar un aumento en la demanda de opciones como protección contra una cartera de acciones. Básicamente, esta mayor percepción de riesgo puede conducir a una mayor disposición a pagar por estas opciones para cubrir una cartera.
En otras palabras, los inversores están dispuestos a pagar una prima por las opciones para tener protección contra caídas significativas del mercado, incluso si estadísticamente la probabilidad de estas caídas es menor o insignificante.
Por lo tanto, la tendencia de la Volatilidad Implícita es de ser mayor que la Volatilidad Realizada, por lo cual el V-R-P es positivo.
 Volatilidad Realizada/Histórica 
La Volatilidad Histórica (HV) es la medida estadística de la dispersión de los rendimientos de un índice durante un período de tiempo determinado.
La Volatilidad Histórica es un concepto bien conocido en finanzas, pero existe confusión sobre cómo se calcula exactamente. Varias fuentes pueden usar fórmulas de Volatilidad Histórica ligeramente diferentes.
Para calcular la Volatilidad Histórica, utilicé el enfoque más común: desviación estándar anualizada de rendimientos logarítmicos, basada en los precios de cierre diarios.
 Volatilidad Implícita 
La Volatilidad Implícita (IV) es la previsión del mercado de un posible movimiento en el precio del índice y se expresa anualizada, utilizando porcentajes y desviaciones estándar en un horizonte de tiempo específico (generalmente 30 días).
IV se utiliza para cotizar contratos de opciones donde la alta Volatilidad Implícita da como resultado opciones con primas más altas y viceversa. Además, la oferta y la demanda de opciones y el valor temporal son factores determinantes importantes para calcular la Volatilidad Implícita.
La Volatilidad Implícita generalmente aumenta en los mercados bajistas y disminuye cuando el mercado es alcista.
Para determinar la Volatilidad Implícita de S&P500 y Nasdaq-100 utilicé sus índices de volatilidad: VIX y VXN (30 días IV) proporcionados por CBOE.
 Precaución 
 
 Tenga en cuenta que debido a que CBOE no proporciona datos en tiempo real en Tradingview, mi cálculo de V-R-P también se retrasa, y por este motivo no se recomienda usar en los primeros 15 minutos desde la apertura.
 Este indicador está calibrado para un marco de tiempo diario.
SAR+RSI+EMAs SignalsNOTE: 
Indicator based strategies may expire and begin to work again. There are various ways to check the expiration of these strategies but I suggest equity curve trading (EC trading) as the best one.
Please check every single indicator based strategy to see if it’s still profitable or it has been expired to avoid losses.
Principles:
I personally believe every profitable indicator-based setup need 3 factors. Actually I analyze indicator-based set up in this way!  
1-	Trend detector: a tool that detect the “trend”.
2-	Oscillators (Discount finder): a tool that detects “discounts” in the direction of the trend.
3-	Stimulus: A tool that indicates the Initiation of a movement.
There may be profitable strategies that do not use all three, because other factors are strong enough to lead us to profit, but they are rare and sometimes they hide the other forgotten factor in the main two ones.
Elements:
(Since most of traders here, are familiar with these famous indicators I will not take your time to write about their uses and formula)
SAR: As a Trend detector, regarding position of close and SAR
EMA 7 and EMA 21: As trend detectors, regarding position of EMA 7 as fast “moving average” and EMA 21 as slow one. Also we need another confirmation for trend regarding EMA 7 and closing price of the signal candle. 
RSI:  In this strategy RSI is used both as a discount finder and a stimulus.
For RSI being over/under 50, regarding the trend, a possible discount may have been occurred. Imagine these conditions: close>EMA7, EMA7>EMA21, close>SAR and simultaneously RSI being under 50 is really a sign of powerful uptrend which it’s RSI decreasing might be a sign of corrective move, which will be following a bullish impulsive move.
The other use of RSI is to stimulate a buy signal by “crossing” over 50 or 30 (50 as balanced point of momentum and 30 as a sign of ending an oversold) or stimulate a sell signal by “crossing” under 50 or 70 (50 as balanced point of momentum and 70 as a sign of ending an overbought).
Entry point: you can use one of the followings.
1- Open of the next candle
2- EMA 7
3- Open of the signal candle
(Totally optional but “open of the next candle” is suggested by me.)
SL: Use one of the followings.
1-	SAR or some pips (regarding ATR Or your experience of this trading instrument’s fluctuations in this time frame) below the SAR
2-	Fixed amount (regarding ATR Or your experience of this trading instrument’s fluctuations in this time frame)
3-	Use EMA21 as dynamic SL (if a candle far enough from the initiative candle close over (for sell) below ( for buy)
Again number 1 is suggested by me.
TP: Use one of the followings.
1-	Use static levels or zones of support and resistance as TP. 
2-	Use dynamic levels for instance band of BB or moving averages (Moving the SL is possible).
3-	Use fixed R to R
And I believe static zones of support and resistance work better.
Examples:
  
I indicate a buy signal on the chart! 
  
Using local level as TP worked just good.
  
Using EMA was better in this case.
  
  
And using a riskier level or a fixed R to R is obvious in the chart!
Since in the range markets, this strategy may not work well and at the same time, TP to SL might be too small to be worth the risk, I prefer to use levels to filter range market conditions!
  
I convert all those circumstances to a simple buy and sell signs on the chart! 
EMA21 and SAR are still visible because it is possible that traders use them for their TP and SL.
  
This is how it look without EMA21 and SAR!
  
Another screenshot of this strategy!
  
I also add a check box to filter signals by another trend detector. MATD created by me to help traders detect trend! 
As it’s visible, some profitable signals filtered too, but using a longer-term trend detector as an additional one, alongside the double EMAs is very useful for this strategy.
The other box “use high&low instead of close for fast EMA” makes the “EMA7 and close” trend detector an easygoing one! 
Almost everything is editable here!
*** I did not invent this strategy, you can find it for free on net *** 
I'll change it to a "strategy" instead of an indicator if reader like to!
Jurik MacD & Leader NCMhey everyone,
While there are some Invite-Only Jurik MacDs, there are no free/open ones, so I thought I'd create one and publish it. It has most of the bells and whistles you'd want (I hope!). 
You can see one with the bells and whistles all turned on in the first, and a 'quieter' one in the second.
//-----------------////-----------------////-----------------//
Why Jurik?
The Jurik MA is a quicker and smoother Exponential MA, and the best of all MAs, according to Jurik Research (lol). To be fair. I have found it to be excellent, and that is why I'm publishing this.
Power can be changed, recommended from 1-4: increasing it pulls it closer to the current price (almost like reducing the period), and decreasing: vice versa.
Phase increases the inertia of the line, how quickly it will respect price changes. It is usual to have less inertia on the fast JMA, and more on the slower (but remember the MACD line is the FastJMA minus the SlowJMA, so you may find adjusting power and phase on Signal line more effective). Search online for JurikRes (or Jurik Research) for more detailed information about the Jurik.
In the coding I have included a list of four different ways to set up the JMAs: however, you should probably tune this to your preferred asset (as with almost all indicators). If you find a good setup, please let me know!
You could trade with a MacD a number of ways. Entries could be:
- MacD crossing the zero line
- MacD crossing over the Signal line
- Histogram crossing above zero line.
Vice versa for exits. If this isn't enough, please google 'trading with a MacD'. 
No indicator is perfect for trading, and that includes this one! Don't trade unless you know what you're doing.
//-----------------////-----------------////-----------------//
Please let me know if I can improve this script, or you have any other feedback. I can post code for colour palette as well if that is something anyone is keen on. 
//-----------------////-----------------////-----------------//
Thanks to the many excellent coders that publish freely their code. I have learned so much from this community, and this code is based on the work of others (Chris Moody and everget).
Shout out to StevieMagg as well, who has helped me develop (and didn't want to charge me!). The Pine Script Community on Discord has been brilliant - lots of knowledge, ideas, support - thanks guys. 
If you are new and interested in pine coding, I suggest you check out some of the masters (in no order):
ChrisMoody
Everget
RedKTrader
LonesomeDove
LazyBear
KivancOzbilgic
and more that I am missing. It is not necessarily the popular scripts that are the best.
//-----------------////-----------------////-----------------//
Kind regards,
Nelson
Volume X-ray [LucF]█  OVERVIEW 
This tool analyzes the relative size of volume reported on intraday vs EOD (end of day) data feeds on historical bars. If you use volume data to make trading decisions, it can help you improve your understanding of its nature and quality, which is especially important if you trade on intraday timeframes.
I often mention, when discussing volume analysis, how it's important for traders to understand the volume data they are using: where it originates, what it includes and does not include. By helping you spot sizeable differences between volume reported on intraday and EOD data feeds for any given instrument, "Volume X-ray" can point you to instruments where you might want to research the causes of the difference.
█  CONCEPTS 
The information used to build a chart's historical bars originates from data providers (exchanges, brokers, etc.) who often maintain distinct historical feeds for intraday and EOD timeframes. How volume data is assembled for intraday and EOD feeds varies with instruments, brokers and exchanges. Variations between the two feeds — or their absence — can be due to how instruments are traded in a particular sector and/or the volume reporting policy for the feeds you are using. Instruments from crypto and forex markets, for example, will often display similar volume on both feeds. Stocks will often display variations because  block trades  or other types of trades may not be included in their intraday volume data. Futures will also typically display variations. It is even possible that volume from different feeds may not be of the same nature, as you can get trade volume (market volume) on one feed and tick volume (transaction counts) on another. You will sometimes be able to find the details of what different feeds contain from the technical information provided by exchanges/brokers on their feeds. This is an example for the  NASDAQ feeds . Once you determine which feeds you are using, you can look for the reporting specs for that feed. This is all research you will need to do on your own; "Volume X-ray" will not help you with that part.
You may elect to forego the deep dive in feed information and simply rely on the figure the indicator will calculate for the instruments you trade. One simple — and unproven — way to interpret "Volume X-ray"  values is to infer that instruments with larger percentages of intraday/EOD volume ratios are more "democratic" because at intraday timeframes, you are seeing a greater proportion of the actual traded volume for the instrument. This could conceivably lead one to conclude that such volume data is more reliable than on an instrument where intraday volume accounts for only 3% of EOD volume, let's say.
Note that as intraday vs EOD variations exist for historical bars on some instruments, there will typically also be differences between the realtime feeds used on intraday vs 1D or greater timeframes for those same assets. Realtime reporting rules will often be different from historical feed reporting rules, so variations between realtime feeds will often be different from the variations between historical feeds for the same instrument. A deep dive in reporting rules will quickly reveal what a jungle they are for some instruments, yet it is the only way to really understand the volume information our charts display.
█  HOW TO USE IT 
The script is very simple and has no inputs. Just add it to 1D charts and it will calculate the proportion of volume reported on the intraday feed over the EOD volume. The plots show the daily values for both volumes: the teal area is the EOD volume, the orange line is the intraday volume. A value representing the average, cumulative intraday/EOD volume percentage for the chart is displayed in the upper-right corner. Its background color changes with the percentage, with brightness levels proportional to the percentage for both the bull color (% >= 50) or the bear color (% < 50). When abnormal conditions are detected, such as missing volume of one kind or the other, a yellow background is used.
Daily and cumulative values are displayed in indicator values and the Data Window.
The indicator loads in a pane, but you can also use it in overlay mode by moving it on the chart with "Move to" in the script's "More" menu, and disabling the plot display from the "Settings/Style" tab.
█  LIMITATIONS 
 • The script will not run on timeframes >1D because it cannot produce useful values on them.
 • The calculation of the cumulative average will vary on different intraday timeframes because of the varying number of days covered by the dataset.
  Variations can also occur because of irregularities in reported volume data. That is the reason I recommend using it on 1D charts.
 • The script only calculates on historical bars because in real time there is no distinction between intraday and EOD feeds.
 • You will see plenty of special cases if you use the indicator on a variety of instruments:
   • Some instruments have no intraday volume, while on others it's the opposite.
   • Missing information will sometimes appear here and there on datasets.
   • Some instruments have higher intraday than EOD volume.
  Please do not ask me the reasons for these anomalies; it's your responsibility to find them. I supply a tool that will spot the anomalies for you — nothing more.
█  FOR PINE CODERS 
 • This script uses a little-known feature of  request.security() , which allows us to specify `"1440"` for the `timeframe` argument. 
  When you do, data from the 1min intrabars of the historical intraday feed is aggregated over one day, as opposed to the usual EOD feed used with `"D"`.
 • I use gaps on my  request.security()  calls. This is useful because at intraday timeframes I can cumulate non- na  values only.
 • I use  fixnan()  on some values. For those who don't know about it yet, it eliminates  na  values from a series, just like not using gaps will do in a  request.security()  call.
 • I like how the new  switch  structure makes for more readable code than equivalent  if  structures.
 • I wrote my script using the revised recommendations in the  Style Guide  from the Pine v5 User Manual.
 • I use the new  runtime.error()  to throw an error when the script user tries to use a timeframe >1D. 
  Why? Because then, my  request.security()  calls would be returning values from the last 1D intrabar of the dilation of the, let's say, 1W chart bar.
  This of course would be of no use whatsoever — and misleading. I encourage all Pine coders fetching HTF data to protect their script users in the same way.
  As tool builders, it is our responsibility to shield unsuspecting users of our scripts from contexts where our calcs produce invalid results.
 • While we're on the subject of accessing intrabar timeframes, I will add this to the intention of coders falling victim to what appears to be 
  a new misconception where the mere fact of using intrabar timeframes with  request.security()  is believed to provide some sort of edge.
  This is a fallacy unless you are sending down functions specifically designed to mine values from  request.security() 's intrabar context.
  These coders do not seem to realize that:
   • They are only retrieving information from the last intrabar of the chart bar.
   • The already flawed behavior of their scripts on historical bars will not improve on realtime bars. It will actually worsen because in real time, 
    intrabars are not yet ordered sequentially as they are on historical bars.
   • Alerts or strategy orders using intrabar information acquired through  request.security()  will be using flawed logic and data most of the time.
  The situation reminds me of the mania where using Heikin-Ashi charts to backtest was all the rage because it produced magnificent — and flawed — results.
  Trading is difficult enough when doing the right things; I hate to see traders infected by lethal beliefs.
  Strive to sharpen your "herd immunity", as Lionel Shriver calls it. She also writes: "Be leery of orthodoxy. Hold back from shared cultural enthusiasms." 
  Be your own trader.
█  THANKS 
This indicator would not exist without the invaluable insights from Tim, a member of the Pine team. Thanks Tim!
CAGR Custom Range█  OVERVIEW 
This script calculates an annualized  Compound Annual Growth Rate  from two points in time which you can select on the chart. It previews an upcoming feature where Pine scripts will be able to provide users with interactive inputs for time and price values.
👉🏼 We are looking for feedback on our first take of this feature.
     Please comment in this publication's "Comments" section if you have suggestions for improvement.
█  HOW TO USE IT 
When you first load this script on a chart, you will enter the new interactive selection mode. At that point, the script is waiting for you to pick two points in time on your chart by clicking on the chart. Once you select the two points, the script will find the  close  value for each of the two selected bars, and calculate the CAGR value from them. It will then display a line between the two points, and the CAGR value above or below the last point in time.
If the CAGR value is positive, the line and label will display in their "up" color (see the "🠅" color in the script's "Settings/Inputs" tab), otherwise they appear in their "down" color (the "🠇" color in the inputs). You can also control the line's width from the inputs.
You have the option of comparing the chart's CAGR value with that of another symbol, which you specify in the "Compare to" input. When a comparison is made, the label's background color will be dependent on the result of the comparison. The line's color will still be determined by the chart's value.
Once time points have been selected on the chart and the script is displaying the line, you can change the time points by clicking on the script's name on the chart. A small, blue rectangular handle will then appear for each point, which you can then grab and move. If you reset the inputs using the "Defaults/Reset Settings" button in the script's inputs, the two time points will reset to the beginning of September and October 2021, respectively.
█  CONCEPTS 
The CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It calculates from the  close  value of the two end points. It does not account for drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two instruments. Because it annualizes values, the function requires a minimum of one day between the two end points (annualizing returns over smaller periods of times doesn't produce very meaningful figures).
█  LIMITATIONS 
 • The two selected points must be distant from a minimum of one day. A runtime error will occur otherwise.
 • There is currently no way to restart the interactive mode from scratch without re-adding the script to the chart.
 • The points in time you select on one chart may map quite differently on other charts,
  depending on their constituent bars (e.g., intraday charts for 24x7 and conventional markets).
█  FOR PINE CODERS 
 • Our script uses the most recent version of Pine, as the `//@version=5` compiler directive indicates.
 • Interactive inputs were a long-standing and highly-requested feature by our beloved community of Pine coders.  
  We hope you find this first step promising, as it opens up entirely new possibilities for both Pine coders and script users. 
  You can, for example, use interactive inputs to draw shapes with your scripts, or support and resistance levels, etc.
  We're sure you'll come up with more creative uses of the feature than we could ever dream up )
 • Interactive inputs are implemented for  input.time()  and  input.price() , the specialized input functions now available in v5.
  See the User Manual's  new page on inputs  for more information about them.
  You can also create one interactive input for both time and price values 
  by using the same `inline` argument in a pair of  input.time()  and  input.price()  function calls.
 • Our min/max filtering when initializing `entryTime` and `exitTime` will handle cases where 
  the script user inverts the two points on the chart.
 • The script uses the new  runtime.error()  function to throw an error in the `if days < 1` conditional structure.
 • We use the `cagr()` function from our recently-published  ta Pine library .
   Pine libraries  — not to be confused with the  Public Library  showcasing scripts published by our community of Pine coders —
  are one of the new features available with the recent Pine v5.
 • Note that our `strRightOf()` function cannot be used to generate ticker identifier strings for use in `request.*()` functions.
  This is because it produces results of "series" form while the functions require 
  arguments of "simple" form for their `symbol` or `ticker` parameters.
  Have a look at our new User Manual page on Pine's  Type system  if you need to brush up on Pine forms and types.
 • We use a simple, repainting  request.security()  call because our calculations are not used to generate orders or alerts.
 • We document our user-defined functions using the same compiler directives used in  exported functions  in libraries.
  It will make conversion of those functions to library format easier if we ever choose to do so.
 • We use two Unicode hair spaces (U+200A) to push the "%" sign slightly away from values in our  str.format()  calls.
  While the impact is minimal, it increases readability.
 • Note the `priceIsHigh` logic used to determine if we place the label above or below bars.
  When price is higher than recent prices, we place the label above the bar, otherwise we place it below.
  It's not foolproof but it provides optimal positioning most of the time.
 • The point of the complicated "bool" expression initializing `displayCAGR` is to ensure that we only draw the line and labels once.
  When no comparison with another symbol is made, this occurs the first time we encounter a non- na  value from the `cagr()` function.
  When a comparison is required, it occurs the first time both values are not  na .
 • Before all mentions of "CAGR" in our description, we use a Unicode zero-width space (U+200B) 
  to prevent the auto-linking feature to kick in for the term. 
  This prevents the dashed underscore and a link like this (CAGR) from appearing every time "CAGR" is mentioned.
 • With Pine v5, the `study()` declaration statement was renamed to  indicator() .
  Accordingly, we will be eliminating the use of the "study" term from documentation and the UI.
  The generic "script" term will continue to designate Pine code that can be an indicator, a strategy or a library, when applicable.
 • We followed our new  Style guide  recommendations to write our script.
 • We used the techniques explained in the  How We Write and Format Script Descriptions  publication by PineCoders.
 • That's it! We've covered all the new features and tricks we used. We sincerely hope you enjoy the new interactive inputs, 
  and please remember to comment here if you have suggestions for improvement. 💙
 Look first. Then leap.  
Matrix_Functions_Lib_JDLibrary   "Matrix_Functions_Lib_JD" 
This is a library to add matrix / 2D array functionality to Pinescript.
once you import the library at the beginning of your script, you can add all the functions described below just by calling them like you do any other built'in function.
Enjoy,
Gr, JD.
PS. if you find functionality or calculation errors in the functions, please let me know, so I can fix them.
There are quite a lot of functions, so little mishaps may have slipped in! ;-)
 get_nr_of_rows()  Returns the number of rows from a 2D matrix
 get_nr_of_columns()  Returns the number of columns from a 2D matrix
 get_size()  Returns a tuple with the total number of rows and columns from a 2D matrix
 init()  2D matrix init function, builds a 2D matrix with dimensional metadata in first two values and fills it with a default value, the body of the actual matrix data starts at index 2.
 from_list()  2D matrix init function, builds a 2D matrix from an existing array by adding dimensional metadata in first two values, the body of the actual matrix data consists of the data of the source array and starts at index 2.
 set()  Sets values in 2D matrix with (row index, column index) (index for rows and columns both starts at 0 !!)
 fill_val()  Fills all elements in a 2D matrix with a value
 randomize()  Fills a 2D matrix with random values//
 get()  Gets values from 2D matrix with (row index, column index) (index for rows and columns both starts at 0 !!)
 copy_slice_body()  Cuts off the metadata header and returns the array body, WITHOUT THE DIMENSIONAL METADATA!!
do_slice This variable should be set as: - 'false' to only make a copy, changes to the new array copy will NOT ALTER the ORIGINAL - 'true' to make a slice, changes to the new array slice WILL(!) ALTER the ORIGINAL
 get_record()  Gets /retrieve the values from a ROW/RECORD from a certain row/lookback period, the values are returned as an array
 get_row_index()  Gets the row nr. in a 2D matrix from 1D index (index for rows and columns both starts at 0 !!)
 get_column_index()  Gets the column nr. in a 2D matrix from 1D index (index for rows and columns both starts at 0 !!)
 get_row_column_index()  Gets a tuple with the (row, column) coordinates in 2D matrix from 1D index (index starts at 0 and does not include the header!!)
 get_array_index()  Gets the 1D index from (row, column) coordinates in 2D matrix (index for row and column both starts at 0 !! Index starts at 0 and does not include the header!!)
 remove_rows()  Removes one or more rows/records from a 2D matrix (if from_row = to_row, only this row is removed)
 remove_columns()  Remove one or more columns from a 2D matrix (if from_column = to_column, only this column is removed)
 insert_array_of_rows()  Insert an array of rows/records at a certain row number in a 2D matrix
 add_row()  ADDS a ROW/RECORD on the TOP of a sheet, shift the whole list one down and gives the option to REMOVE the OLDEST row/record. (2D version of "unshift" + "pop" but with a whole row at once)
 insert_array_of_columns()  Insert an array of columns at a certain column number in a 2D matrix
 append_array_of_rows()  Appends/adds an array of rows/records to the bottom of a 2D matrix
 append_array_of_columns()  Appends/adds an array of columns to the right side of a 2D matrix
 pop_row()  Removes / pops and returns the last row/record from a 2D matrix.
 pop_column()  Removes / pops and returns the last (most right) column from a 2D matrix.
 replace()  
 abs()  
 add_value()  Returns a new matrix with the same value added to all the elements of the source matrix.
 addition()  Returns a new matrix with the of the elements of one 2D matrix added to every corresponding element of a source 2D matrix.
 subtract_value()  Returns a new matrix with the same value subtracted from every element of a 2D matrix
 subtraction()  Returns a new matrix with the values of the elements of one 2D matrix subtracted from every corresponding element of a source 2D matrix.
 scalar_multipy()  Returns a new matrix with all the elements of the source matrix scaled/multiplied by a scalar value.
 transpose()  Returns a new matrix with the elements of the source matrix transposed.
 multiply_elem()  Performs ELEMENT WISE MULTIPLICATION of 2D matrices, returns a new matrix c.
 multiply()  Performs DOT PROCUCT MULTIPLICATION of 2D matrices, returns a new matrix c.
 determinant_2x2()  Calculates the determinant of 2x2 matrices.
 determinant_3x3()  Calculates the determinant of 3x3 matrices.
 determinant_4x4()  Calculates the determinant of 4x4 matrices.
 print()  displays a 2D matrix in a table layout.






















