Test - Most correlated assetThis is a simple test to find the most and least correlated assets in a list.
Statistics
TimeSeriesGrammianAngularFieldLibrary "TimeSeriesGrammianAngularField"
provides Grammian angular field and associated utility functions.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
www.researchgate.net
method normalize(data, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.
Namespace types: array
Parameters:
data (array) : Sample data to normalize.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized array within new range.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
normalize_series(source, length, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.\
*Note that this may provide a different result than the array version due to rolling range*.
Parameters:
source (float) : Series to normalize.
length (int) : Number of bars to sample the range.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized series within new range.
method polar(data)
Turns a normalized sample array into polar coordinates.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Converted array into polar coordinates.
polar_series(source)
Turns a normalized series into polar coordinates.
Parameters:
source (float) : Source series.
Returns: Converted series into polar coordinates.
method gasf(data)
Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
method gasf_id(data)
Trig. identity of Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
method gadf(data)
Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
method gadf_id(data)
Trig. identity of Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
CCOMET_Scanner_LibraryLibrary "CCOMET_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing CCOMET Scanners
Loc_tIDs_Col(_string, _firstLocation)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your CCOMET Scanner.
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my CCOMET Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the TickerIDs, 40 variables for the locations for alert labels, and 40 Colors for labels/plots
TickeridForLabelsAndSecurity(_ticker, _includeExchange)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
_includeExchange (simple bool) : (bool)
Optional (if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your CCOMET Scanner as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the CCOMET Scanner's input.
InvalID_LblSz(_barCnt, _close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your CCOMET Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_close (float) : (float)
Put your 'close' variable named '_close' from the security function here.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never registered then the logic counts the asset as INVALID.
This will be the 1st TickerID variable (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (array) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
_tablePosition (simple string) : (string)
Optional (if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional (if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here, otherwise they will all be in a row.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
Volume Footprint Voids [BigBeluga]Volume Footprint Voids is a unique tool that uses lower timeframe calculation to plot different styles of single candle POC.
This indicator is very powerful for scalping and finding very precise entry and exits, spotting potential trapped traders, and more.
Unlike many other volume profiles, this aims to plot single candle profiles as well as their own footprints.
🔶 FEATURES
The script includes the following settings:
Windows: Plotting style and calculations
Coloring modes
Display modes
lower-timeframe calculations
🔶 CALCULATION
In the image above we can see how the script calculates each level position that will serve as a calculation process to see how much volume/closes there are within the levels.
In the image above, we can have a more clear example of how we count each candle close.
We use the prior screenshot as an example, after setting each level we will use the lower-timeframe input to measure the amount of closes within the ranges.
Depending on the lot size, the box will be larger or smaller, usually the POC will always have the highest box size.
NOTE: Size is the starting point, always from the low of the candle.
To find more voids, select a closer LTF to the current one you're using.
To find fewer voids, select a timeframe away from your current one.
Due to Pine Script limitations, we are only able to plot a certain amount of footprints, and we can't plot the whole history chart.
POC will be the largest block displayed, indicating the time point of control
Gray areas are closes above the average
Black are Void or imbalance that price will fill in the future, like FVG
The image above shows an incorrect size input that will lead to bad calculations, while on the other side, a correct size input that will lead to a clear vision and better calculation.
🔶 WINDOWS
The "▲▼" Mode will display delta buyers and delta sellers coloring with voids as black.
It also offers a gradient mode for a beautier visualization
The "Total Volume" mode will display the net volume within the lot size (closes within the levels).
This is useful to spot possible highest net volume within the same highest lot size.
The "POC + Gaps" will show both POC and Gaps as the highest block while all the rest will be considered as the smaller block.
This is useful to see where the highest lot were and if there are higher or lower imbalances within the candle
The last option "Gaps" will simply display the gaps as the highest block, while the POC as the lowest block.
This is useful to have a better view of the gaps areas
🔶 EXAMPLE
This is one of the most basic examples of how this script can be used. POC at the bottom creating a strong support area as price holds and creates higher voids gap that price fills while rising.
🔶 SETTINGS
Users have full control over the script, from colors to choosing the lower-timeframe inputs to disabling the lot size.
Drawdown % (with SMA)This script, titled "Drawdown % (with SMA)" and designed for Pine Script version 5
offers a sophisticated tool for traders to monitor drawdown percentages, a crucial metric in assessing investment risks. The script calculates the drawdown as the percentage decrease from the all-time high value of the selected financial instrument.
Portfolio Management [TrendX_]Portfolio Management is a powerful tool that helps you create and manage your own portfolio of stocks, based on your risk and return preferences.
*** Note: You should select the appropriate index for each stock as the benchmark to compare your portfolio’s performance.
*** Note: You should apply the indicator to the same chart as the benchmark, so that it can capture the historical trends of all the 10 stocks in your portfolio.
USAGE
Analyze your portfolio’s return factor, which shows the compound annual growth rate (CAGR) of each stock and the portfolio as a whole, as well as the weight of each stock in the portfolio.
The Weighting approach contains 2 options, Equal and Growth-based method:
Customize your portfolio by selecting up to 10 stocks from a wide range of markets and sectors:
Compare your portfolio’s performance with a benchmark of your choice, which is the S&P500 by default setting.
Evaluate your portfolio’s risk factor, which includes the capital asset pricing model (CAPM), the portfolio beta, and the Sharpe ratio of both the portfolio and the benchmark:
- CAPM is a model that calculates the expected return of the portfolio based on its risk and the risk-free rate of return.
- Portfolio beta is a measure of how sensitive the portfolio is to the movements of the benchmark. A beta of 1 means the portfolio moves in sync with the benchmark, a beta of less than 1 means the portfolio is less volatile than the benchmark, and a beta of more than 1 means the portfolio is more volatile than the benchmark.
- Sharpe ratio measures how much excess return the portfolio generates per unit of risk. It is calculated by subtracting the risk-free rate of return from the portfolio’s return, and dividing by the portfolio’s standard deviation. A higher Sharpe ratio means the portfolio has a better risk-adjusted return. A Sharpe ratio of more than 1 is considered good, a Sharpe ratio of more than 2 is considered very good, and a Sharpe ratio of more than 3 is considered excellent .
Adjust your portfolio’s rebalancing strategy, which determines when and how to change the weight of each stock in the portfolio to optimize your return and risk objectives. The tool also suggests a default hedging-stock asset, which is the US dollar interpreted through the dollar index (DXY):
- The dollar index is a measure of the value of the US dollar relative to a basket of other major currencies. It is often used as a proxy for the global economic sentiment and the demand for safe-haven assets. A rising dollar index means the US dollar is strengthening, which may indicate a bearish outlook for the stock market. A falling dollar index means the US dollar is weakening, which may indicate a bullish outlook for the stock market.
- The rebalancing strategy suggest increasing the weight of the hedging-stock asset when the dollar index is under positive supertrend condition, and decreasing the weight of the hedging-stock asset when the dollar index is in the downward supertrend. This way, you can hedge against the adverse effects of the stock market fluctuations on your portfolio, simply you can just cash out at the suggested hedging weight.
CONCLUSION
Investors can gain a deeper insight into their portfolio’s performance, risk, and potential, and make informed decisions to achieve their financial goals with confidence and ease.
DISCLAIMER
The results achieved in the past are not all reliable sources of what will happen in the future. There are many factors and uncertainties that can affect the outcome of any endeavor, and no one can guarantee or predict with certainty what will occur.
Therefore, you should always exercise caution and judgment when making decisions based on past performance.
Qullamaggie ADR and Volatility and Price Change IndicatorElevate your trading strategy with Qullamaggie ADR, a dynamic indicator inspired by the Kristjan Qullamaggie trading approach. Gain a deeper understanding of market dynamics, daily price movements, and potential turning points.
Key Features:
Qullamaggie ADR: Assess market volatility through the QullaADR, offering customizable time intervals (5, 10, 15, 20 days) to adapt to various trading styles.
Today's Change: Monitor price changes relative to the low of the current trading day, providing valuable intraday insights.
PrevDay price differentials from the previous day's low, aiding in the identification of potential trend reversals.
Track the percentage change from the opening price, offering a snapshot of intraday market sentiment.
Percent from 10-day SMA: Visualize the percentage difference between the closing price and a 10-day Simple Moving Average (SMA), a key trend-following indicator.
Usage:
Utilize QullaADR to set realistic profit targets and stop-loss levels based on current market conditions.
Identify potential trend shifts by observing changes from the previous day's low with Today's QullaChange.
Incorporate QullaPercent from 10-day SMA for trend confirmation and well-informed trading decisions.
Strategy Inspiration:
QullaADR draws inspiration from the Kristjan Qullamaggie trading strategy, aiming to complement your trading toolkit and enhance decision-making.
Disclaimer:
Trading involves risk, and past performance is not indicative of future results. Use this indicator as a supplementary tool within a comprehensive trading strategy.
Version: 1.0
Sessions [TradingFinder] New York, London, Tokyo & Sydney ForexTiming is one of the influential factors in a trader's position. This indicator categorizes transactions into three sessions (Asia, Europe, and America). Five significant trading cities (New York, London, Frankfurt, Tokyo, and Sydney) are selectable.
I recommend using the tool on a 5-minute time frame, but it is usable on all time frames.
Settings:
• Trading sessions: Display or hide each trading session as needed.
• Color: Change the color of each box.
• Session time intervals: The default is based on the main working hours for each time interval and can be adjusted.
• Information table: Delete or display additional information table.
Information Table:
• Trading sessions
• Opening and closing times of each trading session
How to Use:
Initiating trading sessions involves entering with increased liquidity, and the market usually experiences significant movements. Many trading strategies are based on "time" and "session openings." This tool empowers traders to focus intensely on each time interval.
These trading sessions are crucial for all Forex, stock, and index traders:
The total price ceiling and floor in the Asia session (Tokyo and Sydney) are crucial for traders in the European session.
The European session starts with Frankfurt, and an hour later, London begins, collectively forming the European session.
The dashboard provides additional information, displaying hours based on UTC.
Customization options are considered in all sections so that everyone can apply their own settings.
Important: Default times are the most accurate for each region, and in most indicators, this time is not correctly selected. Therefore, the level of influence and time intervals are specified at the beginning of each session. If you are using another indicator, match its default time to the announced time and share the results with me in the comments.
Kendall's Tau Correlation Regimes [NariCapitalTrading]The "Kendall's Tau Correlation Regimes" indicator is designed to analyze price data and determine market regimes based on Kendall's Tau correlation coefficient. It provides insight into the strength and direction of the correlation between two data series: close price and a selected moving average.
User Inputs:
Period: Defines the lookback period for calculating Kendall's Tau correlation. It can be adjusted using the input slider, with a minimum value of 1.
Threshold: Sets the threshold for identifying bullish and bearish market regimes. The user can adjust this value within the range of 0.1 to 1.0 with step increments of 0.1.
MA Type: Allows users to select the type of moving average to be used in the correlation calculation. Options include Simple Moving Average (SMA), Exponential Moving Average (EMA), and Hull Moving Average (HMA).
Kendall's Tau Correlation Calculation:
Calculates Kendall's Tau correlation coefficient between the closing price and the selected moving average.
Kendall's Tau measures the strength and direction of the ordinal association between two data series. It assesses whether the data pairs are in the same order or not.
The calculation involves counting concordant and discordant pairs of data points and then computing the coefficient.
Market Regime Identification:
Based on the threshold defined by the user, the indicator identifies two market regimes: bullish and bearish.
A regime is considered bullish when the Kendall's Tau correlation coefficient is greater than the threshold.
A regime is considered bearish when the Kendall's Tau correlation coefficient is less than the negative of the threshold.
Plotting:
The indicator plots the calculated Kendall's Tau correlation coefficient as a blue line on a separate indicator pane.
It also highlights bullish regimes with a green background and bearish regimes with a red background.
Conclusion:
The "Kendall's Tau Correlation Regimes" indicator provides traders with a visual aid for assessing market regimes based on the strength of correlation between price and a selected moving average.
Disclaimer: This indicator is for educational and informational purposes only.
Least Median of Squares Regression | ymxbThe Least Median of Squares (LMedS) is a robust statistical method predominantly used in the context of regression analysis. This technique is designed to fit a model to a dataset in a way that is resistant to outliers. Developed as an alternative to more traditional methods like Ordinary Least Squares (OLS) regression, LMedS is distinguished by its focus on minimizing the median of the squares of the residuals rather than their mean. Residuals are the differences between observed and predicted values.
The key advantage of LMedS is its robustness against outliers. In contrast to methods that minimize the mean squared residuals, the median is less influenced by extreme values, making LMedS more reliable in datasets where outliers are present. This is particularly useful in linear regression, where it identifies the line that minimizes the median of the squared residuals, ensuring that the line is not overly influenced by anomalies.
STATISTICAL PROPERTIES
A critical feature of the LMedS method is its robustness, particularly its resilience to outliers. The method boasts a high breakdown point, which is a measure of an estimator's capacity to handle outliers. In the context of LMedS, this breakdown point is approximately 50%, indicating that it can tolerate corruption of up to half of the input data points without a significant degradation in accuracy. This robustness makes LMedS particularly valuable in real-world data analysis scenarios, where outliers are common and can severely skew the results of less robust methods.
Rousseeuw, Peter J.. “Least Median of Squares Regression.” Journal of the American Statistical Association 79 (1984): 871-880.
The LMedS estimator is also characterized by its equivariance under linear transformations of the response variable. This means that whether you transform the data first and then apply LMedS, or apply LMedS first and then transform the data, the end result remains consistent. However, it's important to note that LMedS is not equivariant under affine transformations of both the predictor and response variables.
ALGORITHM
The algorithm randomly selects pairs of points, calculates the slope (m) and intercept (b) of the line, and then evaluates the median squared deviation (mr2) from this line. The line minimizing this median squared deviation is considered the best fit.
DISCLAIMER
In the LMedS approach, a subset of the data is randomly selected to compute potential models (e.g., lines in linear regression). The method then evaluates these models based on the median of the squared residuals. Since the selection of data points is random, different runs may select different subsets, leading to variability in the computed models.
Autocorrelation Candles [SS]Hey everyone, this is the Autocorrelation Candles indicator!
I have formulated it in a way that is similar to the TD 9 candle counting indicators, only instead of TD, its using a lagged autocorrelation of previous candle over a 14 period look back.
It operates similar to trend correlations (for example, my Trend Correlation Oscillator Indicator), however instead of correlating to time, it correlates to itself (autoregression). The theory being, as the autoregression correlation increases and the market becomes too "trendy", we are due for a reversal.
The indicator will display the current lagged correlation of each candle below it. When we approach a period of previous reversal, it will change the colour to orange. When we reach a very high autocorrelation (0.94 or greater), it will turn red and signal a potential reversal to the upside or downside:
Uses:
I will reference this on the larger timeframes (Daily, weekly and 4 hour) about a couple times a week or after a major trend day to see where we are.
You can use this on the smaller timeframes as well, it will work just fine.
Customizations:
I have been listening and learning my lesson, I have made the ability to customize the base text colour to black or white depending on your theme use! SO if you have white theme, you can change to black and vice versa.
As well, if you don't want labels on every candle, in the settings menu there is an option to limit the labels to a desired amount. You select the max amount and it will adjust.
You can also adjust the size of the labels between tiny, medium, and large.
Conclusion
And that's the indicator! Despite being fairly simple in concept, I have been working away on it for a bit with some logistic issues that I finally got sorted.
Hopefully, you enjoy,
Leave your questions below!
Safe trades everyone!
Advanced Volume Analytics and Distribution IndicatorThe Advanced Volume Analytics and Distribution Indicator is a sophisticated tool designed for financial analysts and traders who seek in-depth insights into market volume dynamics. This Pine Script-based indicator is a comprehensive solution, offering a rich set of features that analyze volume data using various statistical methods and theories. It's tailored for those who require a deeper understanding of market movements and volume distribution.
Key Features:
Volume Distribution Analysis: Utilizes standard deviation and mean calculations to analyze the distribution of trading volume. Employs z-scores to measure the standard deviations of volume from its mean, offering insights into volume anomalies.
Bell Curve Modeling: Constructs a bell curve (normal distribution) based on volume data, enabling users to visualize and assess the distribution of volume in a standard statistical format.
Provides a z-score based bell curve, offering a normalized view of volume deviations.
Exponential Smoothing: Applies exponential smoothing to volume data, giving more weight to recent observations. This feature is crucial for analyzing trending behaviors in volume data.
Stress Metric Calculation: Introduces a unique 'stress' metric, calculated using a custom formula. This metric is designed to evaluate the volatility or variability in the volume data over a specified period.
Central Limit Theorem (CLT) Mean Estimation: Implements CLT for estimating the mean of volume data. The CLT states that the distribution of sample means approximates a normal distribution as the sample size becomes larger.
Variance Point Estimation: Calculates the variance of volume data, providing insights into its variability and consistency over time.
Chi-Squared Test (Commented): Although not active in the initial release, the script includes a framework for a Chi-Squared Test to compare observed and expected volume frequencies, offering potential for future statistical comparisons.
Percentile Calculations and Convolution: Performs percentile calculations on volume data and employs convolution to these percentiles, enabling a more nuanced analysis of volume distribution.
Customizability: Users can input various parameters like anchor period, degrees of freedom, and smoothing preferences, making the tool adaptable to different analysis needs.
Visualization and Plotting: Features multiple plots for easy visualization of volume metrics, including stress, bell curves, point estimators, and smoothed data.
Theoretical Foundations:
This indicator is grounded in established statistical theories and methods, including the Central Limit Theorem, Chi-Squared Test (for future implementations), and convolution techniques. These foundations ensure that the indicator not only provides practical insights but also maintains a high standard of statistical rigor.
Intended Users:
This indicator is ideal for technical analysts, traders, and financial professionals who require a deep and statistically sound understanding of market volume behavior.
Release Notes:
This tool is designed a theoretical test of established statistical models and requires familiarity with Pine Script for customization. Future updates may include activation and expansion of the Chi-Squared Test functionality and additional statistical modules based on user feedback. It should be noted that it is advisable to use a logarithmic-inverted scale; when combined, these scales can provide a unique perspective that neither could offer alone. This combination might be particularly useful in highlighting exponential growth or decay trends, or in cases where the most significant data points are in the lower range of the dataset.
Notes of Stress Calculations:
The "stress metric" in the script is a custom-designed feature intended to measure the level of variability or volatility in the volume data over a given time period. This metric is calculated using a novel approach with concepts similar to those used in the field of engineering , particularly in stress analysis and finite element analysis (FEA).
Segmentation of Time Frame:
The script divides the given time frame (timeFrame) into smaller segments based on a specified number of units (units). This segmentation essentially breaks down the entire period into smaller, more manageable intervals for analysis. For each segment, the script calculates a 'stress' value. This involves iterating through each segment and performing calculations based on the source data (src), the default src is the volume data.
Calculation per Segment:
For each segment, the script identifies two points: the starting point (x1) and the ending point (x2). It then retrieves the corresponding values of the source data at these points (y1 and y2).
It calculates the difference in the x-axis (delta_x, the length of the segment) and the difference in the y-axis (delta_y, the change in volume over that segment).
Stress Calculation:
The script then calculates the 'stress' for each segment as the ratio of delta_y to delta_x. This ratio gives a measure of how much the volume has changed per unit of time within each segment. The stress values for each segment are then summed up to provide a cumulative measure of stress over the entire time frame.
The stress metric is essentially a measure of the volatility or variability in volume data. High stress values indicate larger changes in volume over shorter periods, suggesting more volatile market conditions. For traders and analysts, understanding the level of volatility is crucial. It can inform decision-making processes, risk management strategies, and provide insights into market sentiment. By comparing stress levels across different time frames or different securities, analysts can gain insights into relative market dynamics.
Blockunity Drawdown Visualizer (BDV)Monitor the drawdown (value of the drop between the highest and lowest points) of assets and act accordingly to reduce your risk.
Introducing BDV, the incredibly intuitive metric that visualizes asset drawdowns in the most visually appealing manner. With its color gradient display, BDV allows you to instantly grasp the state of retracement from the asset’s highest price level. But that’s not all – you have the option to display the oscillator’s colorization directly on your chart, enhancing your analysis even further.
The Idea
The goal is to provide the community with the best and most complete tool for visualizing the Drawdown of any asset.
How to Use
Very simple to use, the indicator takes the form of an oscillator, with colors ranging from red to green depending on the Drawdown level. A table summarizes several key data points.
Elements
On the oscillator, you'll find a line with a color gradient showing the asset's Drawdown. The flatter line represents the Max Drawdown (the lowest value reached).
In addition, the table summarizes several data:
The asset's All Time High (ATH).
Current Drawdown.
The Max Drawdown that has been reached.
Settings
First of all, you can activate a "Bar Color" in the settings (You must also uncheck "Borders" and "Wick" in your Chart Settings):
You can display Fibonacci levels on the oscillator. You'll see that levels can be relevant to drawdown. The color of the levels is also configurable.
In the calculation parameters, you can first choose between taking the High of the candles or the Close. By default this is Close, but if you change the parameter to High, the indication next to ATH in the table will change, and you'll see that the values in the table will be affected.
The second calculation parameter (Start Date) lets you modify the effective start date of the ATH, which will affect the drawdown level. Here's an example:
How it Works
First, we calculate the ATH:
var bdv_top = bdv_source
bdv_top := na(bdv_top ) ? bdv_source : math.max(bdv_source, bdv_top )
Then the drawdown is calculated as follows:
bdv = ((bdv_source / bdv_top) * 100) - 100
Then the max drawdown :
bdv_max = bdv
bdv_max := na(bdv_max ) ? bdv : math.min(bdv, bdv_max )
Hodl Calculation v1.0I have developed an indicator that calculates the value of our currency if we had periodically bought any stock or cryptocurrency on any exchange. I believe many individuals would be interested in computing such values.
You can customize the start and end times, choose the amount of currency to be used for each deal, and select from two frequency options.
The first option involves specific intervals, such as hourly, every three days, or bi-weekly.
The second option allows purchases at specific dates or times, like every 15th of the month at 12:00 PM, every Monday at 11:00 AM, or every day at 6:00 AM.
After selecting the frequency, the indicator performs calculations and presents statistical information in a table.
The summarized data includes frequency value, total selected period duration, number of deals, total quantity, total cost, current value, and profit/loss status.
IBIT Premium to CoinbaseThe BTC ETF premium indicator for TradingView is a specialized tool designed to measure and visualize the premium or discount of the iShares Bitcoin Trust (IBIT), an investment vehicle that holds Bitcoin, relative to the actual price of Bitcoin on the Coinbase exchange. This indicator can be particularly insightful for traders interested in the BTC securities market and those analyzing the demand for Bitcoin as reflected by institutional investment products.
#### Description:
The BTC ETF premium indicator in TradingView leverages an advanced Pine Script algorithm to calculate the premium (or discount) percentage of IBIT compared to the spot price of Bitcoin (BTC/USD) on Coinbase. The premium is a critical insight that reflects market sentiment and potentially arbitrage opportunities between the trust's share price and the underlying cryptocurrency asset.
Here's how the indicator works:
1. **Calculation Methodology:**
- **Implied Bitcoin Price of IBIT:** We determine the implied price of Bitcoin within IBIT by dividing the IBIT closing price by the known ratio of Bitcoin per share.
- **IBIT Premium to Coinbase:** The percentage premium is then calculated as:
$$\text{IBIT Premium} = \frac{(\text{Implied Bitcoin Price of IBIT } - \text{Actual Bitcoin Price on Coinbase})}{\text{Actual Bitcoin Price on Coinbase}} \times 100$$
- This calculation is performed using the closing prices on a per-minute basis to ensure timely and accurate analysis.
2. **Visualization:** The indicator plots the premium as a step line chart, making it easy to visualize changes over time. A dynamic label accompanies the plot, displaying the implied Bitcoin price, the actual percentage premium or discount, and whether the premium is trending up or down compared to the previous day's value.
3. **Usage Scenario:** Traders can use this indicator to monitor the live premium 24/7 and analyze how it behaves during different market conditions, including when the equity market, where IBIT is traded, is closed.
#### Additional Features:
- **Color-Coding:** The premium is color-coded in green when positive (premium) and in red when negative (discount), aiding quick visual assessment.
- **Zero-Line Reference:** A horizontal line is drawn at zero to easily identify when IBIT is trading at par with the spot price of Bitcoin.
- **Real-Time Label Updates:** The label updates in real time with the latest premium/discount information and includes an arrow to signify the trend direction.
#### Access and Usage:
The indicator can be favorited or added to your TradingView charts. You are also welcome to use the source code as a foundation for further customization to suit your trading strategies.
#### Notes:
Please consider that the IBIT has specific trading hours, and the indicator can show live changes even when its market is closed, which might lead to discrepancies from official static data. For best performance, use this indicator alongside the IBIT candlestick chart on TradingView.
GBTC Premium to CoinbaseThe BTC ETF premium indicator for TradingView is a specialized tool designed to measure and visualize the premium or discount of the Grayscale Bitcoin Trust (GBTC), an investment vehicle that holds Bitcoin, relative to the actual price of Bitcoin on the Coinbase exchange. This indicator can be particularly insightful for traders interested in the BTC securities market and those analyzing the demand for Bitcoin as reflected by institutional investment products.
#### Description:
The BTC ETF premium indicator in TradingView leverages an advanced Pine Script algorithm to calculate the premium (or discount) percentage of GBTC compared to the spot price of Bitcoin (BTC/USD) on Coinbase. The premium is a critical insight that reflects market sentiment and potentially arbitrage opportunities between the trust's share price and the underlying cryptocurrency asset.
Here's how the indicator works:
1. **Calculation Methodology:**
- **Implied Bitcoin Price of GBTC:** We determine the implied price of Bitcoin within GBTC by dividing the GBTC closing price by the known ratio of Bitcoin per share.
- **GBTC Premium to Coinbase:** The percentage premium is then calculated as:
$$\text{GBTC Premium} = \frac{(\text{Implied Bitcoin Price of GBTC} - \text{Actual Bitcoin Price on Coinbase})}{\text{Actual Bitcoin Price on Coinbase}} \times 100$$
- This calculation is performed using the closing prices on a per-minute basis to ensure timely and accurate analysis.
2. **Visualization:** The indicator plots the premium as a step line chart, making it easy to visualize changes over time. A dynamic label accompanies the plot, displaying the implied Bitcoin price, the actual percentage premium or discount, and whether the premium is trending up or down compared to the previous day's value.
3. **Usage Scenario:** Traders can use this indicator to monitor the live premium 24/7 and analyze how it behaves during different market conditions, including when the equity market, where GBTC is traded, is closed.
#### Additional Features:
- **Color-Coding:** The premium is color-coded in green when positive (premium) and in red when negative (discount), aiding quick visual assessment.
- **Zero-Line Reference:** A horizontal line is drawn at zero to easily identify when GBTC is trading at par with the spot price of Bitcoin.
- **Real-Time Label Updates:** The label updates in real time with the latest premium/discount information and includes an arrow to signify the trend direction.
#### Access and Usage:
The indicator can be favorited or added to your TradingView charts. You are also welcome to use the source code as a foundation for further customization to suit your trading strategies.
#### Notes:
Please consider that the GBTC has specific trading hours, and the indicator can show live changes even when its market is closed, which might lead to discrepancies from official static data. For best performance, use this indicator alongside the GBTC candlestick chart on TradingView.
TabulateTabulate statistics from up to 10 symbols and display in a table format
you can choose to display up to 20 periods data points back in time
Symbol and description
Select a symbol and provide a description for it, this would be used as the label on the left column
Highlighting options
Color based on value increase/decrease
Colors the value green if it has increased from previous value, or red if it has decreased
Color based on positive/negative value
Stat will be colored accordingly green if positive, red if negative
Table value formatting
Allows you to change how the values are formatted for easy viewing
if 0.000% is selected, the source will be replaced by the following formula (close - open)/open
table text color should be changed to "Color based on positive/negative value"
NOTE: symbols that hold only monthly values would need to be placed in a chart with real time data to show the latest period.
Trended CVD [Mxwll]Hey!
This indicator "Trended CVD" categorizes price movement by trend (using zig zag) and calculates cumulative volume delta for the entirety of the price move.
Features
CVD calculated for the trend
CVD divergences are distinguished (uptrend and falling CVD / downtrend and rising CVD)
CVD output normalized to scale with chart, and is plotted alongside the trend
Can be used for trend confirmation (CVD trend correlating with price trend)
All regular zig-zag features available
What constitutes a trend is customizable. Can locate small, medium, large price trends with detailed user-input settings.
How-To Use Trended CVD
The image above shows one of two primary uses for the indicator.
In the left-half of the image, price is downtrending simultaneously with CVD; thereby, CVD is confirming the downtrend.
The right-half of the image shows price uptrending simultaneously with CVD; CVD is confirming the uptrend.
This information can be used to classify the "strength" of the price move, and decide to trade with it or against it.
The image above shows the second primary use for the indicator.
A slight price decrease transpires while CVD increases - CVD diverging upwards from the price trend.
This information can be used to classify the strength of the downtrend, and decide to trade against it, or abstain from trading with it.
The image above shows, subsequent to divergence, price failed to sustain "meaningful" downwards movement.
Labels oriented at the final pivot of a trend show the cumulative volume delta for the entirety of the price move (distinguishable by the superimposed zig zag line).
That's really it! A more complex concept integrated with a simple output.
Thank you!
BTC ETF VolumesVolume
This script plots the trading volume of all BTC spot ETFs as well as the aggregate volume. Works on any chart and any timeframe.
Indicators
The volume of every ETF is plotted in a different color, with the total column adding up to the aggregate volume.
If you have price and indicator labels enabled you will also see individual ETF volume on your price scale on the right hand side.
If more BTC ETFs get launched I will add them.
Bitcoin ETF Tracker (BET)Get all the information you need about all the different Bitcoin ETFs.
With the Bitcoin ETF Tracker, you can observe all possible Bitcoin ETF data:
The ETF name.
The ticker.
The price.
The volume.
The share of total ETF volume.
The ETF fees.
The exchange and custodian.
At the bottom of the table, you'll find the day's total volume.
In addition, you can see the volume for the different Exchanges, as well as for the different Custodians.
If you don't want to display these lines to save space, you can uncheck "Show Additional Data" in the indicator settings.
The Idea
The goal is to provide the community with a tool for tracking all Bitcoin ETF data in a synthesized way, directly in your TradingView chart.
How to Use
Simply read the information in the table. You can hover above the Fees and Exchanges cells for more details.
The table takes space on the chart, you can remove the extra lines by unchecking "Show Additional Data" in the indicator settings or reduce text size by changing the "Table Text Size" parameter.
Upcoming Features
As soon as we have a little more history, we'll add variation rates as well as plots to observe the breakdown between the various Exchanges and Custodians.
Candle Strength AnalysisView candles differently with this new indicator designed to simply visualise and analyse price movements on your chart!
The more vibrant the colour, the stronger the conviction of its respective candle.
This simple script calculates the closing price as a percentage within the candles high/low range. A colour/strength rating is then assigned to the candle based on where this close price sits within the range.
Strong coloured candles occur when the close is very close to a high or low.
User defined percentage and colour inputs allow for quick personalisation and flexibility.
An additional wick imbalance feature identifies when a candle has a larger wick than its body, which may be used to identify a ranging market or shift in trader sentiment.
For any questions, concerns, or requests, please reach out to me in the comments below.
- The Pine Guru
ARIMA Moving Average and Forecaster [SS]Finally releasing this. This took months, over 3 months to be precise, to figure out, code and troubleshoot! I honestly was going to give up on this project, but I finally got it to actually work fairly reliably. So hopefully you like it!
This is a very basic ARIMA modeler. It can do the following:
1. Provide you with an ARIMA based Moving Average;
2. Provide you with a standard error band;
3. Auto-select a lag length for assessment based on stationarity;
3. Provide you with the option of extending the error range by a user selected amount of standard deviations; and
4. Forecasting and plotting the forecast on the chart.
I will go over each function individually, but before I do, I think its important to talk a bit about what an ARIMA Model is and does:
ARIMA stands for AutoRegressive Integrated Moving Average and is an approach to modeling and time series forecasting. In simple terms, it combines autoregressive (AR) and moving average (MA) components to capture the underlying patterns in a time series data. The "AutoRegressive" part accounts for the relationship between an observation and its previous values, while the "Moving Average" part considers the relationship between an observation and a residual error from past observations. The "Integrated" component involves differencing the time series to make it stationary, which aids in stabilizing the model. ARIMA models help predict future values based on patterns observed in historical data, making them useful for forecasting in various fields such as economics, finance, and weather prediction.
The benefits to ARIMA is it will forecast based on the current trend, but it also provides for both the up and down scenario of the trend (i.e., if we are in a downtrend, what it would look like and what values we could expect if the trend reverses and vice versa). All of this is within the scope of this indicator, believe it or not!
If you would like more information on ARIMA, you can check out my educational post about it here:
Alrighty, now for the indicator functions.
ARIMA Moving Average and Standard Error Band
The ARIMA moving average is very simple, it takes the SMA of the current trend, lags it and plots out the lagged SMA. You can toggle the auto-select lag on, or you can pick your own lag manually. The above image is an auto-selected lag, but if we manually lag it by 5, this is what it looks like:
Its simply a lagged average of the 5 SMA (that is essentially how ARIMA works, by creating a moving average and lagging the moving average).
There are some implications to selecting a lag factor when it comes to forecasting, but I will cover this in the forecasting section. But I do want to make mention, you can use the ARIMA moving average in lieu of other moving averages. The advantage to doing this is it will be able to plot out the error bands. For example, if we wanted to get an ARIMA MA of the 200 SMA, we can toggle on the error bands and this is what we get:
Or the 50 MA:
NOTE: You ABSOLUTELY SHOULD NEVER use more than a lag of 4 or 5 for Forecasting (will be discussed later).
Auto-Select Lag
The indicator pulls the ARIMA modeler framework from my Forecasting library and pulls the stationarity assessment from my SPTS library. When you are doing an ARIMA model for forecasting, we need to ensure the data is stationary. Thus, if you want to forecast out the current trend, its highly recommended you select the "Auto Determine Lag Length" to find the most appropriate lag and forecast accordingly.
You can, however, chose your own lag order (model order), but this should never be above 4 or 5.
You should never select a lag of more than 5 because you are introducing too much "trendiness" into the equation, and you will get astronomical readings. ARIMA models never generally exceed a lag of 3 or 4 at most, as they are supposed be stationary and de-trended.
Extending by Standard Deviation
There is an option to select a standard deviation extension band. This is helpful for active day trading. Here is NIO extended by 2 standard deviations:
General suggestion is to only extend by 2 standard deviations and this is sufficient for most stocks.
Forecasting
The hallmark of an ARIMA model is the ability to use it for forecasting. Thus, the forecasting feature is a large portion of this indicator. You can see it displayed in the main chart above, but let's show some other examples:
NIO on the 1 hour:
TSLA on the 4 hour:
You can also display a forecasting table:
The result row shows the most likely, conservative, price at each time increment.
The Upper Confidence and Lower Confidence show what the trend would look like if it continued up or down at the current rate and the 95% confidence intervals show the values that the true source is likely to fall between at various increments in time with a 95% confidence (i.e. 95% probability that it should fall between these levels at period xyz assuming normal distribution).
The important levels, in my opinion, are the upper and lower confidence levels. These show you the current rate of decline or increase that the stock is expecting and what the trend would look like with a continuation or a reversal. This is ARIMA's biggest strength, as it has the ability to plot both outcomes assuming the current trend rate and time remains constant.
And that is the indicator! ARIMA is a bit of a complex process, but its a very powerful tool when used properly!
Troubleshooting:
One thing of note. Sometimes when autoselecting a length for forecasting, if there has been a heavy trend in one direction, you will not get the upper or lower confidence levels because of the lack of any up or down movement. In this case, manually select a lag of 3 to 5 to correct for this.
Let me know if you have any questions below and safe trades everyone!
GARCH Volatility Estimation - The Quant ScienceThe GARCH (Generalized Autoregressive Conditional Heteroskedasticity) model is a statistical model used to forecast the volatility of a financial asset. This model takes into account the fluctuations in volatility over time, recognizing that volatility can vary in a heteroskedastic (i.e., non-constant variance) manner and can be influenced by past events.
The general formula of the GARCH model is:
σ²(t) = ω + α * ε²(t-1) + β * σ²(t-1)
where:
σ²(t) is the conditional variance at time t (i.e., squared volatility)
ω is the constant term (intercept) representing the baseline level of volatility
α is the coefficient representing the impact of the squared lagged error term on the conditional variance
ε²(t-1) is the squared lagged error term at the previous time period
β is the coefficient representing the impact of the lagged conditional variance on the current conditional variance
In the context of financial forecasting, the GARCH model is used to estimate the future volatility of the asset.
HOW TO USE
This quantitative indicator is capable of estimating the probable future movements of volatility. When the GARCH increases in value, it means that the volatility of the asset will likely increase as well, and vice versa. The indicator displays the relationship of the GARCH (bright red) with the trend of historical volatility (dark red).
USER INTERFACE
Alpha: select the starting value of Alpha (default value is 0.10).
Beta: select the starting value of Beta (default value is 0.80).
Lenght: select the period for calculating values within the model such as EMA (Exponential Moving Average) and Historical Volatility (default set to 20).
Forecasting: select the forecasting period, the number of bars you want to visualize data ahead (default set to 30).
Design: customize the indicator with your preferred color and choose from different types of charts, managing the design settings.