US Composite Leading Indicator (CLI)The US Composite Leading Indicator (CLI), normalized for the United States, closely mirrors the Conference Board "Leading Economic Index" (LEI). It offers unique insights into economic and financial dynamics.
The Composite Leading Indicator (CLI) is an economic tool designed to anticipate economic developments. It is created by aggregating and normalizing a wide range of economic and financial data from various sources.
The normalized data is then aggregated, and a composite indicator is calculated by taking a weighted average of individual indicators.
The CLI is used to provide early insights into the state of the economy and to anticipate future economic trends. It is particularly valuable for predicting economic downturns, including recessions.
The CLI is an essential tool for economists, governments, businesses, and investors seeking to understand economic trends and make informed decisions.
Key Features:
1. Early Warning: Just like its counterpart, the CLI indicator excels at offering early warnings about significant economic events, particularly economic crises. This makes it an indispensable asset for analysts and investors.
2. Recession Indicators: The moving average serves as an early warning system for potential economic recessions. When it crosses the indicator line from the bottom to the top while surpassing a predefined threshold (e.g., 101), it signals a potential crisis.
3. Market Impact: The CLI indicator provides valuable insights into the performance of financial markets, offering cues about indices such as the S&P 500, Nasdaq, Dow Jones, and more.
Why It Matters:
Understanding the US Composite Leading Indicator (CLI) indicator, normalized for the United States, is crucial for anticipating economic shifts and preparing for changes in financial markets. By analyzing a diverse array of economic factors, it provides a holistic view of economic well-being. Whether you're an investor or economist, this indicator can be an invaluable resource for staying informed about market trends and major economic developments.
Source:
www.data.oecd.org
Forecasting
Supertrend Multiasset Correlation - vanAmsen Hello traders!
I am elated to introduce the "Supertrend Multiasset Correlation" , a groundbreaking fusion of the trusted Supertrend with multi-asset correlation insights. This approach offers traders a nuanced, multi-layered perspective of the market.
The Underlying Concept:
Ever pondered over the term Multiasset Correlation?
In the intricate tapestry of financial markets, assets do not operate in silos. Their movements are frequently intertwined, sometimes palpably so, and at other times more covertly. Understanding these correlations can unlock deeper insights into overarching market narratives and directional trends.
By melding the Supertrend with multi-asset correlations, we craft a holistic narrative. This allows traders to fathom not merely the trend of a lone asset but to appreciate its dynamics within a broader market tableau.
Strategy Insights:
At the core of this indicator is its strategic approach. For every asset, a signal is generated based on the Supertrend parameters you've configured. Subsequently, the correlation of daily price changes is assessed. The ultimate signal on the selected asset emerges from the average of the squared correlations, factoring in their direction. This indicator not only accounts for the asset under scrutiny (hence a correlation of 1) but also integrates 12 additional assets. By default, these span U.S. growth ETFs, value ETFs, sector ETFs, bonds, and gold.
Indicator Highlights:
The "Supertrend Multiasset Correlation" isn't your run-of-the-mill Supertrend adaptation. It's a bespoke concoction, tailored to arm traders with an all-encompassing view of market intricacies, fortified with robust correlation metrics.
Key Features:
- Supertrend Line : A crystal-clear visual depiction of the prevailing market trajectory.
- Multiasset Correlation : Delve into the intricate interplay of various assets and their correlation with your primary instrument.
- Interactive Correlation Table : Nestled at the top right, this table offers a succinct overview of correlation metrics.
- Predictive Insights : Leveraging correlations to proffer predictive pointers, adding another layer of conviction to your trades.
Usage Nuances:
- The bullish Supertrend line radiates in a rejuvenating green hue, indicative of potential upward swings.
- On the flip side, the bearish trajectory stands out in a striking red, signaling possible downtrends.
- A rich suite of customization tools ensures that the chart resonates with your trading ethos.
Parting Words:
While the "Supertrend Multiasset Correlation" bestows traders with a rejuvenated perspective, it's paramount to embed it within a comprehensive trading blueprint. This would include blending it with other technical tools and adhering to stringent risk management practices. And remember, before plunging into live trades, always backtest to fine-tune your strategies.
Supertrend Forecast - vanAmsenHello everyone!
I am thrilled to present the "vanAmsen - Supertrend Forecast", an advanced tool that marries the simplicity of the Supertrend with comprehensive statistical insights.
Before we dive into the functionalities of this indicator, it's essential to understand its foundation and theory.
The Theory:
What exactly is the Supertrend?
The Supertrend, at its core, is a momentum oscillator. It's a tool that provides buy and sell signals based on the prevailing market trend. The underlying principle is straightforward: by analyzing average price data and volatility over a period, the Supertrend gives us a line that represents the trend direction.
However, trading isn't just about identifying trends; it's about understanding their strength, potential profitability, and historical accuracy. This is where statistics come into play. By incorporating statistical analysis into the Supertrend, we can gain deeper insights into the market's behavior.
Description:
The "vanAmsen - Supertrend Forecast" isn't just another Supertrend indicator. It's a comprehensive tool designed to offer traders a holistic view of market trends, backed by robust statistical analysis.
Key Features:
- Supertrend Line: A visual representation of the current market direction.
- Win Rate & Expected Return: Delve into the historical accuracy and profitability of the prevailing trend.
- Average Percentage Change: Understand the average price fluctuation for both winning and losing trends.
- Forecast Lines: Project future price movements based on historical data, providing a roadmap for potential scenarios.
- Interactive Table: A concise table in the top right, offering a snapshot of all vital metrics at a glance.
Usage:
- The bullish Supertrend line adopts an Aqua hue, indicating potential upward momentum.
- In contrast, the bearish line is painted in Orange, suggesting potential downtrends.
- Customize your chart by toggling labels, tables, and lines according to preference.
Recommendation:
The "vanAmsen - Supertrend Forecast" is undoubtedly a powerful tool in a trader's arsenal. However, it's imperative to combine it with other technical analysis tools and sound risk management practices. It's always prudent to backtest strategies with historical data before embarking on live trading.
Strong Pullback Indicator [Rami_LB]Strong Pullback Indicator
Description:
The Strong Pullback Indicator is designed to identify potential pullbacks or even trend reversals by utilizing a specific candlestick pattern in conjunction with the Relative Strength Index (RSI). It is advised to employ this indicator in chart intervals of 15 minutes or higher, as intervals below 15 minutes may generate excessive false signals.
Working Mechanism:
Upon detecting the designated candlestick pattern, the indicator examines whether any of the last five candles exhibit RSI values below 30 or above 70 across at least four distinct time intervals, depending on whether the pattern is bullish or bearish. The RSI calculations incorporate eight different intervals: 1 minute (1m), 5 minutes (5m), 15 minutes (15m), 30 minutes (30m), 1 hour (1h), 2 hours (2h), 4 hours (4h), and 1 day (1d). An arrow is rendered above or below the current candle only when these conditions are met.
Users have the option to adjust the number of overbought or oversold intervals, as well as the general settings for the RSI.
SL/TP Lines:
The indicator can also serve as a trade signal to initiate trades in the opposite direction. To evaluate the potential success of a trade in a backtesting scenario, SL (Stop Loss) and TP (Take Profit) lines can be displayed on the chart. The SL is calculated by taking the distance from the close of the current candle to the high/low of the previous candle and multiplying it by 2.
In the settings, you can alter the Risk Reward Ratio (RRR) of the trade. Given the pullback nature of this indicator, a RRR of 1:1 is deemed logical, thus set as the default value.
Bullish vs. Bearish Candle Counter:
An additional feature of this indicator is its ability to analyze the last 100 candles to ascertain the ratio of bullish to bearish candles. When a 60% threshold is reached, the chart background color alters accordingly. This feature was conceived after a thorough analysis of over 50,000 candles of a currency pair revealed nearly identical counts of bullish and bearish candles, suggesting a market tendency to maintain this balance.
Within the settings, you have the flexibility to modify the number of candles to be analyzed and the percentage threshold for each candle type.
Should you have any ideas on how to enhance the accuracy of this indicator, or suggestions for other indicators that could improve the signals, feel free to leave a comment.
Open, Open +/- EMA ATR Lines with LabelsThis indicator provides traders with a clear visualization of the opening price and its potential movement range for a specific timeframe, based on the Exponential Moving Average (EMA) of the Average True Range (ATR).
Features:
Opening Price Line: A green line representing the opening price for the chosen timeframe.
EMA ATR Lines:
An upper blue line, calculated as the opening price plus the EMA of the ATR.
A lower blue line, calculated as the opening price minus the EMA of the ATR.
Labels: Each line comes with a label on its right side, displaying the price level and, for the EMA ATR lines, the distance in pips from the opening price.
Custom Timeframes: Users can select their desired timeframe for calculations, making this tool versatile for different trading strategies.
Usage:
The EMA-smoothed ATR provides a measure of volatility. By plotting this value above and below the opening price, traders get a sense of potential price movement for the selected timeframe. This can be particularly useful for setting stop losses, take profit levels, or identifying breakout points.
For instance, if the price breaks above the upper EMA ATR line, it might indicate a potential upward move, especially if other market conditions align.
Customization:
Timeframe: Choose from various timeframes like 1-minute, 5-minutes, daily, weekly, and more.
ATR Length: Adjust the length of the ATR for more or less sensitivity.
This indicator is designed to offer traders a quick way to gauge potential price movement for their chosen timeframe. By combining the principles of the opening price and volatility measured by the EMA-smoothed ATR, it provides a straightforward yet powerful tool for various trading scenarios.
Machine Learning: SuperTrend Strategy TP/SL [YinYangAlgorithms]The SuperTrend is a very useful Indicator to display when trends have shifted based on the Average True Range (ATR). Its underlying ideology is to calculate the ATR using a fixed length and then multiply it by a factor to calculate the SuperTrend +/-. When the close crosses the SuperTrend it changes direction.
This Strategy features the Traditional SuperTrend Calculations with Machine Learning (ML) and Take Profit / Stop Loss applied to it. Using ML on the SuperTrend allows for the ability to sort data from previous SuperTrend calculations. We can filter the data so only previous SuperTrends that follow the same direction and are within the distance bounds of our k-Nearest Neighbour (KNN) will be added and then averaged. This average can either be achieved using a Mean or with an Exponential calculation which puts added weight on the initial source. Take Profits and Stop Losses are then added to the ML SuperTrend so it may capitalize on Momentum changes meanwhile remaining in the Trend during consolidation.
By applying Machine Learning logic and adding a Take Profit and Stop Loss to the Traditional SuperTrend, we may enhance its underlying calculations with potential to withhold the trend better. The main purpose of this Strategy is to minimize losses and false trend changes while maximizing gains. This may be achieved by quick reversals of trends where strategic small losses are taken before a large trend occurs with hopes of potentially occurring large gain. Due to this logic, the Win/Loss ratio of this Strategy may be quite poor as it may take many small marginal losses where there is consolidation. However, it may also take large gains and capitalize on strong momentum movements.
Tutorial:
In this example above, we can get an idea of what the default settings may achieve when there is momentum. It focuses on attempting to hit the Trailing Take Profit which moves in accord with the SuperTrend just with a multiplier added. When momentum occurs it helps push the SuperTrend within it, which on its own may act as a smaller Trailing Take Profit of its own accord.
We’ve highlighted some key points from the last example to better emphasize how it works. As you can see, the White Circle is where profit was taken from the ML SuperTrend simply from it attempting to switch to a Bullish (Buy) Trend. However, that was rejected almost immediately and we went back to our Bearish (Sell) Trend that ended up resulting in our Take Profit being hit (Yellow Circle). This Strategy aims to not only capitalize on the small profits from SuperTrend to SuperTrend but to also capitalize when the Momentum is so strong that the price moves X% away from the SuperTrend and is able to hit the Take Profit location. This Take Profit addition to this Strategy is crucial as momentum may change state shortly after such drastic price movements; and if we were to simply wait for it to come back to the SuperTrend, we may lose out on lots of potential profit.
If you refer to the Yellow Circle in this example, you’ll notice what was talked about in the Summary/Overview above. During periods of consolidation when there is little momentum and price movement and we don’t have any Stop Loss activated, you may see ‘Signal Flashing’. Signal Flashing is when there are Buy and Sell signals that keep switching back and forth. During this time you may be taking small losses. This is a normal part of this Strategy. When a signal has finally been confirmed by Momentum, is when this Strategy shines and may produce the profit you desire.
You may be wondering, what causes these jagged like patterns in the SuperTrend? It's due to the ML logic, and it may be a little confusing, but essentially what is happening is the Fast Moving SuperTrend and the Slow Moving SuperTrend are creating KNN Min and Max distances that are extreme due to (usually) parabolic movement. This causes fewer values to be added to and averaged within the ML and causes less smooth and more exponential drastic movements. This is completely normal, and one of the perks of using k-Nearest Neighbor for ML calculations. If you don’t know, the Min and Max Distance allowed is derived from the most recent(0 index of data array) to KNN Length. So only SuperTrend values that exhibit distances within these Min/Max will be allowed into the average.
Since the KNN ML logic can cause these exponential movements in the SuperTrend, they likewise affect its Take Profit. The Take Profit may benefit from this movement like displayed in the example above which helped it claim profit before then exhibiting upwards movement.
By default our Stop Loss Multiplier is kept quite low at 0.0000025. Keeping it low may help to reduce some Signal Flashing while not taking extra losses more so than not using it at all. However, if we increase it even more to say 0.005 like is shown in the example above. It can really help the trend keep momentum. Please note, although previous results don’t imply future results, at 0.0000025 Stop Loss we are currently exhibiting 69.27% profit while at 0.005 Stop Loss we are exhibiting 33.54% profit. This just goes to show that although there may be less Signal Flashing, it may not result in more profit.
We will conclude our Tutorial here. Hopefully this has given you some insight as to how Machine Learning, combined with Trailing Take Profit and Stop Loss may have positive effects on the SuperTrend when turned into a Strategy.
Settings:
SuperTrend:
ATR Length: ATR Length used to create the Original Supertrend.
Factor: Multiplier used to create the Original Supertrend.
Stop Loss Multiplier: 0 = Don't use Stop Loss. Stop loss can be useful for helping to prevent false signals but also may result in more loss when hit and less profit when switching trends.
Take Profit Multiplier: Take Profits can be useful within the Supertrend Strategy to stop the price reverting all the way to the Stop Loss once it's been profitable.
Machine Learning:
Only Factor Same Trend Direction: Very useful for ensuring that data used in KNN is not manipulated by different SuperTrend Directional data. Please note, it doesn't affect KNN Exponential.
Rationalized Source Type: Should we Rationalize only a specific source, All or None?
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
Machine Learning Smoothing Type: How should we smooth our Fast and Slow ML Datas to be used in our KNN Distance calculation? SMA, EMA or VWMA?
KNN Distance Type: We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.
Machine Learning Length: How far back is our Machine Learning going to keep data for.
k-Nearest Neighbour (KNN) Length: How many k-Nearest Neighbours will we account for?
Fast ML Data Length: What is our Fast ML Length?? This is used with our Slow Length to create our KNN Distance.
Slow ML Data Length: What is our Slow ML Length?? This is used with our Fast Length to create our KNN Distance.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Euclidean Distance Predictive Candles [SS]Finally releasing this, its been in the works for the past 2 weeks and has undergone many iterations.
I am not sure if I am 100% happy with it yet, but I guess its best to release and get feedback to make improvements.
So this is the Euclidean distance predictive candle indicator and what it does is exactly what it sounds like, it uses Euclidean distance to identify similar candles and then plot the candles and range that immediately proceeded like candles.
While this is using a general machine learning/data science approach (Euclidean distance), I do not employ the KNN (Nearest Neighbors) algo into this. The reason being is it simply offered no predictive advantage than isolating for the last case. I tried it, I didn't like it, the results were not improve and, at times, acutally hindered so I ditched it. Perhaps it was my approach but using some other KNN indicators, I just don't really find them all that more advantageous to simply relying on the Law of Large Numbers and collecting more data rather than less data (which we will get into later in this explanation).
So using this indicator:
There is a lot of customizability here. And the reason is, not all settings are going to work the same for all tickers. To help you narrow down your parameters, I have included various backtest results that show you how the model is performing. You see in the AMZN chart above, with the current settings, it is performing optimally, with a cumulative range pass of 99% (meaning that, of all the cases, the indicator accurately predicted the next day high OR low range 99% of the time), and the ability to predict the candle slightly over 52%.
The recommended settings, from me, are as follows:
So these are generally my recommended settings.
Euclidian Tolerance: This will determine the parameters to look for similar candles. In general, the lower the tolerance, the greater the precision. I recommend keeping it between 0.5, for tickers with larger prices (like ES1! futures or NQ1!) or 0.05 for tickers with lower TPs, like SPY or QQQ.
If the ED Tolerance is too extreme that the indicator cannot find identical setups, it will alert you:
But in general, the more precise you can get it, the better.
Anchor Type: You will see the option to anchor by "Predicted Open" or by "Previous Close". I suggest sticking with anchoring by predicted open. All this means is, it is going to anchor your range, candle, high and low targets by the predicted open price. Anchoring by previous close will anchor by the close of yesterday. Both work okay, but in general the results from anchoring to predicted open have higher pass rates and more accurately depict the candle.
Euclidean Distance Measurement Type: You can choose to measure by candle body or from high to low wicks. I haven't played around with measuring from high to low wicks all that much, because candle body tends to do the job. But remember, ED is a neutral measurement. Which means, its not going to distinguish between a red or green candle, just the formation of the candle. Thus, I tend to recommend, pragmatically, not to necessarily rely on the candle being red or green, but one the formation of the candle (where are the wicks going, are there more bearish wicks or bullish wicks) etc. Examples will follow.
Range Prediction Type: You can filter the range prediction type by last instance (in which, it will pull the previous identical candle and plot the next candle that followed it, adjusted for the current ranges) or "Average of All Cases". So this is where we need to talk a little bit about the law of large numbers.
In general, in statistics, when you have a huge amount of random data, the law of large numbers stipulates that, within this randomness should be repeated events. This is why sometimes chart patterns work, sometimes they don't. When we filter by the average of all cases, we are relying on the law of large numbers. In general, if you are getting good Backtest readings from Last Instance, then you don't need to use this function. But it provides an alternative insight into potential candle formations next day. Its not a bad idea to compare between the two and look for similarities and differences.
So now that we have covered the boring details, let's get into how to use the indicator and some examples.
So the indicator is plotting the range and candle for the next day. As such, we are not looking at the current candle being plotted, but we are looking at the previous candle (see image below for example):
The green arrow shows the prediction for Friday, along with the corresponding result. The purple arrow shows the prediction for Monday which we have yet to realize.
So remember when you are using this, you need to look at the previous candle, and not the candle that it is currently plotting with realtime data, because it is plotting for the next candle.
If you are plotting by last instance, the indicator will tell you which day it is pulling its data from if you have opted to toggle on the demographic data:
You can see the green arrow pointing to the date where it is pulling from. This data serves as the example candle with the candle proceeding this date being the anchored candle (or the predicted candle).
Price Targets and Probability:
In the chart, you can see the green arrow pointing to the green portion of the table. In this table, it will give you the current TPs. These represent the current time target price, which means, the TPs shown here are for Friday. On Monday, the table will update with the TPs for Monday, etc. If you want to view the TPs in advance, you can view them from the actual candle itself.
Below the TPs, you see a bullish 7:6. It means, in a total of 13 cases, the next candle was bullish 7 times and bearish 6 times. Where do we see the number of cases? In the demographic table as well:
Auxiliary functions
Because you are using the previous candle, if you want to avoid confusion, you can have the indicator plot the price targets over the predicted candle, to anchor your attention so to speak. Simply select "Label" in the "Show Price Targets" section, which will look like this:
You can also ask the indicator to plot the demographic data of Higher High, Low, etc. information. What this does is simply looks at all the cases and plots how many times higher highs, lows, lower lows, highs etc. were made:
This will just count all of the cases identified and plot the number of times higher highs, lows, etc. were made.
Concluding Remarks
This is a kind of complex indicator and I can appreciate it may take some getting used to.
I will try to post a tutorial video at some point next week for it, so stay tuned for that.
But this isn't designed to make your life more complicated, just to help give you insights into potential outcomes for the next day or hour or 5 minute (it can be used on all timeframes).
If you find it helpful, great! If not, that's okay, too :-).
Please be aware, this is not my forte of indicators. I am not a data scientist or programmer. My background is in Epi and we don't use these types of data science approaches, so if you have any suggestions or critiques, feel free to share them below.
Otherwise, I hope you enjoy!
Take care everyone and safe trades!
Bullish vs. Bearish Candle CounterFollowing an exhaustive analysis of the most recent 50,000 candles within a given currency pair, a notable equilibrium between bearish and bullish candles has emerged as a persistent market phenomenon. This equilibrium, indicative of the market's continuous endeavor to establish parity, has spurred the development of the following indicator.
The indicator meticulously scrutinizes the preceding 100 candles, promptly triggering an on-chart marker when either bullish or bearish candle counts surpass the threshold of 60%. This marker serves as an invaluable tool, providing traders with a potential signal for the initiation of a trend reversal.
As such, this indicator serves as a valuable asset in a trader's toolkit, offering insights into shifts in market sentiment and the prospect of emerging trends.
Key Features:
- Customizable Candle Count: Traders can set the number of candlesticks to be analyzed in the input parameters, allowing flexibility in their analysis.
- Bullish and Bearish Percentage: Users can define their desired percentage for both bullish and bearish candles in the indicator's settings. The indicator calculates the percentage of each candle type within the specified range.
- Arrow Signals: The indicator plots arrows above or below the current candle, indicating bullish or bearish conditions based on the defined percentage thresholds. A green arrow signifies bullish sentiment, while a red arrow denotes bearish sentiment.
How to Use:
- Adjust Parameters: In the indicator settings, users can customize the number of candlesticks to be analyzed, as well as set their preferred percentages for both bullish and bearish conditions.
- Interpret Arrows: The indicator generates arrows above or below the current candle, reflecting the prevailing market sentiment. A green arrow suggests a bullish bias, while a red arrow indicates a bearish bias.
- Trade with Confidence: Traders can use this indicator as a tool to gauge market sentiment and make informed trading decisions. It helps identify potential entry and exit points based on the chosen percentage thresholds.
Multiperiod Volume Pressure Indicator
Description:
The Volume Pressure Indicator is a powerful tool designed to assess market sentiment based on a combination of price and volume data. By analyzing buy and sell pressure within specific lookback periods, this indicator provides valuable insights into the intensity of market buying and selling activities. Traders can use this information to make informed decisions, especially during periods of price consolidation or trend reversal.
Key Features:
- **Multi-Period Analysis:** Utilizes multiple lookback periods (1, 2, and 4) to calculate buy and sell pressures, offering a nuanced view of market dynamics over different timeframes.
- **Pressure Calculation:** Computes buy and sell pressures based on price range and closing values, providing a comprehensive understanding of market participant behavior.
- **Color-Coded Bars:** Visualizes market sentiment by coloring bars according to the number of positive (buy pressure > sell pressure) periods observed within the specified lookback periods.
How to Use:
- **Color Coding:** Green bars represent periods where buy pressure dominates, indicating potential buying interest. Yellow bars suggest a balance between buy and sell pressures. Red bars signal periods dominated by sell pressure, indicating potential selling interest.
- **Lookback Periods:** Shorter lookback periods (e.g., 1) offer insights into immediate market sentiment, while longer periods (e.g., 4) provide a broader perspective. Analyzing multiple periods can help traders confirm trends and anticipate reversals.
Customization:
- **Lookback Periods:** Adjust the length of the lookback periods (1, 2, and 4) to match your trading style and timeframe preferences.
Disclaimer:
Trading involves risk, and past performance is not indicative of future results. Always conduct thorough analysis and apply proper risk management techniques before making trading decisions.
Usage Scenarios:
- **Trend Confirmation:** Use the indicator to confirm the strength of an ongoing trend. Consistent green bars can validate a bullish trend, while red bars may confirm a bearish trend.
- **Reversal Signals:** Look for transitions in bar colors to identify potential trend reversals. A shift from green to yellow/red or vice versa can indicate changing market sentiment.
- **Divergence Analysis:** Compare price movements with the indicator's bar colors. Divergence between price trends and bar colors may signal upcoming price movements.
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.
@tk · spectral█ OVERVIEW
This script is an indicator that helps traders to identify the price difference between spot and futures of the current crypto plotted into the chart. It works in both types of markets, when the chart is plotting the crypto in spot market, it will compare with its respective futures ticker and vice-versa. If the current asset isn't a crypt ticker, the indicator will not be plotted into the chart.
█ MOTIVATION
Since crypto's derivative market is based on spot market asset's price, to calculate the arbitrage mechanisms that attempts to balance the asset price, this indicator can help traders to identify some spot and futures price divergence that can create an anomaly of funding rate and can push it to an extreme negative — or positive — rate. So, easing to track the price difference between both markets will bring more evidences to identify an artificial price move, specially in crypto assets with low market cap.
█ CONCEPT
The trading concept to use this indicator is the concept of the arbitrage machamism created by exchanges that calculates the funding rate based on spot and futures price difference that will vary from exchange to exchange. This strategy don't works alone. It needs to be aligned together with others indicators like Exponential Moving Averages, Chart Patterns, Support and Resistance, and so on... Even more confluences that you have, bigger are your chances to increase the probability for a successful trade. So, don't use this indicator alone. Compose a trading strategy and use it to improve your analysis.
█ CUSTOMIZATION
This indicator allows the trader to customize the following settings:
GENERAL
Text size
Changes the font size of price difference table to improve accessibility.
Type: string
Options: `tiny`, `small`, `normal`, `large`.
Default: `small`
Position
Changes the position of price difference table.
Type: string
Options: `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`.
Default: `bottom_right`
Pair Quote
The ticker quote symbol that will be used to base the ticker comparison from spot to futures (e.g. BTCUSDT which `USDT` is the quote. ETHBTC which `BTC` is the quote).
Type: string
Default: USDT
Spectrum Color
The color of the spectrum candles. Spectrum candles are the candles of the opposite market. If the current ticker is in the spot market, the spectrum candles will be the price of the futures market.
Type: color
Default: #434651
█ FUNCTIONS
The indicator contains the following functions:
stripStarts(src, str)
Strips a defined pattern from a string.
Parameters:
src: (string) Source string
str: (string) String pattern to be stripped from start of source string.
Returns: (string) Stripped string with matched regex pattern.
Golden Level Predictions v1.0Golden Level Predictions (GLP) Trading Indicator
This script introduces a custom trading indicator named "GLP" tailored for the TradingView platform. It offers various price levels derived from Fibonacci calculations and other mathematical models, assisting traders in pinpointing potential overpriced and discounted price levels.
Key Features:
User Inputs : Users have the flexibility to select their desired timeframe, with options ranging from Weekly, Daily, Monthly, and more. Additionally, they can opt to showcase Fibonacci lines and the associated prices within these levels.
Price Level Calculations :
- Employs constants such as the Golden Ratio (PHI) and Pi (PI) to extract various multipliers and factors.
- Assesses if the current asset is a cryptocurrency and tweaks calculations accordingly.
- Determines overpriced and discounted price levels, drawing from the current open price and past data.
Fibonacci Levels :
- For each overpriced and discounted level, the script computes intermediary Fibonacci levels, including 23.6%, 38.2%, 50%, 61.8%, and 78.6% (the 3rd level is excluded due to plot limitations).
- These levels are illustrated on the chart, granting traders a more detailed view of price targets.
Visual Elements :
- Projects horizontal lines to the subsequent selected indicator interval for every calculated price level.
- Exhibits potential percentage gains or losses at each tier, indicating the prospective price alteration upon reaching that level.
- Differentiates overpriced (green) and discounted (red) levels using color codes. A neutral price is depicted in yellow.
Anticipated Close Calculation : Offers a projected closing price for the current timeframe, based on a myriad of factors.
This indicator is particularly effective with cryptocurrencies due to their inherent volatility. It's also compatible with stocks and is most efficient with tickers that provide volume data.
Highlight BarHighlight bars in the past. I use this to show the start of moving average calculations - very helpful to anticipate the change in slope of moving averages. You can change color as well as how far back in time to highlight. The defaults are 20, 50 and 200.
I learned of the idea from Brian Shannon - thanks!
Seasonality and Presidential cycleAn incredibly useful indicator that shows seasonality and presidential cycles by indices, stocks and industries. Just type in a ticker and trade according to seasonal patterns
Blue line - seasonality excluding presidential cycles
Green line - seasonality taking into account presidential cycles
*Seasonal patterns over the last 10 years
This indicator uses the request.seed() function.
Requests data from a GitHub repository maintained by our team and returns it as a series.
Pine Seeds is a service to import custom data and access it via TradingView.
Use TradingView as frontend and use a GitHub repository as backend.
github.com
...
Rus: Невероятно полезный индикатор, который показывает сезонность и президентские циклы по индексам, акциям и отраслям. Просто вбейте тикер и торгуйте согласно сезонным паттернам
Синяя линия - сезонность без учета президентских циклов
Зеленая линия - сезонность с учетом президентских циклов
*Сезонные паттерны за последние 10 лет
Machine Learning: Gaussian Process Regression [LuxAlgo]We provide an implementation of the Gaussian Process Regression (GPR), a popular machine-learning method capable of estimating underlying trends in prices as well as forecasting them.
While this implementation is adapted to real-time usage, do remember that forecasting trends in the market is challenging, do not use this tool as a standalone for your trading decisions.
🔶 USAGE
The main goal of our implementation of GPR is to forecast trends. The method is applied to a subset of the most recent prices, with the Training Window determining the size of this subset.
Two user settings controlling the trend estimate are available, Smooth and Sigma . Smooth determines the smoothness of our estimate, with higher values returning smoother results suitable for longer-term trend estimates.
Sigma controls the amplitude of the forecast, with values closer to 0 returning results with a higher amplitude. Do note that due to the calculation of the method, lower values of sigma can return errors with higher values of the training window.
🔹 Updating Mechanisms
The script includes three methods to update a forecast. By default a forecast will not update for new bars (Lock Forecast).
The forecast can be re-estimated once the price reaches the end of the forecasting window when using the "Update Once Reached" method.
Finally "Continuously Update" will update the whole forecast on any new bar.
🔹 Estimating Trends
Gaussian Process Regression can be used to estimate past underlying local trends in the price, allowing for a noise-free interpretation of trends.
This can be useful for performing descriptive analysis, such as highlighting patterns more easily.
🔶 SETTINGS
Training Window: Number of most recent price observations used to fit the model
Forecasting Length: Forecasting horizon, determines how many bars in the future are forecasted.
Smooth: Controls the degree of smoothness of the model fit.
Sigma: Noise variance. Controls the amplitude of the forecast, lower values will make it more sensitive to outliers.
Update: Determines when the forecast is updated, by default the forecast is not updated for new bars.
Intraday Volatility Bands [Honestcowboy]The Intraday Volatility Bands aims to provide a better alternative to ATR in the calculation of targets or reversal points.
How are they different from ATR based bands?
While ATR and other measures of volatility base their calculations on the previous bars on the chart (for example bars 1954 to 1968). The volatility used in these bands measure expected volatility during that time of the day.
Why would you take this approach?
Markets behave different during certain times of the day, also called sessions.
Here are a couple examples.
Asian Session (generally low volatility)
London Session (bigger volatility starts)
New York Session (overlap of New York with London creates huge volatility)
Generally when using bands or channel type indicators intraday they do not account for the upcoming sessions. On London open price will quickly spike through a bollinger band and it will take some time for the bands to adjust to new volatility.
This script will show expected volatility targets at the start of each new bar and will not adjust during the bar. It already knows what price is expected to do at this time of day.
Script also plots arrows when price breaches either the top or bottom of the bands. You can also set alerts for when this occurs. These are non repainting as the script knows the level at start of the bar and does not change.
🔷 CALCULATION
Think of this script like an ATR but instead it uses past days data instead of previous bars data. Charts below should visualise this more clearly:
The scripts measure of volatility is based on a simple high-low.
The script also counts the number of bars that exist in a day on your current timeframe chart. After knowing that number it creates the matrix used in it's calculations and data storage.
See how it works perfectly on a lower timeframe chart below:
Getting this right was the hardest part, check the coding if you are interested in this type of stuff. I commented every step in the coding process.
🔷 SETTINGS
Every setting of the script has a tooltip but I provided a breakdown here:
Some more examples of different charts:
Machine Learning: Trend Lines [YinYangAlgorithms]Trend lines have always been a key indicator that may help predict many different types of price movements. They have been well known to create different types of formations such as: Pennants, Channels, Flags and Wedges. The type of formation they create is based on how the formation was created and the angle it was created. For instance, if there was a strong price increase and then there is a Wedge where both end points meet, this is considered a Bull Pennant. The formations Trend Lines create may be powerful tools that can help predict current Support and Resistance and also Future Momentum changes. However, not all Trend Lines will create formations, and alone they may stand as strong Support and Resistance locations on the Vertical.
The purpose of this Indicator is to apply Machine Learning logic to a Traditional Trend Line Calculation, and therefore allowing a new approach to a modern indicator of high usage. The results of such are quite interesting and goes to show the impacts a simple KNN Machine Learning model can have on Traditional Indicators.
Tutorial:
There are a few different settings within this Indicator. Many will greatly impact the results and if any are changed, lots will need ‘Fine Tuning’. So let's discuss the main toggles that have great effects and what they do before discussing the lengths. Currently in this example above we have the Indicator at its Default Settings. In this example, you can see how the Trend Lines act as key Support and Resistance locations. Due note, Support and Resistance are a relative term, as is their color. What starts off as Support or Resistance may change when the price crosses over / under them.
In the example above we have zoomed in and circled locations that exhibited markers of Support and Resistance along the Trend Lines. These Trend Lines are all created using the Default Settings. As you can see from the example above; just because it is a Green Upwards Trend Line, doesn’t mean it’s a Support Line. Support and Resistance is always shifting on Trend Lines based on the prices location relative to them.
We won’t go through all the Formations Trend Lines make, but the example above, we can see the Trend Lines formed a Downward Channel. Channels are when there are two parallel downwards Trend Lines that are at a relatively similar angle. This means that they won’t ever meet. What may happen when the price is within these channels, is it may bounce between the upper and lower bounds. These Channels may drive the price upwards or downwards, depending on if it is in an Upwards or Downwards Channel.
If you refer to the example above, you’ll notice that the Trend Lines are formed like traditional Trend Lines. They don’t stem from current Highs and Lows but rather Machine Learning Highs and Lows. More often than not, the Machine Learning approach to Trend Lines cause their start point and angle to be quite different than a Traditional Trend Line. Due to this, it may help predict Support and Resistance locations at are more uncommon and therefore can be quite useful.
In the example above we have turned off the toggle in Settings ‘Use Exponential Data Average’. This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN. By Default it is enabled, but as you can see when it is disabled it may create some pretty strong lasting Trend Lines. This is why we advise you ZOOM OUT AS FAR AS YOU CAN. Trend Lines are only displayed when you’ve zoomed out far enough that their Start Point is visible.
As you can see in this example above, there were 3 major Upward Trend Lines created in 2020 that have had a major impact on Support and Resistance Locations within the last year. Lets zoom in and get a closer look.
We have zoomed in for this example above, and circled some of the major Support and Resistance locations that these Upward Trend Lines may have had a major impact on.
Please note, these Machine Learning Trend Lines aren’t a ‘One Size Fits All’ kind of thing. They are completely customizable within the Settings, so that you can get a tailored experience based on what Pair and Time Frame you are trading on.
When any values are changed within the Settings, you’ll likely need to ‘Fine Tune’ the rest of the settings until your desired result is met. By default the modifiable lengths within the Settings are:
Machine Learning Length: 50
KNN Length:5
Fast ML Data Length: 5
Slow ML Data Length: 30
For example, let's toggle ‘Use Exponential Data Averages’ back on and change ‘Fast ML Data Length’ from 5 to 20 and ‘Slow ML Data Length’ from 30 to 50.
As you can in the example above, all of the lines have changed. Although there are still some strong Support Locations created by the Upwards Trend Lines.
We will conclude our Tutorial here. Hopefully you’ve learned how to use Machine Learning Trend Lines and will be able to now see some more unorthodox Support and Resistance locations on the Vertical.
Settings:
Use Machine Learning Sources: If disabled Traditional Trend line sources (High and Low) will be used rather than Rational Quadratics.
Use KNN Distance Sorting: You can disable this if you wish to not have the Machine Learning Data sorted using KNN. If disabled trend line logic will be Traditional.
Use Exponential Data Average: This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN.
Machine Learning Length: How strong is our Machine Learning Memory? Please note, when this value is too high the data is almost 'too' much and can lead to poor results.
K-Nearest Neighbour (KNN) Length: How many K-Nearest Neighbours are allowed with our Distance Clustering? Please note, too high or too low may lead to poor results.
Fast ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 3/5/7 all seem to work well for Fast.
Slow ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 20 - 50 all seem to work well for Slow.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
RVI_HTFThe "RVI_HTF" indicator is a tool designed to assist traders in analyzing market trends using the Relative Vigor Index (RVI) across different timeframes. It enables users to customize various aspects of the indicator's appearance and behavior. By monitoring the RVI on different timeframes, tracking its relationship with the moving average, and paying attention to extreme arrows above the 80 or below the 20 line, traders can anticipate potential reversals, trends, or changes in market momentum.
Above 80 Line: When the RVI moves above the 80 line, it suggests that the market may be overbought. Extreme upward arrows (indicating potential sell signals) can be a sign that a bullish trend might be reaching an exhaustion point. Traders may anticipate a possible trend reversal or pullback.
Below 20 Line: When the RVI dips below the 20 line, it implies that the market might be oversold. Extreme downward arrows (indicating potential buy signals) can be an early signal of a potential bullish reversal. Traders may anticipate an upcoming uptrend or bounce.
Crossing Above Moving Average: When the RVI crosses above its moving average on the selected timeframe, it can serve as an early indication of potential bullish strength in the market. This suggests that buying pressure may be increasing.
Crossing Below Moving Average: Conversely, when the RVI crosses below its moving average, it can signal potential bearish momentum. This indicates that selling pressure may be gaining strength.
Variables:
Timeframe (TF) Selection:
The indicator allows you to select the timeframe for the RVI calculation. You can choose from various options such as 1 minute (1), 5 minutes (5), 15 minutes (15), 30 minutes (30), 60 minutes (60), 240 minutes (240), Daily (D), Weekly (W), Monthly (M), or use "Auto" to automatically select a higher timeframe based on your current chart's timeframe.
Moving Average Type (MA_Type):
Function: Allows users to select the type of moving average used in RVI calculations.
Options: You can select from various moving average types, including:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
SMMA (Smoothed Moving Average, also known as RMA)
WMA (Weighted Moving Average)
VWMA (Volume Weighted Moving Average)
DEMA (Double Exponential Moving Average)
Moving Average Length (MA_Length):
Function: Permits users to set the number of periods for the selected moving average type.
Purpose: Controls the sensitivity of the RVI indicator. Longer lengths provide smoother results, while shorter lengths react more quickly to price changes.
Up Arrow Color (upArrowColor):
Function: Enables users to customize the color of arrows that indicate potential Overbought areas. (Only shown when the TF is same as or lower than the chart TF)
Down Arrow Color (downArrowColor):
Function: Allows users to specify the color of downward-pointing arrows signaling potential Oversold areas. (Only shown when the TF is same as or lower than the chart TF)
RVI Up Color (firstColor):
Function: Defines the color of the RVI line when it indicates a bullish condition on the higher timeframe.
RVI Down Color (secondColor):
Function: Specifies the color of the RVI line when it suggests a bearish condition on the higher timeframe.
RVI-Based Moving Average Up Color (firstColorMA):
Function: Customizes the color of the RVI-based moving average line when it indicates a bullish condition.
RVI-Based Moving Average Down Color (secondColorMA):
Function: Defines the color of the RVI-based moving average line when it suggests a bearish condition.
Double AI Super Trend Trading - Strategy [PresentTrading]█ Introduction and How It is Different
The Double AI Super Trend Trading Strategy is a cutting-edge approach that leverages the power of not one, but two AI algorithms, in tandem with the SuperTrend technical indicator. The strategy aims to provide traders with enhanced precision in market entry and exit points. It is designed to adapt to market conditions dynamically, offering the flexibility to trade in both bullish and bearish markets.
*The KNN part is mainly referred from @Zeiierman.
BTCUSD 8hr performance
ETHUSD 8hr performance
█ Strategy, How It Works: Detailed Explanation
1. SuperTrend Calculation
The SuperTrend is a popular indicator that captures market trends through a combination of the Volume-Weighted Moving Average (VWMA) and the Average True Range (ATR). This strategy utilizes two sets of SuperTrend calculations with varying lengths and factors to capture both short-term and long-term market trends.
2. KNN Algorithm
The strategy employs k-Nearest Neighbors (KNN) algorithms, which are supervised machine learning models. Two sets of KNN algorithms are used, each focused on different lengths of historical data and number of neighbors. The KNN algorithms classify the current SuperTrend data point as bullish or bearish based on the weighted sum of the labels of the k closest historical data points.
3. Signal Generation
Based on the KNN classifications and the SuperTrend indicator, the strategy generates signals for the start of a new trend and the continuation of an existing trend.
4. Trading Logic
The strategy uses these signals to enter long or short positions. It also incorporates dynamic trailing stops for exit conditions.
Local picture
█ Trade Direction
The strategy allows traders to specify their trading direction: long, short, or both. This enables the strategy to be versatile and adapt to various market conditions.
█ Usage
ToolTips: Comprehensive tooltips are provided for each parameter to guide the user through the customization process.
Inputs: Traders can customize numerous parameters including the number of neighbors in KNN, ATR multiplier, and types of moving averages.
Plotting: The strategy also provides visual cues on the chart to indicate bullish or bearish trends.
Order Execution: Based on the generated signals, the strategy will execute buy or sell orders automatically.
█ Default Settings
The default settings are configured to offer a balanced approach suitable for most scenarios:
Initial Capital: $10,000
Default Quantity Type: 10% of equity
Commission: 0.1%
Slippage: 1
Currency: USD
These settings can be modified to suit various trading styles and asset classes.
Recession Indicator (Unemployment Rate)Unemployment rate
percentage of unemployed individuals in an economy among individuals currently in the labour force. It is calcuated as Unemployed IndividualsTotal Labour Force × 100 where unemployed individuals are those who are currently not working but are actively seeking work.
The unemployment rate is one of the primary economic indicators used to measure the health of an economy. It tends to fluctuate with the business cycle, increasing during recessions and decreasing during expansions. It is among the indicators most commonly watched by policy makers, investors, and the general public.
Policy makers and central banks consider how much the unemployment rate has increased during a particular recession to gauge the recession’s impact on the economy and to decide how to tailor fiscal and monetary policies to mitigate its adverse effects. In addition, central banks carefully try to predict the future trend of the unemployment rate to devise long-term strategies to lower it.
This indicator is a representation of yearly rate of change of Unemployment rate. Historically (not always) when ROC(Yearly) of Unemployment rate crossover zero line was a signal of recession or economic contraction.
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.
Machine Learning: MFI Heat Map [YinYangAlgorithms]Overview:
MFI Heat Maps are a visually appealing way to display the values of 29 different MFIs at the same time while being able to make sense of it. Each plot within the Indicator represents a different MFI value. The higher you get up, the longer the length that was used for this MFI. This Indicator also features the use of Machine Learning to help balance the MFI levels. It doesn’t solely rely upon Machine Learning but instead incorporates a growing length MFI averaged with the Machine Learning MFI at any given index.
For instance, say we are calculating the 10th plot from the bottom, the MFI would be an average of:
MFI(source, 11)
Machine Learning MFI at Index of 10
We do it this way as they both help smooth each other out without relying solely on just one calculation method.
Due to plot limitations, you are capped at 28 Plot Amounts within this indicator, but that is still quite a bit of information you can glean from a Heat Map.
The Machine Learning used in this indicator is of the K-Nearest Neighbor (KNN). It uses a Fast and Slow MFI calculation then sorts through them over Machine Learning Length and calculates the differences between them. It then slices off KNN length to create our Max/Min Distances allotted. It adds the average between Fast and Slow MFIs to a Viable Distances array if their distances are within the KNN Min/Max distance. It then averages all distances in the Viable Distances array and returns the result.
The result of the KNN Function is saved to another ML Data array whose length is that of Plot Amount (Heat Map Size). This way each Index of the ML Data array can be indexed according to the Heat Map Size.
The Average of the ML Data array is the MFI line (white) that you’ll see plotted on the Indicator. There is also the SMA of the MFI Average (orange) which is likewise plotted. These plots allow you to visualize where the ML MFI is sitting and can potentially be useful for seeing when the MFI Average and SMA cross over and under each other.
We’ve heard many people talk highly of RSI, but sadly not too many even refer to MFI. MFI oftentimes may be overlooked, especially with new traders who may not even know what it is. Essentially MFI is an RSI but it also incorporates Volume into its calculations, which in our opinion leads to a more accurate reading; afterall, what is price movement without Volume.
Tutorial:
You may be thinking, this Indicator looks appealing to the eye, but how do I benefit from it trading wise?
Before we get into our visual examples, let's talk briefly about what makes Heat Maps in general a useful tool for trading. Heat Maps give us the ability to visualize and understand lots of data while removing the clutter. We can understand the data of 29 different MFIs without having to look at and decipher 29 different MFI plots. When you overlay too many MFI lines on top of each other, they can be very difficult to read and oftentimes end up actually hindering your Technical Analysis. For this reason, we have a simple solution to this problem; Heat Maps. This MFI Heat Map allows you to easily know (in a relative %) what the MFI level is for varying lengths. For Instance, the First (bottom) plot indexes an MFI of (K(0) (loop of Plot Amount) + Smoothing Length (default 1)) = 1. Since this is indexing (usually) a very low length, it will change much quicker. Whereas the Last (top) plot indexes an MFI of (K(27) (loop of Plot Amount) + Smoothing Length (default 1)) = 28. This is indexing a much higher length of MFI which results in the MFI the higher you go up in the Heat Map to move much slower.
Heat Maps give us the ability to see changes happening over multiple MFIs at the same time, which can be very useful for seeing shifts in MFI / Momentum. Remember, MFI incorporates Volume, so even if the price goes up a lot, if there was low volume, the MFI won’t move as much as an RSI would. However, likewise, if there is high volume but low price movement, the MFI will move slightly more than the RSI.
Heat Maps change color based on their MFI level. If the MFI is >= 90 it is HOT (red), if the MFI <= 9 it is COLD (teal, think of ICE). Green represents an MFI of 50-59 and Dark Blue represents an MFI of 40-49. Green and Dark blue are the most common colors as all the others are more ‘Extreme’ MFI levels.
Okay, time to get to the Examples :
Since there is so much going on in Heat Maps, we’ve decided to focus this tutorial to this specific area and talk about individual locations before talking about it as a whole.
If you refer to the example above where there are 2 white circles; these white circles are highlighting a key location you’ll be wanting to identify within your Heat Maps, many things are happening here:
The MFI crossed over the SMA (bullish).
The Heat Map started changing from mid/dark Blue (30-50 MFI) to Green (50-59 MFI) around the midline (the 50% dashed like).
The Lower levels of the Heat Map are turning Yellow/Orange/Red (60-100 MFI).
The Upper Levels of the Heat Map are still Light Blue - Green (10-50 MFI).
The 4 Key points above, all point towards potential Bullish Momentum changes. You’re likely wondering, but why? Let's discuss about each one in more specific detail:
1. The MFI crossed over the SMA (bullish): What this tells us is that the current MFI Average is now greater than its average over the last (default) 16 bars. This means there's been a large amount of Money Flow (Price and Volume) recently (subjectively based on the last (default) 16 average). This is one of the leading Bullish / Bearish signals you will see within this Indicator. You can enable Signals within the Settings and/or even add Alerts for when these crossings occur.
2. The Heat Map started changing from mid/dark Blue (30-50 MFI) to Green (50-59 MFI) around the midline (the 50% dashed like): This shows us that the index’s in the mid (if using all 28 heat map plots it would be at 14) has already received some of this momentum change. If you look at the second white circle (right), you’ll also notice the higher MFI plot indexes are also green. This is because since their length is long they still have some momentum and strength from the first white circle (left). Just because the first white circle failed in its bullish push, doesn’t mean it didn’t achieve momentum that would later on help to push the price up.
3. The Lower levels of the Heat Map are turning Yellow/Orange/Red (60-100 MFI): It occurred somewhat in the left white circle, but mainly in the right white circle. This shows us the MFI is very high on the lower lengths, this may lead to the current, middle and higher length MFIs following suit soon. Remember it has to work its way up, the higher levels can’t go red unless the lower levels go red first and the higher levels can also lag quite a bit behind and take awhile to catch up, this is normal, expected and meant to happen. Vice versa is also true with getting higher levels to go cold (light teal (think of ICE)).
4. The Upper Levels of the Heat Map are still Light Blue - Green (10-50 MFI): You might think at first that this is a bad thing, but it's not! Remember you want to be Fearful when others are Greedy and Greedy when others are Fearful! You don’t want to buy when the higher levels have a high MFI, you want to buy when you see the momentum pushing up in the lower MFI levels (getting yellow/orange/red in the low levels) while it is still Cold in the higher levels (BLUE OR GREEN, nothing higher than green as it is already slightly too high). There will be many times that it is Yellow or possibly Orange in the high levels and the bullish push still happens, but this is much more risky! The key to trading is to minimize risks while maximizing potential.
Hopefully now you’re getting an idea of how to spot potential bullish momentum changes, but what about bearish momentum changes? Technically they are the exact opposite, so we don’t need to go into as much detail, but lets still take a look at a few examples:
In the example above we marked the 3 times where it was displaying overly bullish characteristics. We marked the bullish momentum occurring with arrows. If you look closely at the start of the arrow to where it finishes, you’ll notice how the heat (HOT)(RED) works its way up from the lower levels to the higher levels. We then see the MFI to SMA cross under. In all 3 of these examples the heat made it all the way to the top of the chart. These are all very bearish signals that represent a bearish momentum movement that may occur soon.
Also, please note, the level the MFI is at DOES matter! That line isn’t there simply for you to see when there are crosses over and under. The MFI is considered to be Overbought when it is greater than 70 (the upper white dashed line, it is just formatted to be on a different scale cause there are 28 plots, but it represents 70). The MFI is considered to be Oversold when it is less than 30 (the lower white dashed line).
If we look to the left a little here where a big drop in price occurred shortly after our MFI and SMA crossed, would we have been able to identify it using the Heat Maps? Likely, No. There was some color change in the lower levels a few bars prior that went yellow/orange/red but before this cross happened they all went back to Dark Blue. In the middle section when the cross happened it was only Green and Yellow and in the upper section we are Blue. This would be a very risky trade to go on as the only real Bearish Indication was the MFI to SMA cross under. Remember, you want to reduce risk, you don’t want to simply trade on everytime the MFI and SMA cross each other or you’ll be getting yourself into many risky trades based on false signals.
Based on what you’ve learned above, can you see the signs that are indicating where this white circle may have potential for a bullish momentum change?
Now that we are more zoomed in, you may also be noticing there are colors to the price bars. This can be disabled in the settings, but just so you know what they mean, let’s zoom in a little more and talk about it.
We’ve condensed the Indicator a bit so you can see the bars better here. The colors that are displayed on these bars are the Heat Map value for your MFI (the white line in the Indicator). This way you can better see when the Price is Hot and Cold. As you may see while looking, the colors generally go from cold to hot when bullish momentum is happening and hot to cold when bearish momentum is happening. We don’t recommend solely looking at the bars as indicators to MFI momentum change, as seeing the Heat Map will give you much more data; however it can be nice to see the Heat Map projected on the bars rather than trying to eyeball it yourself or hover over each bar specifically to see their levels.
We will conclude our Tutorial here. Hopefully this has given you some insight to how useful Heat Maps can be and why it works well with a Machine Learning (KNN) Model applied to the MFI.
PLEASE NOTE: You can adjust the line width for the Heat Map within the settings. If you condense the Indicator a lot or have a small screen, likely use a length of 1-2. If you have it stretched out or a large screen, a length of 2-3 will work nice. You just don’t want to have the lines overlapping or it defeats the purpose of a Heat Map. Also, the bigger the linewidth, generally you’ll want to increase the Transparency within the Settings also as it can get quite bright and hurt your eyes over time.
Settings:
MFI:
Show MFI and SMA Crossing Signals: MFI and SMA Crossing is one of the leading Bullish and Bearish Signals in this Indicator. You can also add alerts for these signals.
Plot Amount: How many plots are used in this Heat Map. (2 - 28).
Source: The Source to use in all MFI calculations.
Smooth Initial MFI Length: How much to smooth the Fast and Slow MFI calculation by. 1 = No smoothing.
MFI SMA Length: What length we smooth the MFI Average over to get our MFI SMA.
Machine Learning:
Average MFI data by adding a lookback to the Source: While populating our Heat Map with the MFI's, should use use the Source each MFI Length increase or should we also lookback a Source each MFI Length Increase.
KNN Distance Requirement: To be a valid KNN, it needs to abide by a Distance calculation. Generally only Max is used, but you can change it if it suits your trading style better.
Machine Learning Length: How much ML data should we store? The longer the length generally the smoother the result; which may not be as accurate for something like a Heat Map, so keeping this relatively low may lead to more accurate results.
KNN Length: How many KNN are used in the slice to calculate max/min distance allowed.
Fast Length: Fast MFI length used in KNN to calculate distances by comparing its distance with the Slow MFI Length.
Slow Length: Slow MFI length used in KNN to calculate distances by comparing its distance with the Fast MFI Length.
Smoothing Length: When populating our Heat Map, at what length do we start our MFI calculations with (A Higher value with result in a slower and more smoothed MFI / Heat Map).
Colors:
Change Bar Color: Change bar colors to MFI Avg Color.
Heat Map Transparency: If there isn't any transparency it can be a little hard on the eyes. The Greater the Line Width, generally the more transparency you'll want for your eyes.
Line Width: Set how wide the Heat Map lines are
MFI 90-100 Color: Color when the MFI is between these levels.
MFI 80-89 Color: Color when the MFI is between these levels.
MFI 70-79 Color: Color when the MFI is between these levels.
MFI 60-69 Color: Color when the MFI is between these levels.
MFI 50-59 Color: Color when the MFI is between these levels.
MFI 40-49 Color: Color when the MFI is between these levels.
MFI 30-39 Color: Color when the MFI is between these levels.
MFI 20-29 Color: Color when the MFI is between these levels.
MFI 10-19 Color: Color when the MFI is between these levels.
MFI 0-100 Color: Color when the MFI is between these levels.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
IU Break of any session StrategyHow this script works:
1. This script is an intraday trading strategy script which buy and sell on the bases of user-defined intraday session range breakout and gives alert(if the alert is set) message too when the new position is open.
2. It calculate the session as per the user inputs or user defined custom session.
3. The script stores the highest and lowest value of the whole session.
4. It take a long position on the first break and close above the highest value.
5. It take a short position on the break and close below the lowest value.
6. The script takes one position in one day.
7. The stop loss for this script is the previous low(if long) or high(if short).
8. Take profit is 1:2 and it's adjustable.
9. This script work on every kind of market.
How The Useful For The User :
1. User can backtest any session range breakout he wants to trade.
2. User can get alert when the new position is open.
3. User can change the Risk to Reward in order to find the best Risk to Reward.
4. User can see the highest and lowest value of the session with respect to analyzing his trading objective.
5. This strategy script highlights which session range breakout performs best and which performs worst.