Volume and Price Z-Score [Multi-Asset] - By LeviathanThis script offers in-depth Z-Score analytics on price and volume for 200 symbols. Utilizing visualizations such as scatter plots, histograms, and heatmaps, it enables traders to uncover potential trade opportunities, discern market dynamics, pinpoint outliers, delve into the relationship between price and volume, and much more.
A Z-Score is a statistical measurement indicating the number of standard deviations a data point deviates from the dataset's mean. Essentially, it provides insight into a value's relative position within a group of values (mean).
- A Z-Score of zero means the data point is exactly at the mean.
- A positive Z-Score indicates the data point is above the mean.
- A negative Z-Score indicates the data point is below the mean.
For instance, a Z-Score of 1 indicates that the data point is 1 standard deviation above the mean, while a Z-Score of -1 indicates that the data point is 1 standard deviation below the mean. In simple terms, the more extreme the Z-Score of a data point, the more “unusual” it is within a larger context.
If data is normally distributed, the following properties can be observed:
- About 68% of the data will lie within ±1 standard deviation (z-score between -1 and 1).
- About 95% will lie within ±2 standard deviations (z-score between -2 and 2).
- About 99.7% will lie within ±3 standard deviations (z-score between -3 and 3).
Datasets like price and volume (in this context) are most often not normally distributed. While the interpretation in terms of percentage of data lying within certain ranges of z-scores (like the ones mentioned above) won't hold, the z-score can still be a useful measure of how "unusual" a data point is relative to the mean.
The aim of this indicator is to offer a unique way of screening the market for trading opportunities by conveniently visualizing where current volume and price activity stands in relation to the average. It also offers features to observe the convergent/divergent relationships between asset’s price movement and volume, observe a single symbol’s activity compared to the wider market activity and much more.
Here is an overview of a few important settings.
Z-SCORE TYPE
◽️ Z-Score Type: Current Z-Score
Calculates the z-score by comparing current bar’s price and volume data to the mean (moving average with any custom length, default is 20 bars). This indicates how much the current bar’s price and volume data deviates from the average over the specified period. A positive z-score suggests that the current bar's price or volume is above the mean of the last 20 bars (or the custom length set by the user), while a negative z-score means it's below that mean.
Example: Consider an asset whose current price and volume both show deviations from their 20-bar averages. If the price's Z-Score is +1.5 and the volume's Z-Score is +2.0, it means the asset's price is 1.5 standard deviations above its average, and its trading volume is 2 standard deviations above its average. This might suggest a significant upward move with strong trading activity.
◽️ Z-Score Type: Average Z-Score
Calculates the custom-length average of symbol's z-score. Think of it as a smoothed version of the Current Z-Score. Instead of just looking at the z-score calculated on the latest bar, it considers the average behavior over the last few bars. By doing this, it helps reduce sudden jumps and gives a clearer, steadier view of the market.
Example: Instead of a single bar, imagine the average price and volume of an asset over the last 5 bars. If the price's 5-bar average Z-Score is +1.0 and the volume's is +1.5, it tells us that, over these recent bars, both the price and volume have been consistently above their longer-term averages, indicating sustained increase.
◽️ Z-Score Type: Relative Z-Score
Calculates a relative z-score by comparing symbol’s current bar z-score to the mean (average z-score of all symbols in the group). This is essentially a z-score of a z-score, and it helps in understanding how a particular symbol's activity stands out not just in its own historical context, but also in relation to the broader set of symbols being analyzed. In other words, while the primary z-score tells you how unusual a bar's activity is for that specific symbol, the relative z-score informs you how that "unusualness" ranks when compared to the entire group's deviations. This can be particularly useful in identifying symbols that are outliers even among outliers, indicating exceptionally unique behaviors or opportunities.
Example: If one asset's price Z-Score is +2.5 and volume Z-Score is +3.0, but the group's average Z-Scores are +0.5 for price and +1.0 for volume, this asset’s Relative Z-Score would be high and therefore stand out. This means that asset's price and volume activities are notably high, not just by its own standards, but also when compared to other symbols in the group.
DISPLAY TYPE
◽️ Display Type: Scatter Plot
The Scatter Plot is a visual tool designed to represent values for two variables, in this case the Z-Scores of price and volume for multiple symbols. Each symbol has it's own dot with x and y coordinates:
X-Axis: Represents the Z-Score of price. A symbol further to the right indicates a higher positive deviation in its price from its average, while a symbol to the left indicates a negative deviation.
Y-Axis: Represents the Z-Score of volume. A symbol positioned higher up on the plot suggests a higher positive deviation in its trading volume from its average, while one lower down indicates a negative deviation.
Here are some guideline insights of plot positioning:
- Top-Right Quadrant (High Volume-High Price): Symbols in this quadrant indicate a scenario where both the trading volume and price are higher than their respective mean.
- Top-Left Quadrant (High Volume-Low Price): Symbols here reflect high trading volumes but prices lower than the mean.
- Bottom-Left Quadrant (Low Volume-Low Price): Assets in this quadrant have both low trading volume and price compared to their mean.
- Bottom-Right Quadrant (Low Volume-High Price): Symbols positioned here have prices that are higher than their mean, but the trading volume is low compared to the mean.
The plot also integrates a set of concentric squares which serve as visual guides:
- 1st Square (1SD): Encapsulates symbols that have Z-Scores within ±1 standard deviation for both price and volume. Symbols within this square are typically considered to be displaying normal behavior or within expected range.
- 2nd Square (2SD): Encapsulates those with Z-Scores within ±2 standard deviations. Symbols within this boundary, but outside the 1 SD square, indicate a moderate deviation from the norm.
- 3rd Square (3SD): Represents symbols with Z-Scores within ±3 standard deviations. Any symbol outside this square is deemed to be a significant outlier, exhibiting extreme behavior in terms of either its price, its volume, or both.
By assessing the position of symbols relative to these squares, traders can swiftly identify which assets are behaving typically and which are showing unusual activity. This visualization simplifies the process of spotting potential outliers or unique trading opportunities within the market. The farther a symbol is from the center, the more it deviates from its typical behavior.
◽️ Display Type: Columns
In this visualization, z-scores are represented using columns, where each symbol is presented horizontally. Each symbol has two distinct nodes:
- Left Node: Represents the z-score of volume.
- Right Node: Represents the z-score of price.
The height of these nodes can vary along the y-axis between -4 and 4, based on the z-score value:
- Large Positive Columns: Signify a high or positive z-score, indicating that the price or volume is significantly above its average.
- Large Negative Columns: Represent a low or negative z-score, suggesting that the price or volume is considerably below its average.
- Short Columns Near 0: Indicate that the price or volume is close to its mean, showcasing minimal deviation.
This columnar representation provides a clear, intuitive view of how each symbol's price and volume deviate from their respective averages.
◽️ Display Type: Circles
In this visualization style, z-scores are depicted using circles. Each symbol is horizontally aligned and represented by:
- Solid Circle: Represents the z-score of price.
- Transparent Circle: Represents the z-score of volume.
The vertical position of these circles on the y-axis ranges between -4 and 4, reflecting the z-score value:
- Circles Near the Top: Indicate a high or positive z-score, suggesting the price or volume is well above its average.
- Circles Near the Bottom: Represent a low or negative z-score, pointing to the price or volume being notably below its average.
- Circles Around the Midline (0): Highlight that the price or volume is close to its mean, with minimal deviation.
◽️ Display Type: Delta Columns
There's also an option to utilize Z-Score Delta Columns. For each symbol, a single column is presented, depicting the difference between the z-score of price and the z-score of volume.
The z-score delta essentially captures the disparity between how much the price and volume deviate from their respective mean:
- Positive Delta: Indicates that the z-score of price is greater than the z-score of volume. This suggests that the price has deviated more from its average than the volume has from its own average. Such a scenario could point to price movements being more significant or pronounced compared to the changes in volume.
- Negative Delta: Represents that the z-score of volume is higher than the z-score of price. This might mean that there are substantial volume changes, yet the price hasn't moved as dramatically. This can be indicative of potential build-up in trading interest without an equivalent impact on price.
- Delta Close to 0: Means that the z-scores for price and volume are almost equal, indicating their deviations from the average are in sync.
◽️ Display Type: Z-Volume/Z-Price Heatmap
This visualization offers a heatmap either for volume z-scores or price z-scores across all symbols. Here's how it's presented:
Each symbol is allocated its own horizontal row. Within this row, bar-by-bar data is displayed using a color gradient to represent the z-score values. The heatmap employs a user-defined gradient scale, where a chosen "cold" color represents low z-scores and a chosen "hot" color signifies high z-scores. As the z-score increases or decreases, the colors transition smoothly along this gradient, providing an intuitive visual indication of the z-score's magnitude.
- Cold Colors: Indicate values significantly below the mean (negative z-score)
- Mild Colors: Represent values close to the mean, suggesting minimal deviation.
- Hot Colors: Indicate values significantly above the mean (positive z-score)
This heatmap format provides a rapid, visually impactful means to discern how each symbol's price or volume is behaving relative to its average. The color-coded rows allow you to quickly spot outliers.
VOLUME TYPE
The "Volume Type" input allows you to choose the nature of volume data that will be factored into the volume z-score calculation. The interpretation of indicator’s data changes based on this input. You can opt between:
- Volume (Regular Volume): This is the classic measure of trading volume, which represents the volume traded in a given time period - bar.
- OBV (On-Balance Volume): OBV is a momentum indicator that accumulates volume on up bars and subtracts it on down bars, making it a cumulative indicator that sort of measures buying and selling pressure.
Interpretation Implications:
- For Volume Type: Regular Volume:
Positive Z-Score: Indicates that the trading volume is above its average, meaning there's unusually high trading activity .
Negative Z-Score: Suggests that the trading volume is below its average, signifying unusually low trading activity.
- For Volume Type: OBV:
Positive Z-Score: Signifies that “buying pressure” is above its average.
Negative Z-Score: Signifies that “selling pressure” is above its average.
When comparing Z-Score of OBV to Z-Score of price, we can observe several scenarios. If Z-Price and Z-Volume are convergent (have similar z-scores), we can say that the directional price movement is supported by volume. If Z-Price and Z-Volume are divergent (have very different z-scores or one of them being zero), it suggests a potential misalignment between price movement and volume support, which might hint at possible reversals or weakness.
Statistics
HistDistDevsv2Iteration on ChrisakaChis' HIsDistDevs indicator which adds customizability options and automatically adjusts the deviations according to the loaded chart and timeframe. Supports ES, NQ, YM, RTY, GC
Blockunity Performance Oscillator (BPO)The Performance Oscillator (BPO) is an intuitive indicator that makes it easy to analyze the performance of any asset. It operates over 5 simultaneously configurable periods. All design elements are also customizable. The integrated table summarizes the information in color, so you can quickly assess the different variations.
How it works
The operation of this script is quite simple. It calculates the performance of the selected asset over the different lookback periods indicated in the parameters (default: 1, 7, 30, 120 and 365). It then plots the lines in an independent panel (it is possible to hide lines by unchecking them in the parameters). Finally, performance information is displayed in a table for enhanced clarity.
The Idea
The idea is to bring information about the performance of any asset into your TradingView chart, and to make it visual. What's more, it can give an idea of the asset's trend, as, for example, if all periods are green (positive) in the table, then we can deduce that the selected asset is in a clear uptrend.
Being able to visually analyze several variations over different periods at the same time, while adding this information to a colorful table, makes it unique.
Usage Advice
You can use this indicator on any asset or index.
For example, if you use the indicator in a daily timeframe, the default periods will be 1 day, 7 days, 30 days, etc. If you use the indicator in a horary timeframe, the default periods will be 1 hour, 7 hours, 30 hours, etc.
Parameters
Display of different periods.
Periods according to the timeframe selected on the graph.
Line widths.
Line colors.
Table parameters.
Candlestick Percentile RankCANDLESTICK PERCENTILE RANK
█ OVERVIEW
This script is designed to sample all available candles within a chosen time frame and provide a candlestick percentile rank to each candle. This script works by measuring a candle's body or its low to high value to the upside, or to the downside in percentage or in dollar value. Once the candle is measured its given a value based on all the previous measurements. You will be able to know if a body ( or a full candle/bar ) is above, or below a certain percentile level. By doing this you're effectively going to know if a candle is under performing or under-performing compared to the chart's history.
Example : A candle that did a 30% move vs another did a 10% and a third did a 5%. Here we 3 candles. The one that did a 30% is going to be ranked at 100 because it's the highest while the 5% candle ranks at 0 and the 10% candles ranks at 50. you see how this works. Having a candle in the 90th percentile means at that time it scored better than 90% of the preceding candles based on its move ( in dollar or percentage ).
So imagine you have an organic move of an up trend, ideally and what you want to see is this ; a candle with a low rank followed by one that's higher, followed by one that's also higher until the trend stops and you see a pin bar or whatever topping candle. You expect to see a rank going from low value to high value to suddenly sharply decrease to low value.
Constant low values may indicate lower volatility or time to change. For example, a doji candle will create a very low percentile rank value ( body-wise ). A high percentile rank value means high volatility on body and full candle calculations.
^ This is only one use of it.
A trendline may also form with a breakout points and information about the trend of the volatility of recent candles. Moving averages when applied to these calculations and to the percentile ranks can absolutely help in making these trends a bit smoother which is why you can add them to the graph. if you wish.
This script can be used in multiple ways including as a measure of volatility. or for statistical purposes. If I know the 50th percentile of a candle value I can know a very critical information about an asset's behavior and how volatile it is compared to another. There are many questions that can be answered using this script. How many times has this asset printed a candle of x% in the past y amount of time and how often does that happen. Is this candle or that truly rare ?
This script also has an option to highlight a specific percentile level showing its value. You can also see the number of sampled candles for clarity on the reliability of the data.
In conclusion, candlesticks effect each others. The whole candlestick/bars patterns is based on this. The percentile Rank is an effective way to observe and study these effects. The percentile rank shows you how on a measuring stick from 0 to 100 how a candle ( body or full low-high ) ranks compared to other candles in the past based on dollar value or percentage value. There are many untapped usages of the percentile rank when applied to candlesticks calculations and I hope this script can help you with this. If one can study the behavior of an asset and its bars percentile ranks they can unlock some probabilistic advantages.
█ Future Plans and upgrades to this script may include :
1. Count the times a percentile level is hit.
2. Display details about the highest/lowest levels.
and more! feel free to let me know what you'd like to see!
█ How to use :
1. Put the script on your chart
2. Navigate to the settings
give the script a few seconds and you should be set.
Buy Below Prev_Low. Sell 100% Above Avg. Pyramiding.This is simple indicator script for long term investors. It will check if the low of today is less than low of yesterday (or any time frame candle) and if the condition is satisfied, then the alert will be triggerred and that particular stock will be bought.
Each time a unit is bought, the average price is calculated and also the trget selling price, which is set at 100% above the average buying price. So once the price reaches that selling price target, the entire holding is sold.
The code resets all the variables back to 0 once a sell signal is triggerred.
[MAD] Gaussian silence detectorBased on a short experiments a Gaussian silence detector
This script utilizes a Gaussian distribution function to visualize price volatility and potential major movement moments in trading.
Dynamic Spectrum Visualization:
The script plots ten different levels of the Gaussian distribution, each represented by a different color ranging from red to violet. This provides a spectrum view of the price data.
Adjustable Alert Levels:
Users can set a specific alert level, and when more than four Gaussian values exceed this threshold, a breakout alert is triggered.
Customizable Display Settings:
The visual compression, transparency, and color scheme can be adjusted to cater to different charting preferences.
Background Highlighting:
Whenever a potential breakout scenario is detected, the chart's background changes color, allowing for quick visual reference.
--------------
How to Use the Indicator
Adjust Deviation & Alert Levels:
First things first, play around with the deviation setting. This is going to help the tool understand the market's 'normal' behavior.
Next, tweak the alert levels. You want the background color to switch effectively during periods of silence. This is based on past data, so look at how the chart behaved historically and adjust accordingly.
For now each timeframe needs its own setup.
Set Up The Colors:
Once you've got the basics down, dive into the color settings. This doesn't affect how the tool works; it just makes things look prettier (or uglier, depending on your color choices 😜).
Compression (Optional):
If you think the data display is too intense or too mellow, adjust the compression. This won't change the calculations.
It's just about how you view the data.
Remember to combine it with other trading strategies and tools for the best results.
Machine Learning using Neural Networks | EducationalThe script provided is a comprehensive illustration of how to implement and execute a simplistic Neural Network (NN) on TradingView using PineScript.
It encompasses the entire workflow from data input, weight initialization, implicit neuron calculation, feedforward computation, backpropagation for weight adjustments, generating predictions, to visualizing the Mean Squared Error (MSE) Loss Curve for monitoring the training phase.
In the visual example above, you can see that the prediction is not aligned with the actual value. This is intentional for demonstrative purposes, and by incrementing the Epochs or Learning Rate, you will see these two values converge as the accuracy increases.
Hyperparameters:
Learning Rate, Epochs, and the choice between Simple Backpropagation and a verbose version are declared as script inputs, allowing users to tailor the training process.
Initialization:
Random initialization of weight matrices (w1, w2) is performed to ensure asymmetry, promoting effective gradient updates. A seed is added for reproducibility.
Utility Functions:
Functions for matrix randomization, sigmoid activation, MSE loss calculation, data normalization, and standardization are defined to streamline the computation process.
Neural Network Computation:
The feedforward function computes the hidden and output layer values given the input.
Two variants of the backpropagation function are provided for weight adjustment, with one offering a more verbose step-by-step computation of gradients.
A wrapper train_nn function iterates through epochs, performing feedforward, loss computation, and backpropagation in each epoch while logging and collecting loss values.
Training Invocation:
The input data is prepared by normalizing it to a value between 0 and 1 using the maximum standardized value, and the training process is invoked only on the last confirmed bar to preserve computational resources.
Output Forecasting and Visualization:
Post training, the NN's output (predicted price) is computed, standardized and visualized alongside the actual price on the chart.
The MSE loss between the predicted and actual prices is visualized, providing insight into the prediction accuracy.
Optionally, the MSE Loss Curve is plotted on the chart, illustrating the loss trajectory through epochs, assisting in understanding the training performance.
Customizable Visualization:
Various inputs control visualization aspects like Chart Scaling, Chart Horizontal Offset, and Chart Vertical Offset, allowing users to adapt the visualization to their preference.
-------------------------------------------------------
The following is this Neural Network structure, consisting of one hidden layer, with two hidden neurons.
Through understanding the steps outlined in my code, one should be able to scale the NN in any way they like, such as changing the input / output data and layers to fit their strategy ideas.
Additionally, one could forgo the backpropagation function, and load their own trained weights into the w1 and w2 matrices, to have this code run purely for inference.
-------------------------------------------------------
While this demonstration does create a “prediction”, it is on historical data. The purpose here is educational, rather than providing a ready tool for non-programmer consumers.
Normally in Machine Learning projects, the training process would be split into two segments, the Training and the Validation parts. For the purpose of conveying the core concept in a concise and non-repetitive way, I have foregone the Validation part. However, it is merely the application of your trained network on new data (feedforward), and monitoring the loss curve.
Essentially, checking the accuracy on “unseen” data, while training it on “seen” data.
-------------------------------------------------------
I hope that this code will help developers create interesting machine learning applications within the Tradingview ecosystem.
Treasury Yields Heatmap [By MUQWISHI]▋ INTRODUCTION :
The “Treasury Yields Heatmap” generates a dynamic heat map table, showing treasury yield bond values corresponding with dates. In the last column, it presents the status of the yield curve, discerning whether it’s in a normal, flat, or inverted configuration, which determined by using Pearson's linear regression coefficient. This tool is built to offer traders essential insights for effectively tracking bond values and monitoring yield curve status, featuring the flexibility to input a starting period, timeframe, and select from a range of major countries' bond data.
_______________________
▋ OVERVIEW:
______________________
▋ YIELD CURVE:
It is determined through Pearson's linear regression coefficient and considered…
R ≥ 0.7 → Normal
0.7 > R ≥ 0.35 → Slight Normal
0.35 > R > -0.35 → Flat
-0.35 ≥ R > -0.7 → Slight Inverted
-0.7 ≥ R → Inverted
_______________________
▋ INDICATOR SETTINGS:
#Section One: Table Setting
#Section Two: Technical Setting
(1) Country: Select country’s treasury yields data
(2) Timeframe: Time interval.
(3) Fetch By:
(3A) Date: Retrieve data by beginning of date.
(3B) Period: Retrieve data by specifying the number of time series back.
Enjoy. Please let me know if you have any questions.
Thank you.
TTP Pair CipherPair Cipher can run your hedge pair trading strategy.
Pair cipher can use a spread chart (two assets ratio or difference) to manage a hedge position consisting of two assets: one long and one short position.
Event though the spread chart is used to determine the entries and exits each coin price action is used to calculate floating PNL.
It supports different bot platforms. It's backtestable and can run live.
Features:
- Internal and external entry signal
- In-chart realised PNL plot
- Hedge position floating PNL chart
- Individual floating PNL for each long and short ("show coins" toggle)
- Retracement exit strategy: determine at which retracement factor to exit your position while in profit
- PNL RSI exit strategy: determine at which RSI level crossunder you'd like to exit. RSI is applied to the floating PNL
- Static TP/SL levels
- ATR TP/SL levels with individual factors. When ATR is selected the TP or SL acts as a multiplier of ATR instead.
- On-chart debug labels for alerts
- Intra candle alert: signals can trigger intra candle in this mode, but this mode will cause repainting. Example: if the position goes below SL intra candle, the alert will be sent, but later if it goes in profit before closing the candle, the backtest will continue with the position open. The backtest does NOT have access to the intra candle data. Alert intra candle reduces the risk of not applying SL.
Example of setup:
1) Load an empty 1 hour timeframe chart with the spread BYBIT:REQUSDT.P / BYBIT:REEFUSDT.P
2) Select an investment amount
3) Select TP 1.2 and enable ATR
4) Select SL 1.1 and enable ATR
5) Select RSI profits of crossunder 70
6) Don't enable external signal (you can try with TTP PNR)
7) Select BYBIT:REQUSDT.P as symbol 1
8) Select BYBIT:REEFUSDT.P as symbol 2
NSE METRICS Public [ILuvMarkets]This indicator supports the following NSE wide metrics derived from EOD BHAVCOPY.
UP/DOWN VOLUME
UP/DOWN TRADED VALUE
ADVN/DCLN
4% UP/DOWN
NEW HIGHS/LOWS 20D
NEW HIGHS/LOWS 50D
NEW HIGHS/LOWS 100D
NEW HIGHS/LOWS 200D
The metrics can be displayed as NET ( UP - DOWN), ACTUAL VALUE (UP vs. DOWN) or a PERCENTAGE ( UP / (UP + DOWN))
Please use Daily Timeframe for these metrics.
The metrics are updated by an EOD Batch process once NSE BHAVCOPY is available.
Bankruptcy Risk: Altman Z-Score, Zmijewski Score, Grover GThis custom indicator calculates three common bankruptcy risk scores:
Altman Z-Score
Zmijewski Score
Grover G-Score
Altman Z-Score
Companies are in healthy condition if the Z-Score > 2.6.
Companies are in vulnerable conditions and need improvement (grey area) if the score is between 1.1 - 2.6.
Companies have the potential to lead to serious bankruptcy if the Z-Score < 1.1.
Zmijewski Score
The company has the potential to go bankrupt if the value of X Score > 0.
The company is healthy if the value of X Score < 0.
Grover Model: G-Score
The company has the potential to go bankrupt if the G Score ≤ -0.02.
The company is in good health if the value of G Score ≥ 0.001.
The indicator pulls key financial metrics and calculates each score, then displays the results in a table with color-coding based on the level of bankruptcy risk.
Users can toggle between FQ and FY periods and view details on the underlying metrics. This provides an easy way to visualize bankruptcy risk for a company and compare across different scoring models.
Useful for fundamental analysis and assessing financial health.
The financial ratios and methodology are based on research described in
"Analysis of Bankruptcy Prediction Models in Determining Bankruptcy of Consumer Goods Companies in Indonesia" (Thomas et al., 2020).
NIFTY POSITION ScannerTracking the real-time intraday position of NIFTY stocks is the utility of this price action based scanner. The number of stocks in this scanner is 40 due to TradingView's script limit.
The script takes present day's price range of the stocks (stocks of the Index being tracked included in this screener) into account, to hint strength or weakness in the underlying Index (for example: NIFTY here).
The day's price range of a stock is gauged on a scale of 0-100, where 0 is Day's price low and 100 is day's price high.
If a stock is in 90-100 price range section the cell with title "90" illuminates hinting the stock is trading near day's high.
Likewise, if a stock is in 0-10 price range section the cell with title "10" illuminates hinting that the stock is trading near day's low.
The price range of 10-25 is represented in the cell titled "25"
The price range of 75-90 is represented in the cell titled "75"
Only one cell from the day's range illuminates at a time for a stock, signaling the present position of that stock in the Day's range at that instant.
The script works best above 10 second time frame.
Idea: If majority of the heavy weight stocks of the Index being tracked are trading near Day's high the underlying Index must be going strong at that very instant and Vice versa.
Disclaimer: Only for studying Index movement ideas intraday, trading is not advised.
Also check out the other scripts by me.
-- Dr. Vats
Market Performance TableThe Market Performance Table displays the performance of multiple tickers (up to 5) in a table format. The tickers can be customized by selecting them through the indicator settings.
The indicator calculates various metrics for each ticker, including the 1-day change percentage, whether the price is above the 50, 20, and 10-day simple moving averages (SMA), as well as the relative strength compared to the 10/20 SMA and 20/50 SMA crossovers. It also calculates the price deviation from the 50-day SMA.
The table is displayed on the chart and can be positioned in different locations.
Credits for the idea to @Alex_PrimeTrading ;)
S&P Sector PerformanceS&P Sector Performance calculate and display the logarithmic returns of SPX and each S&P Sector for a predefined timeframe or for a custom date.
PCA-Risk IndicatorOBJECTIVE:
The objective of this indicator is to synthesize, via PCA (Principal Component Analysis), several of the most used indicators with in order to simplify the reading of any asset on any timeframe.
It is based on my Bitcoin Risk Long Term indicator, and is the evolution of another indicator that I have not published 'Average Risk Indicator'.
The idea of this indicator is to use statistics, in this case the PCA, to reduce the number of dimensions (indicator) to aggregate them in some synthetic indicators (PCX)
I invite you to dig deeper into the PCA, but that is to try to keep as much information as possible from the raw data. The signal minus the noise.
I realized this indicator a year ago, but I publish it now because I do not see the interest to keep it private.
USAGE:
Unlike the Bitcoin Risk Long Term indicator, it does not make sense to change or disable the input indicators unless you use the 'Average Indicator' function. Because each input is weighted to generate the outputs, the PCX.
I extracted several courses (Bitcoin, Gold, S&P, CAC40) on several timeframes (W, D, 4h, 1h) of Trading view and use the Excel generated for the data on which I played the PCA analysis.
The results:
explained_variance_ratio: 0.55540809 / 0.13021972 / 0.07303142 / 0.03760925
explained_variance: 11.6639671 / 2.73470717 / 1.53371209 / 0.7898212
Interpretation:
Simply put, 55% of the information contained in each indicator can be represented with PC1, +13% with PC2, +7% with PC3, +3% with PC4.
What is important to understand is that PC1, which serves as a thermometer in a way, gives a simple indication of over-buying or over-selling area better than any other indicator.
PC2, difficult to interpret, is more reactive because precedes PC1, but can give false signals.
PC3 and PC4 do not seem relevant to me.
The way I use it is to take PC1 for Risk indicator, and display PC2 with 'Area'. When PC2 turns around and PC1 arrives on extremes, it can be good points to act.
NOTES :
- It is surprising that a simple average of all the indicators gives a fairly relevant result
- With Average indicator as Risk indicator, you can combine the indicators of your choice and see the predictive power with the staining of bars.
- You can add alerts on the levels of your choice on the Risk Indicator
- If you have any idea of adding an indicator, modification, criticism, bug found: share them, it’s appreciated!
---- FR ----
OBJECTIF :
L'objectif de cet indicateur est de synthétiser, via l'ACP (Analyse en Composantes Principales), plusieurs indicateurs parmi les plus utilisés avec afin de simplifier la lecture de n'importe quel actif sur n'importe quel timeframe.
Il est inspiré de mon indicateur 'Bitcoin Risk Long Term indicator', et est l'évolution d'un autre indicateur que je n'ai pas publié 'Average Risk Indicator'.
L'idée de cet indicateur est d'utiliser les statistiques, en l'occurence l'ACP, pour réduire le nombre de dimensions (indicateur) pour les agréger dans quelques indicateurs synthétiques (PCX)
Je vous invite à creuser l'ACP, mais c'est chercher à conserver un maximum d'informations à partir de la donnée brute. Le signal moins le bruit.
J'ai réalisé cet indicateur il y a un an, mais je le publie maintenant car je ne vois pas l'intérêt de le garder privé.
UTILISATION :
Contrairement à 'Bitcoin Risk Long Term indicator', il ne fait pas sens de modifier ou désactiver les indicateurs inputs, sauf si vous utiliser la fonction 'Average Indicator'. Car chaque input est pondéré pour générer les outputs, les PCX.
J'ai extrait plusieurs cours (Bitcoin, Gold, S&P, CAC40) sur plusieurs timeframes (W, D, 4h, 1h) de Trading view et utiliser les Excel généré pour la data sur laquelle j'ai joué l'analyse ACP.
Les résultats :
explained_variance_ratio : 0.55540809 / 0.13021972 / 0.07303142 / 0.03760925
explained_variance : 11.6639671 / 2.73470717 / 1.53371209 / 0.7898212
Interprétation :
Pour faire simple, 55% de l'information contenu dans chaque indicateur peut être représenté avec PC1, +13% avec PC2, +7% avec PC3, +3% avec PC4.
Ce qui faut y comprendre c'est que le PC1, qui sert de thermomètre en quelque sorte, donne une indication simple de zone de sur-achat ou sur-vente mieux que n'importe quel autre indicateur.
PC2, difficile à interpréter, est plus réactif car précède PC1, mais peut donner des faux signaux.
PC3 et PC4 ne me semble pas pertinent.
La manière dont je m'en sert c'est de prendre PC1 pour Risk indicator, et d'afficher PC2 avec 'Region'. Lorsque PC2 se retourne et que PC1 arrive sur des extrêmes, cela peut être des bons points pour agir.
NOTES :
- Il est étonnant de constater qu'une simple moyenne de tous les indicateurs donne un résultat assez pertinent
- Avec Average indicator comme Risk indicator, vous pouvez combiner les indicateurs de vos choix et voir la force prédictive avec la coloration des bars.
- Vous pouvez ajouter des alertes sur les niveaux de votre choix sur le Risk Indicator
- Si vous avez la moindre idée d'ajout d'indicateur, modification, critique, bug trouvé : partagez-les, c'est apprécié !
IU SIP CALCULATORHow This Indicator Script Works:
1. This indicator script calculate the monthly SIP returns of any market over any user defined period.
2. SIP stands for Systematic Investment Plan. It is a way to invest in any asset by regularly investing a fixed amount of money at regular intervals for example Monthly, Weekly, Quarterly etc.
3. This indicator Calculate the following
# Average buy price
# Total quantity hold
# Yearly returns
# Monthly returns
# Total invested amount
# Total profits in amount
# Total portfolio value
# Total returns in per percentage term.
4. This script takes monthly SIP amount, starting month, starting year, ending year, ending month from the user and store the value for calculations.
5. After that it store the open price of every month into an array then it average the array and compare that price with the last month close price.
6. on the bases of this it performs all of the calculations.
7. The script plot every calculation into an table from.
8. It requires monthly chart timeframe for working.
9. The table is editable user can change the color and transparency.
How User Can Benefit From The Script:
1. User can get the past monthly SIP returns of any market he wants to invest this will give him an overview about what to expect from the market.
2. Once user understand the expected returns from the market he can adjust his investment strategy.
3. This help the user to Analyse various stocks and their past performance.
4. User can also short list the best performed stocks.
5. Over all this script will give complete SIP vision of any market.
Crypto Liquidation HeatmapThis indicator is designed to identify potential areas of liquidations, in most crypto assets.
How does it work?
At the core of this indicator, it utilizes Open Interest (a statistic measuring the sum of all open futures positions), which I will refer to as OI.
The script monitors changes in OI, and then correlates these changes to the price action trend to derive an estimation of whether an increase in OI relates to an increase in Shorts or in Longs.
The trend is currently identified by the candle closing direction, therefore a bullish candle with increasing OI, results in the script counting an increase in Long Positions. Whereas a bearish candle and increasing OI, results in an increase of Short Positions.
Following that, the script estimates where these new positions will be liquidated (set either as a manual percentage, or using one of the defined presets).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What makes this indicator unique from "Liquidation Levels" scripts, is the the way it groups potential liquidation volumes in segments, creating a cumulative view of liquidity potential - a true heatmap, not simply levels. To further clarify, liquidity within a set range is added to the segment of that range. The settings allow you to set the resolution of the range, according to preference. There is also an Automatic mode (at this moment limited to Bitcoin).
Regular OI Liquidation levels do not combine their volumes when overlapped, nor do they adhere to any ranges - making them scattered and not representative of the true liquidity in that area. This Liquidation Heatmap fixes all of those limitations.
Another unique addition to this Liquidation Heatmap, is my custom three tier color gradients with alpha support (transparency). This function allows a seamless transition of the coloring in liquidation potential from purple (minimum), to blue (medium), to yellow (maximum). This allows a larger range of liquidity identification, along with further aesthetic bonuses.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How to use this indicator?
In general, such a tool can be used in numerous ways. It is not a standalone signal, meaning you should always compliment this tool with your own TA and reasoning.
One way of using this tool, is to anticipate that the price will continue on its trend, when you see it moving towards a zone of high liquidity (expecting that liquidity to be taken out).
Another way of using this tool, would be to anticipate a kickback after a liquidation event has taken place, thus returning to the mean.
Kalman MomentumKalman Filter
The Kalman Filter is an algorithm used for recursive estimation and filtering of time-series data. It was developed by Rudolf E. Kálmán in the 1960s and has found widespread applications in various fields, including control systems, navigation, signal processing, and finance.
The primary purpose of the Kalman filter is to estimate the state of a dynamic system based on a series of noisy measurements over time. It operates recursively, meaning it processes each new measurement and updates its estimate of the system state as new data becomes available.
Kalman Momentum Indicator
This indicator implements the Kalman Filter to provide a smoothed momentum indicator using returns. The momentum in this indicator is calculated by getting the logarithmic returns and then getting the expected value.
The Kalman calculation in this indicator is used to filter and predict the next value based on the logarithmic returns expected value.
Here's a simplified explanation of the steps and how they are applied in the Script:
State Prediction: Predict the current state based on the previous state estimate.
Error Covariance Prediction: Predict the covariance of the prediction error.
Correction Step:
Kalman Gain Calculation: Calculate the Kalman gain, which determines the weight given to the measurement.
State Correction: Update the state estimate based on the measurement.
Error Covariance Correction: Update the error covariance.
In this Script, the Kalman Filter is applied to estimate the state of the system, with two state variables.
When the Kalman Momentum is above 0, there is positive momentum or positive smoothed expected value.
When the Kalman Momentum is below 0, there is negative momentum or negative smoothed expected value.
How to Use:
Trend Identification:
Positive values of the Kalman Momentum Indicator indicates positive expected value, while negative values suggest negative expected value.
You can look for changes in the sign of the indicator to identify potential shifts in market direction.
Volatility Analysis:
Observe the behavior of the indicator during periods of high and low volatility. Changes in the volatility of the Kalman Momentum Indicator may precede changes in market conditions.
Filtering Noise:
The Kalman Filter is known for its ability to filter out noise in time series data. Use the Kalman Momentum Indicator to filter out the noise in momentum to catch the trend more clearly.
Squeezes:
At time there may be squeezes, and these are zones with low volatility. What could follow after these zones are expansions and huge trending moves.
Indicator Settings:
You can change the source of the calculations.
There is also a lookback for the log returns.
Understanding Expected Value in Trading:
The Expected Value is a fundamental concept that shows the potential outcomes of a trading strategy or individual trade over a series of occurrences. It is a measure that represents the average outcome when a particular action is repeated multiple times.
Images of the indicator:
Sync Frame (MTF Charts) [Kioseff Trading]Hello!
This indicator "Sync Frame" displays various lower timeframe charts for the asset on your screen!
5 lower timeframe candle charts shown
Timeframes auto-calculated using the new timeframe.from_seconds() function
Heikin-Ashi candles available
Baseline chart type available
Dynamic Scaling for ease of use
User customizable timeframes
Simple script (:
The image above shows the baseline chart type.
Time image above shows a traditional candlestick chart.
The image above shows a hekin-ashi chart.
The image above shows the indicator when nearly zoomed in as much as possible. The lower timeframe charts adjust to my chart positioning.
The image above shows my screen fully zoomed out; the lower timeframe charts adjust in both height and width to accommodate my chart positioning!
Thank you for checking this out (:
Blockchain FundamentalThis indicator is made for traders to harness fundamental blockchain data for better decision-making. Unlike traditional tools, this indicator doesn't depend on standard technical indicators. It offers a novel perspective by focusing on core blockchain metrics like capitalization, miner activity, and other intrinsic data elements. I've designed a distinct scoring logic, exclusive to BF, ensuring it's user-friendly and provides actionable insights for traders at all levels.
Mainly created for Bitcoin , but can be applied to any other crypto assets in cost of losing some metrics in the analysis.
Ethereum chart:
Features:
Customizable Moving Averages:
Choose from an array of moving averages, with the flexibility to adjust the length for a tailored analysis, aiding in pinpointing asset trends.
Blockchain Metrics Integration:
Incorporates a range of blockchain metrics such as Market Cap to Realised Cap ratio, Spent Output Profit Ratio, ATH Drawdown, and more.
Blockchain Metrics Evaluation:
Each metric can be toggled on/off to customize the analysis. Using default settings, traders can use all of the metrics combined.
Every metric is essentially evaluated on a scale from -100 to 100 and then combined with others. If any metric is uncertain about its direction (equals to 0), then the score of it is not accounted in a final calculation.
Kalman Filter:
This indicator offers the option to apply a Kalman filter to the signals, enhancing the smoothness and accuracy of the indicator’s output. This is my approach to mitigate the noise in the final output.
Signal Oscillator:
Displays the aggregated score of all selected blockchain metrics.
Offers visual signals with adjustable upper and lower bounds for easy interpretation based on particular asset observation.
Visual Elements:
Signal Oscillator:
A visual representation of the aggregated blockchain fundamental score.
(White line for a raw calculation, orange line for kalman-filtered one)
Signal Counter:
Displays the count of metrics currently being considered in the fundamental score calculation. (grey line at the middle of an indicator)
Buy/Sell Signal Coloring:
The background color changes to indicate potential buying or selling opportunities based on user-defined bounds.
Usage:
Analysis:
Use the signal oscillator to identify potential market tops and bottoms based on blockchain fundamental data.
Adjust the bounds to customize the sensitivity of buy/sell signals.
Customization:
Enable/disable specific blockchain metrics to tailor the indicator to your analytical needs.
Adjust the moving average type and length for better analysis.
Integration:
Combine with other technical indicators to create a comprehensive trading strategy.
Utilize in conjunction with volume and price action analysis for enhanced decision-making. Every output could be used in traders custom strategies and indicators.
IU Probability CalculatorHow This Script Works:
1. This script calculate the probability of price reaching a user-defined price level within one candle with the help Normal Distribution Probability Table.
2. Normal Distribution Probability Table is use for calculating probability of events, it's very powerful for calculation of probability and this script is fully based on that table.
3. It takes the Average True Range value or Standard Deviation value of past user-defined length bar.
4. After that it take this formula z = ( price_level - close ) / (ATR or Standard Deviation) and return the value for z, for the bearish side it take z = (close - price level) / (ATR or Standard Deviation ) formula.
5. Once we have the z it look into Normal Distribution Probability Table and match the value.
6. Now the value of z is multiple buy 100 in order to make it look in percentage term.
7. After that this script subtract the final value with 100 because probability always comes under 100%
8. finally we plot the probability at the bottom of the chart the red line indicates "The probability of price not reaching that price level", While the green line indicates "Probability of price Reaching that level " .
9. This script will work fine for both of the directions
How This Is Useful For The User:
1. With this script user can know the probability of price reaching the certain level within one candle for both Directions .
2. This is useful while creating options hedging strategies
3. This can be helpful for deciding stop loss level.
4. It's useful for scalpers for managing their traders and it can be use by binary option traders.
IU Average move How The Script Works :
1. This script calculate the average movement of the price in a user defined custom session and plot the data in a table from on top left corner of the chart.
2. The script takes highest and lowest value of that custom session and store their difference into an array.
3. Then the script average the array thus gets the average price.
4. Addition to that the script converter the price pip change into percentage in order to calculate the value in percentage form.
5. This script is pure price action based the script only take price value and doesn't take any indicator for calculation.
6. The script works on every type of market.
7. If the session is invalid it returns nothing
8. The background color, text color and transparency is changeable.
How User Can Benefit From This Script:
1. User can understand the volatility of any session that he/she wish to trade.
2. It can be helpful for understanding the average price moment of any tradeble asset.
3. It will give the average price movement both in percentage and points bases.
4. By understanding the volatility user can adjust his stop loss or take profit with respect his risk management.
Quadratic & Linear Time Series Regression [SS]Hey everyone,
Releasing the Quadratic/Linear Time Series regression indicator.
About the indicator:
Most of you will be familiar with the conventional linear regression trend boxes (see below):
This is an awesome feature in Tradingview and there are quite a few indicators that follow this same principle.
However, because of the exponential and cyclical nature of stocks, linear regression tends to not be the best fit for stock time series data. From my experience, stocks tend to fit better with quadratic (or curvlinear) regression, which there really isn't a lot of resources for.
To put it into perspective, let's take SPX on the 1 month timeframe and plot a linear regression trend from 1930 till now:
You can see that its not really a great fit because of the exponential growth that SPX has endured since the 1930s. However, if we take a quadratic approach to the time series data, this is what we get:
This is a quadratic time series version, extended by up to 3 standard deviations. You can see that it is a bit more fitting.
Quadratic regression can also be helpful for looking at cycle patterns. For example, if we wanted to plot out how the S&P has performed from its COVID crash till now, this is how it would look using a linear regression approach:
But this is how it would look using the quadratic approach:
So which is better?
Both linear regression and quadratic regression are pivotal and important tools for traders. Sometimes, linear regression is more appropriate and others quadratic regression is more appropriate.
In general, if you are long dating your analysis and you want to see the trajectory of a ticker further back (over the course of say, 10 or 15 years), quadratic regression is likely going to be better for most stocks.
If you are looking for short term trades and short term trend assessments, linear regression is going to be the most appropriate.
The indicator will do both and it will fit the linear regression model to the data, which is different from other linreg indicators. Most will only find the start of the strongest trend and draw from there, this will fit the model to whatever period of time you wish, it just may not be that significant.
But, to keep it easy, the indicator will actually tell you which model will work better for the data you are selecting. You can see it in the example in the main chart, and here:
Here we see that the indicator indicates a better fit on the quadratic model.
And SPY during its recent uptrend:
For that, let's take a look at the Quadratic Vs the Linear, to see how they compare:
Quadratic:
Linear:
Functions:
You will see that you have 2 optional tables. The statistics table which shows you:
The R Squared to assess for Variance.
The Correlation to assess for the strength of the trend.
The Confidence interval which is set at a default of 1.96 but can be toggled to adjust for the confidence reading in the settings menu. (The confidence interval gives us a range of values that is likely to contain the true value of the coefficient with a certain level of confidence).
The strongest relationship (quadratic or linear).
Then there is the range table, which shows you the anticipated price ranges based on the distance in standard deviations from the mean.
The range table will also display to you how often a ticker has spent in each corresponding range, whether that be within the anticipated range, within 1 SD, 2 SD or 3 SD.
You can select up to 3 additional standard deviations to plot on the chart and you can manually select the 3 standard deviations you want to plot. Whether that be 1, 2, 3, or 1.5, 2.5 or 3.5, or any combination, you just enter the standard deviations in the settings menu and the indicator will adjust the price targets and plotted bands according to your preferences. It will also count the amount of time the ticker spent in that range based on your own selected standard deviation inputs.
Tips on Use:
This works best on the larger timeframes (1 hour and up), with RTH enabled.
The max lookback is 5,000 candles.
If you want to ascertain a longer term trend (over years to months), its best to adjust your chart timeframe to the weekly and/or monthly perspective.
And that's the indicator! Hopefully you all find it helpful.
Let me know your questions and suggestions below!
Safe trades to all!