Hobbiecode - RSI + Close previous dayThis is a simple strategy that is working well on SPY but also well performing on Mini Futures SP500. The strategy is composed by the followin rules:
1. If RSI(2) is less than 15, then enter at the close.
2. Exit on close if today’s close is higher than yesterday’s high.
If you backtest it on Mini Futures SP500 you will be able to track data from 1993. It is important to select D1 as timeframe.
Please share any comment or idea below.
Have a good trading,
Ramón.
Cerca negli script per "algo"
Hobbiecode - SP500 IBS + HigherThis is a simple strategy that is working well on SPY but also well performing on Mini Futures SP500. The strategy is composed by the followin rules:
1. Today is Monday.
2. The close must be lower than the close on Friday.
3. The IBS must be below 0.5.
4. If 1-3 are true, then enter at the close.
5. Sell 5 trading days later (at the close).
If you backtest it on Mini Futures SP500 you will be able to track data from 1993. It is important to select D1 as timeframe.
Please share any comment or idea below.
Have a good trading,
Ramón.
Pure Morning 2.0 - Candlestick Pattern Doji StrategyThe new "Pure Morning 2.0 - Candlestick Pattern Doji Strategy" is a trend-following, intraday cryptocurrency trading system authored by devil_machine.
The system identifies Doji and Morning Doji Star candlestick formations above the EMA60 as entry points for long trades.
For best results we recommend to use on 15-minute, 30-minute, or 1-hour timeframes, and are ideal for high-volatility markets.
The strategy also utilizes a profit target or trailing stop for exits, with stop loss set at the lowest low of the last 100 candles. The strategy's configuration details, such as Doji tolerance, and exit configurations are adjustable.
In this new version 2.0, we've incorporated a new selectable filter. Since the stop loss is set at the lowest low, this filter ensures that this value isn't too far from the entry price, thereby optimizing the Risk-Reward ratio.
In the specific case of ALPINE, a 9% Take-Profit and and Stop-Loss at Lowest Low of the last 100 candles were set, with an activated trailing-stop percentage, Max Loss Filter is not active.
Name : Pure Morning 2.0 - Candlestick Pattern Doji Strategy
Author : @devil_machine
Category : Trend Follower based on candlestick patterns.
Operating mode : Spot or Futures (only long).
Trades duration : Intraday
Timeframe : 15m, 30m, 1H
Market : Crypto
Suggested usage : Short-term trading, when the market is in trend and it is showing high volatility .
Entry : When a Doji or Morning Doji Star formation occurs above the EMA60.
Exit : Profit target or Trailing stop, Stop loss on the lowest low of the last 100 candles.
Configuration :
- Doji Settings (tolerances) for Entry Condition
- Max Loss Filter (Lowest Low filter)
- Exit Long configuration
- Trailing stop
Backtesting :
⁃ Exchange: BINANCE
⁃ Pair: ALPINEUSDT
⁃ Timeframe: 30m
⁃ Fee: 0.075%
⁃ Slippage: 1
- Initial Capital: 10000 USDT
- Position sizing: 10% of Equity
- Start: 2022-02-28 (Out Of Sample from 2022-12-23)
- Bar magnifier: on
Disclaimer : Risk Management is crucial, so adjust stop loss to your comfort level. A tight stop loss can help minimise potential losses. Use at your own risk.
How you or we can improve? Source code is open so share your ideas!
Leave a comment and smash the boost button!
Thanks for your attention, happy to support the TradingView community.
Directional Volume EStimate from Price Action (RedK D_VESPA)The "Directional Volume EStimate from Price Action (RedK D_VESPA)" is another weapon for the VPA (Volume Price Analysis) enthusiasts and traders who like to include volume-based insights & signals to their trading. The basic concept is to estimate the sell and buy split of the traded volume by extrapolating the price action represented by the shape of the associated price bar. We then create and plot an average of these "estimated buy & sell volumes" - the estimated average Net Volume is the balance between these 2 averages.
D_VESPA uses clear visualizations to represent the outcomes in a less distracting and more actionable way.
How does D_VESPA work?
-------------------------------------
The key assumption is that when price moves up, this is caused by "buy" volume (or increasing demand), and when the price moves down, this is due to "selling" volume (or increasing supply). Important to note that we are making our Buy/sell volume estimates here based on the shape of the price bar, and not looking into lower time frame volume data - This is a different approach and is still aligned to the key concepts of VPA.
Originally this work started as an improvement to my Supply/Demand Volume Viewer (V.Viewer) , I ended up re-writing the whole thing after some more research and work on VPA, to improve the estimation, visualization and usability / tradability.
Think of D_VESPA as the "Pro" version of V.Viewer -- and please go back and review the details of V.Viewer as the root concepts are the same so I won't repeat them here (as it comes to exploring Balance Zone and finding Price Convergence/Divergence)
Main Features of D_VESPA
--------------------------------------
- Update Supply/Demand calculation to include 2-bar gaps (improved algo)
- Add multiple options for the moving average (MA type) for the calculation - my preference is to use WMA
- Add option to show Net Volume as 3-color bars
- Visual simplification and improvements to be less distracting & more actionable
- added options to display/hide main visuals while maintaining the status line consistency (Avg Supply, Avg Demand, Avg Net)
- add alerts for NetVol moving into Buy (crosses 0 up) or Sell (crosses 0 down) modes - or swing from one mode to the other
(there are actually 2 sets of alerts, one set for the main NetVol plot, and the other for the secondary TF NetVol - give user more options on how to utilize D_VESPA)
Quick techie piece, how does the estimated buy/sell volume algo work ?
------------------------------------------------------------------------------------------
* per our assumption, buy volume is associated with price up-moves, sell volume is associated with price down-moves
* so each of the bulls and bears will get the equivalent of the top & bottom wicks,
* for up bars, bulls get the value of the "body", else the bears get the "body"
* open gaps are allocated to bulls or bears depending on the gap direction
The below sketch explains how D_VESPA estimates the Buy/Sell Volume split based on the bar shape (including gap) - the example shows a bullish bar with an opening gap up - but the concept is the same for a down-bar or a down-gap.
I kept both the "Volume Weighted" and "2-bar Gap Impact" as options in the indicator settings - these 2 options should be always kept selected. They are there for those who would like to experiment with the difference these changes have on the buy/sell estimation. The indicator will handle cases where there is no volume data for the selected symbol, and in that case, it will simply reflect Average Estimated Bull/Bear ratio of the price bar
The Secondary TF Est Average Net Volume:
---------------------------------------------------------
I added the ability to plot the Estimate Average Net Volume for a secondary timeframe - options 1W, 1D, 1H, or Same as Chart.
- this feature provides traders the confidence to trade the lower timeframes in the same direction as the prevailing "market mode"
- this also adds more MTF support beyond the existing TradingView's built-in MTF support capability - experiment with various settings between exposing the indicator's secondary TF plot, and changing the TF option in the indicator settings.
Note on the secondary TF NetVol plot:
- the secondary TF needs to be set to same as or higher TF than the chart's TF - if not, a warning sign would show and the plot will not be enabled. for example, a day trader may set the secondary TF to 1Hr or 1Day, while looking at 5min or 15min chart. A swing/trend trader who frequently uses the daily chart may set the secondary TF to weekly, and so on..
- the secondary TF NetVol plot is hidden by default and needs to be exposed thru the indicator settings.
the below chart shows D_VESPA on a the same (daily) chart, but with secondary TF plot for the weekly TF enabled
Final Thoughts
-------------------
* RedK D_VESPA is a volume indicator, that estimates buy/sell and net volume averages based on the price action reflected by the shape of the price bars - this can provide more insight on volume compared to the classic volume/VolAverage indicator and assist traders in exploring the market mode (buyers/sellers - bullish/bearish) and align trades to it.
* Because D_VESPA is a volume indicator, it can't be used alone to generate a trading signal - and needs to be combined with other indicators that analysis price value (range), momentum and trend. I recommend to at least combine D_VESPA with a variant of MACD and RSI to get a full view of the price action relative to the prevailing market and the broader trend.
* I found it very useful to take note and "read" how the Est Buy vs Est Sell lines move .. they sort of "tell a story" - experiment with this on your various chart and note the levels of estimate avg demand vs estimate avg supply that this indicator exposes for some very valuable insight about how the chart action is progressing. Please feel free to share feedback below.
Benner-Fibonacci Reversal Points [CC]This is an original script based on a very old idea called the Benner Theory from the Civil War times. Benner discovered a pattern in pig iron prices (no clue what those are), and this turned out to be a parallel idea to indicators based on Fibonacci numbers. Because a year is 365 days (nearly 377, which is a Fibonacci number), made up of 52 weeks (nearly 55, which is another Fibonacci number), or 12 months (nearly 13, which is another Fibonacci number), Benner theorized that he could find both past and future turning points in the market by using a pattern he found. He discovered that peaks in prices seemed to follow a pattern of 8-9-10, meaning that after a recent peak, it would be 8 bars until the next peak, 9 bars until after that peak for the next, and 10 bars until the following peak. For past peaks, he would just need to reverse this pattern, and so the previous peak would be 10 bars before the most current peak, 9 bars before that peak, and 8 bars before the previous one, and these patterns seemed to repeat. For troughs, he found a pattern of 16,18,20 which follows the same logic, and this idea also seemed to work on long-term peaks and troughs as well.
This is my version of the Benner theory and the major difference between my version and his is that he would manually select a year or date and either work backwards or forwards from that point. I chose to go with an adaptive version that will automatically detect those points and plot those past and future points. I have included several options such as allowing the algorithm to be calculated in reverse which seems to work well for Crypto for some reason. I also have both short and long term options to only show one or both if you choose and of course the option to enable repainting or leave it disabled.
Big thanks to @HeWhoMustNotBeNamed and @RicardoSantos for helping me fix some bugs in my code and for @kerpiciwuasile for suggesting this idea in the first place.
Advanced Trend Detection StrategyThe Advanced Trend Detection Strategy is a sophisticated trading algorithm based on the indicator "Percent Levels From Previous Close".
This strategy is based on calculating the Pearson's correlation coefficient of logarithmic-scale linear regression channels across a range of lengths from 50 to 1000. It then selects the highest value to determine the length for the channel used in the strategy, as well as for the computation of the Simple Moving Average (SMA) that is incorporated into the strategy.
In this methodology, a script is applied to an equity in which multiple length inputs are taken into consideration. For each of these lengths, the slope, average, and intercept are calculated using logarithmic values. Deviation, the Pearson's correlation coefficient, and upper and lower deviations are also computed for each length.
The strategy then selects the length with the highest Pearson's correlation coefficient. This selected length is used in the channel of the strategy and also for the calculation of the SMA. The chosen length is ultimately the one that best fits the logarithmic regression line, as indicated by the highest Pearson's correlation coefficient.
In short, this strategy leverages the power of Pearson's correlation coefficient in a logarithmic scale linear regression framework to identify optimal trend channels across a broad range of lengths, assisting traders in making more informed decisions.
Z-Score(Slope(OBV(LBC)))Summary : Market price is simply a dance of liquidity to the specific market.
tl;dr: "Cash come-in, market moon; Cash go-out, market doom"
In Simple Language : Large changes in the money flow to an asset often mark local price extremia.
Academic paper:
Title: Z-Score(Slope(OBV)): An Efficient Indicator for Identifying Local Extremes in Asset Prices
Abstract: This paper presents a novel trading indicator, Z-Score(Slope(OBV)), that aims to predict local extremes in asset prices by analyzing the patterns of money flow. The indicator is constructed using the Z-score of the slope of the On Balance Volume (OBV).
Hypothesis: The price levels at which the money flows into and out of an asset often mark local extremes. This notion underpins our exploration of the Z-Score(Slope(OBV)) indicator's potential in identifying these critical points.
1. On Balance Volume (OBV): The OBV is a momentum indicator that leverages the volume flow to forecast potential changes in asset prices. It operates on the premise that changes in volume often presage shifts in price. The OBV algorithm adds a period's volume to the cumulative total when the closing price is up and subtracts it when the closing price is down. Therefore, an ascending OBV suggests positive volume pressure, potentially heralding higher prices, while a declining OBV signifies negative volume pressure, possibly indicating lower prices.
2. Slope: In this context, the slope represents the rate of change of the OBV. It is a measure of the rise-over-run for a linear regression line through the OBV data points. By evaluating the slope of the OBV, we can extract valuable insights into the momentum of the volume. A positive slope indicates increasing volume momentum, suggesting growing interest in the asset, while a negative slope implies declining volume momentum, potentially reflecting dwindling interest.
3. Z-Score: The Z-score is a statistical measure that delineates a data point's relationship to the mean of a group of values, expressed in terms of standard deviations from the mean. For instance, a Z-score of 0 reveals that the data point's score aligns with the mean score. Positive Z-scores indicate values higher than the mean, and negative Z-scores represent values lower than the mean. Applying the Z-score to the slope of the OBV allows us to comprehend the degree of deviation of the current OBV slope from its historical mean.
A Z-score of 1 suggests that the OBV's slope is one standard deviation from the mean, which implies that the slope is within the range of values where approximately 68% (not 67%) of all values lie.
A Z-score of 2 implies that the slope is two standard deviations from the mean, thus within the range where roughly 95% of all values lie.
A Z-score of 3 indicates that the slope is three standard deviations from the mean, putting it within the range where about 99.7% of all values lie.
Z-scores of 4 and 5 and beyond are increasingly rare and represent extreme values.
4. The Z-Score(Slope(OBV)) Indicator and Line Break Chart Synergy: The Z-Score(Slope(OBV)) indicator's efficiency is further amplified when visualized using a Line Break chart. This chart type disregards time, concentrating solely on price changes, thus providing a clear visualization of market trends. When combined with the Line Break chart, the Z-Score(Slope(OBV(LBC))) indicator can help traders identify trend shifts more accurately and promptly, reinforcing the hypothesis that price levels where money flows into and out of an asset often mark local extremes.
In summary, the Z-Score(Slope(OBV)) indicator, combining volume, momentum, and statistical analysis, provides a robust tool for traders to predict local extremes in asset prices.
Regarding Implementation:
- This is implemented using Pinescript V5
- Uses inbuilt ta module
- Very effective and simple and efficient computation in 30 lines of code
Stochastic Chebyshev Smoothed With Zero Lag SmoothingFast and Smooth Stochastic Oscillator with Zero Lag
Introduction
In this post, we will discuss a custom implementation of a Stochastic Oscillator that not only smooths the signal but also does so without introducing any noticeable lag. This is a remarkable achievement, as it allows for a fast Stochastic Oscillator that is less prone to false signals without being slow and sluggish.
We will go through the code step by step, explaining the various functions and the overall structure of the code.
First, let's start with a brief overview of the Stochastic Oscillator and the problem it addresses.
Background
The Stochastic Oscillator is a momentum indicator used in technical analysis to determine potential overbought or oversold conditions in an asset's price. It compares the closing price of an asset to its price range over a specified period. However, the Stochastic Oscillator is susceptible to false signals due to its sensitivity to price movements. This is where our custom implementation comes in, offering a smoother signal without noticeable lag, thus reducing the number of false signals.
Despite its popularity and widespread use in technical analysis, the Stochastic Oscillator has its share of drawbacks. While it is a price scaler that allows for easier comparisons across different assets and timeframes, it is also known for generating false signals, which can lead to poor trading decisions. In this section, we will delve deeper into the limitations of the Stochastic Oscillator and discuss the challenges associated with smoothing to mitigate its drawbacks.
Limitations of the Stochastic Oscillator
False Signals: The primary issue with the Stochastic Oscillator is its tendency to produce false signals. Since it is a momentum indicator, it reacts to short-term price movements, which can lead to frequent overbought and oversold signals that do not necessarily indicate a trend reversal. This can result in traders entering or exiting positions prematurely, incurring losses or missing out on potential gains.
Sensitivity to Market Noise: The Stochastic Oscillator is highly sensitive to market noise, which can create erratic signals in volatile markets. This sensitivity can make it difficult for traders to discern between genuine trend reversals and temporary fluctuations.
Lack of Predictive Power: Although the Stochastic Oscillator can help identify potential overbought and oversold conditions, it does not provide any information about the future direction or strength of a trend. As a result, it is often used in conjunction with other technical analysis tools to improve its predictive power.
Challenges of Smoothing the Stochastic Oscillator
To address the limitations of the Stochastic Oscillator, many traders attempt to smooth the indicator by applying various techniques. However, these approaches are not without their own set of challenges:
Trade-off between Smoothing and Responsiveness: The process of smoothing the Stochastic Oscillator inherently involves reducing its sensitivity to price movements. While this can help eliminate false signals, it can also result in a less responsive indicator, which may not react quickly enough to genuine trend reversals. This trade-off can make it challenging to find the optimal balance between smoothing and responsiveness.
Increased Complexity: Smoothing techniques often involve the use of additional mathematical functions and algorithms, which can increase the complexity of the indicator. This can make it more difficult for traders to understand and interpret the signals generated by the smoothed Stochastic Oscillator.
Lagging Signals: Some smoothing methods, such as moving averages, can introduce a time lag into the Stochastic Oscillator's signals. This can result in late entry or exit points, potentially reducing the profitability of a trading strategy based on the smoothed indicator.
Overfitting: In an attempt to eliminate false signals, traders may over-optimize their smoothing parameters, resulting in a Stochastic Oscillator that is overfitted to historical data. This can lead to poor performance in real-time trading, as the overfitted indicator may not accurately reflect the dynamics of the current market.
In our custom implementation of the Stochastic Oscillator, we used a combination of Chebyshev Type I Moving Average and zero-lag Gaussian-weighted moving average filters to address the indicator's limitations while preserving its responsiveness. In this section, we will discuss the reasons behind selecting these specific filters and the advantages of using the Chebyshev filter for our purpose.
Filter Selection
Chebyshev Type I Moving Average: The Chebyshev filter was chosen for its ability to provide a smoother signal without sacrificing much responsiveness. This filter is designed to minimize the maximum error between the original and the filtered signal within a specific frequency range, effectively reducing noise while preserving the overall shape of the signal. The Chebyshev Type I Moving Average achieves this by allowing a specified amount of ripple in the passband, resulting in a more aggressive filter roll-off and better noise reduction compared to other filters, such as the Butterworth filter.
Zero-lag Gaussian-weighted Moving Average: To further improve the Stochastic Oscillator's performance without introducing noticeable lag, we used the zero-lag Gaussian-weighted moving average (GWMA) filter. This filter combines the benefits of a Gaussian-weighted moving average, which prioritizes recent data points by assigning them higher weights, with a zero-lag approach that minimizes the time delay in the filtered signal. The result is a smoother signal that is less prone to false signals and is more responsive than traditional moving average filters.
Advantages of the Chebyshev Filter
Effective Noise Reduction: The primary advantage of the Chebyshev filter is its ability to effectively reduce noise in the Stochastic Oscillator signal. By minimizing the maximum error within a specified frequency range, the Chebyshev filter suppresses short-term fluctuations that can lead to false signals while preserving the overall trend.
Customizable Ripple Factor: The Chebyshev Type I Moving Average allows for a customizable ripple factor, enabling traders to fine-tune the filter's aggressiveness in reducing noise. This flexibility allows for better adaptability to different market conditions and trading styles.
Responsiveness: Despite its effective noise reduction, the Chebyshev filter remains relatively responsive compared to other smoothing filters. This responsiveness allows for more accurate detection of genuine trend reversals, making it a suitable choice for our custom Stochastic Oscillator implementation.
Compatibility with Zero-lag Techniques: The Chebyshev filter can be effectively combined with zero-lag techniques, such as the Gaussian-weighted moving average filter used in our custom implementation. This combination results in a Stochastic Oscillator that is both smooth and responsive, with minimal lag.
Code Overview
The code begins with defining custom mathematical functions for hyperbolic sine, cosine, and their inverse functions. These functions will be used later in the code for smoothing purposes.
Next, the gaussian_weight function is defined, which calculates the Gaussian weight for a given 'k' and 'smooth_per'. The zero_lag_gwma function calculates the zero-lag moving average with Gaussian weights. This function is used to create a Gaussian-weighted moving average with minimal lag.
The chebyshevI function is an implementation of the Chebyshev Type I Moving Average, which is used for smoothing the Stochastic Oscillator. This function takes the source value (src), length of the moving average (len), and the ripple factor (ripple) as input parameters.
The main part of the code starts by defining input parameters for K and D smoothing and ripple values. The Stochastic Oscillator is calculated using the ta.stoch function with Chebyshev smoothed inputs for close, high, and low. The result is further smoothed using the zero-lag Gaussian-weighted moving average function (zero_lag_gwma).
Finally, the lag variable is calculated using the Chebyshev Type I Moving Average for the Stochastic Oscillator. The Stochastic Oscillator and the lag variable are plotted on the chart, along with upper and lower bands at 80 and 20 levels, respectively. A fill is added between the upper and lower bands for better visualization.
Conclusion
The custom Stochastic Oscillator presented in this blog post combines the Chebyshev Type I Moving Average and zero-lag Gaussian-weighted moving average filters to provide a smooth and responsive signal without introducing noticeable lag. This innovative implementation results in a fast Stochastic Oscillator that is less prone to false signals, making it a valuable tool for technical analysts and traders alike.
However, it is crucial to recognize that the Stochastic Oscillator, despite being a price scaler, has its limitations, primarily due to its propensity for generating false signals. While smoothing techniques, like the ones used in our custom implementation, can help mitigate these issues, they often introduce new challenges, such as reduced responsiveness, increased complexity, lagging signals, and the risk of overfitting.
The selection of the Chebyshev Type I Moving Average and zero-lag Gaussian-weighted moving average filters was driven by their combined ability to provide a smooth and responsive signal while minimizing false signals. The advantages of the Chebyshev filter, such as effective noise reduction, customizable ripple factor, and responsiveness, make it an excellent fit for addressing the limitations of the Stochastic Oscillator.
When using the Stochastic Oscillator, traders should be aware of these limitations and challenges, and consider incorporating other technical analysis tools and techniques to supplement the indicator's signals. This can help improve the overall accuracy and effectiveness of their trading strategies, reducing the risk of losses due to false signals and other limitations associated with the Stochastic Oscillator.
Feel free to use, modify, or improve upon this custom Stochastic Oscillator code in your trading strategies. We hope this detailed walkthrough of the custom Stochastic Oscillator, its limitations, challenges, and filter selection has provided you with valuable insights and a better understanding of how it works. Happy trading!
Recursive Reversal Chart Patterns [Trendoscope]Caution: This algorithm is very heavy and bound to cause timeouts. If that happens, there are few settings you can change to reduce the load. (Will explain them in the description below)
🎲 Recursive Reversal Chart Patterns Indicator
Welcome to another exploration of Zigzag and Pattern ecosystem components. Previously we derived Pitchfork and Recursive Zigzag indicators. This indicator is designed to scan and highlight few popular "Reversal Chart Patterns". Similar to other indicators in the ecosystem, this too is built on recursive zigzags.
Double Taps
Triple Taps
Cup and Handles
Head and Shoulders
Indicator however names the patterns separately for bullish and bearish formations. So, the actual names you see on the screen are
Double Top
Double Bottom
Triple Top
Triple Bottom
Cup and Handle
Inverted Cup and Handle
Head and Shoulders
Inverse Head and Shoulders
Here is a snapshot on how each category of patterns look on the chart.
🎲 Architecture
Many of you may be cursing me for publishing too many libraries. But, these are all preparations for something big. Like other indicators in the Zigzag and Patterns Ecosystem, this too uses a bunch of libraries.
🎯Major direct dependencies
ZigzagTypes
ZigzagMethods
ReversalChartPatternLibrary
🎯Indirect dependencies
DrawingTypes
DrawingMethods
🎯Minor dependencies
Utils
TradeTracker
🎲 Indicator Settings
🎯Generic and Zigzag Settings.
Note: In case of timeout, please decrease the value of depth parameter
🎯Pattern Selection
Having all the patterns selected on chart may also cause timeouts and will make the chart look messy. It is better to limit one or two patterns on the chart to have clear picture.
🎯Scanner Settings
🎯Indicators.
These are options to use indicators as secondary confirmation to calculate divergence. If selected, the patterns are shown only if the divergence data is inline. Option also available to plugin external indicator. These calculations are not straightforward and not easy to measure by manual inspection. This feature at present is purely experimental.
Have a go and let me know how you feel :)
JS-TechTrading: Supertrend-Strategy_Basic versionAre you looking for a reliable and profitable algorithmic trading strategy for TradingView? If so, you might be interested in our Supertrend basic strategy, which is based on three powerful indicators: Supertrend (ATR), RSI and EMA.
Supertrend is a trend-following indicator that helps you identify the direction and strength of the market. It also gives you clear signals for entry and exit points based on price movements.
RSI is a momentum indicator that measures the speed and change of price movements. It helps you filter out false signals and avoid overbought or oversold conditions.
EMA is a moving average indicator that smooths out price fluctuations and shows you the long-term trend of the market. It helps you confirm the validity of your trades and avoid trading against the trend.
Our Supertrend basic strategy combines these three indicators to give you a simple yet effective way to trade any market. Here's how it works:
- For long trades, you enter when the price is above Supertrend and pulls back below it (the low of the candle crosses Supertrend) and then rebounds above it (the high of the next candle goes above the pullback candle). You exit when the price closes below Supertrend or when you reach your target profit or stop loss.
- For short trades, you enter when the price is below Supertrend and pulls back above it (the high of the candle crosses Supertrend) and then drops below it (the low of the next candle goes below the pullback candle). You exit when the price closes above Supertrend or when you reach your target profit or stop loss.
- You can also use RSI and EMA filters to improve your results. For long trades, you only enter if RSI is above 50 and price is above 200 EMA. For short trades, you only enter if RSI is below 50 and price is below 200 EMA.
- You can set your stop loss and target profit as a percentage of your entry price or based on other criteria. You can also adjust the parameters of each indicator according to your preferences and risk tolerance.
Our Supertrend basic strategy is easy to use and has been tested on various markets and time frames. It can help you capture consistent profits while minimizing your losses.
Arbitrary Price Point Probability (APPP)The "Arbitrary Price Point Probability" indicator is designed to calculate the probability of a given price point occurring within a certain range of prices. The indicator uses statistical analysis to determine the likelihood of a specific price point appearing based on the market data.
The indicator works by taking the input price, which is the price point for which the probability is being calculated. The indicator then calculates the mean and standard deviation of the prices over a certain period specified by the user. The length of the period for calculating the mean and standard deviation is also specified by the user.
Once the mean and standard deviation have been calculated, the indicator uses them to calculate the probability of the input price point occurring within the range of prices over the specified period. The indicator does this by calculating the z-score, which is the number of standard deviations between the input price point and the mean price. The z-score is then used to calculate the probability using a t-distribution probability density function.
The t-distribution probability density function used by the indicator is a mathematical function that describes the likelihood of obtaining a particular value from a t-distribution. A t-distribution is a statistical distribution used when the sample size is small, and the population standard deviation is unknown.
The indicator also uses a binary search algorithm to find the t-value for a given confidence level. The t-value is the number of standard deviations from the mean at which the confidence interval is set. The confidence level is set by the user, and the default value is 99%.
Overall, the "Arbitrary Price Point Probability" indicator is a useful tool for traders who want to determine the probability of a particular price point occurring within a certain range of prices. The indicator can be used in conjunction with other technical analysis tools to make more informed trading decisions.
Yesterday’s High Breakout - Trend Following StrategyYesterday’s High Breakout it is a trading system based on the analysis of yesterday's highs, it works in trend-following mode therefore it opens a long position at the breakout of yesterday's highs even if they occur several times in one day.
There are several methods for exiting a trade, each with its own unique strategy. The first method involves setting Take-Profit and Stop-Loss percentages, while the second utilizes a trailing-stop with a specified offset value. The third method calls for a conditional exit when the candle closes below a reference EMA.
Additionally, operational filters can be applied based on the volatility of the currency pair, such as calculating the percentage change from the opening or incorporating a gap to the previous day's high levels. These filters help to anticipate or delay entry into the market, mitigating the risk of false breakouts.
In the specific case of NULS, a 9% Take-Profit and a 3% Stop-Loss were set, with an activated trailing-stop percentage. To postpone entry and avoid false breakouts, a 1% gap was added to the price of yesterday's highs.
Name : Yesterday's High Breakout - Trend Follower Strategy
Author : @tumiza999
Category : Trend Follower, Breakout of Yesterday's High.
Operating mode : Spot or Futures (only long).
Trade duration : Intraday.
Timeframe : 30M, 1H, 2H, 4H
Market : Crypto
Suggested usage : Short-term trading, when the market is in trend and it is showing high volatility.
Entry : When there is a breakout of Yesterday's High.
Exit : Profit target or Trailing stop, Stop loss or Crossunder EMA.
Configuration :
- Gap to anticipate or postpone the entry before or after the identified level
- Rate of Change for Entry Condition
- Take Profit, Stop Loss and Trailing Stop
- EMA length
Backtesting :
⁃ Exchange: BINANCE
⁃ Pair: NULSUSDT
⁃ Timeframe: 2H
⁃ Fee: 0.075%
⁃ Slippage: 1
- Initial Capital: 10000 USDT
- Position sizing: 10% of Equity
- Start : 2018-07-26 (Out Of Sample from 2022-12-23)
- Bar magnifier: on
Credits : LucF for Pine Coders (f_security function to avoid repainting using security)
Disclaimer : Risk Management is crucial, so adjust stop loss to your comfort level. A tight stop loss can help minimise potential losses. Use at your own risk.
How you or we can improve? Source code is open so share your ideas!
Leave a comment and smash the boost button!
Thanks for your attention, happy to support the TradingView community.
Advanced Price Direction bar colorsIn the advanced price direction algorithm situations of faltering price directions (fda) are identified.
These are very interesting, because this happens at tops, flags and trend turns.
I got the idea of coloring the bars with fda in a distinguishing color, reddish gray for fda down and blueish gray for faltering up.
The remaining bars retain standard color, but now this color 'confirms' the trend.
To show that this is true, I also plot a simple moving average (sma) with the same length in the chart.
It turns out that somehow the bars react to being above or below the sma, but also react to the direction of the sma.
Very interesting.
Have fun
3D BowlingIntroducing the "3D Bowling Game" – a fun and interactive demo scene project in Pine Script, powered by a custom 3D engine! This bowling game showcases the potential of Pine Script for developing engaging and immersive experiences, even within the confines of a trading platform.
To play the game, you'll first be prompted to choose where you want to throw the ball. Next, you'll be asked to draw a line indicating the direction you want the ball to go. Sit back and enjoy as the game takes care of the rest!
The source code features various sections, including:
Types and helper functions to manipulate vectors, matrices, and angles
Routines for calculating cross products, dot products, and vector normalization
Transformation matrices for rotation and scaling
Functions for perspective transformation, mesh transformations, and face normal calculations
Culling and shading algorithms to provide a more realistic visual experience
The project's source code is an excellent starting point for anyone interested in exploring the capabilities of Pine Script beyond the typical trading indicators and strategies. The 3D Bowling Game demonstrates the flexibility of Pine Script and its potential for creating interactive experiences in a seemingly unconventional environment.
So, what are you waiting for? Dive into the source code, tweak it to your liking, or build upon it to create your own interactive 3D experiences. Enjoy the game, and happy coding!
With light. I will say there is an issue with the fact that you cant draw as may linefills as you can lines.
Sniffer
╭━━━╮╱╱╱╱╭━╮╭━╮
┃╭━╮┃╱╱╱╱┃╭╯┃╭╯
┃╰━━┳━╮╭┳╯╰┳╯╰┳━━┳━╮
╰━━╮┃╭╮╋╋╮╭┻╮╭┫┃━┫╭╯
┃╰━╯┃┃┃┃┃┃┃╱┃┃┃┃━┫┃
╰━━━┻╯╰┻╯╰╯╱╰╯╰━━┻╯
Overview
A vast majority of modern data analysis & modelling techniques rely upon the idea of hidden patterns, wether it is some type of visualisation tool or some form of a complex machine learning algorithm, the one thing that they have in common is the belief, that patterns tell us what’s hidden behind plain numbers. The same philosophy has been adopted by many traders & investors worldwide, there’s an entire school of thought that operates purely based on chart patterns. This is where Sniffer comes in, it is a tool designed to simplify & quantify the job of pattern recognition on any given price chart, by combining various factors & techniques that generate high-quality results.
This tool analyses bars selected by the user, and highlights bar clusters on the chart that exhibit similar behaviour across multiple dimensions. It can detect a single candle pattern like hammers or dojis, or it can handle multiple candles like morning/evening stars or double tops/bottoms, and many more. In fact, the tool is completely independent of such specific candle formations, instead, it works on the idea of vector similarity and generates a degree of similarity for every single combination of candles. Only the top-n matches are highlighted, users get to choose which patterns they want to analyse and to what degree, by customising the feature-space.
Background
In the world of trading, a common use-case is to scan a price chart for some specific candlestick formations & price structures, and then the chart is further analysed in reference to these events. Traders are often trying to answer questions like, when was the last time price showed similar behaviour, what are the instances similar to what price is doing right now, what happens when price forms a pattern like this, what were some of other indicators doing when this happened last(RSI, CCI, ADX etc), and many other abstract ideas to have a stronger confluence or to confirm a bias.Having such a context can be vital in making better informed decisions, but doing this manually on a chart that has thousands of candles can have many disadvantages. It’s tedious, human errors are rather likely, and even if it’s done with pin-point accuracy, chances are that we’ll miss out on many pieces of information. This is the thought that gave birth to Sniffer .
Sniffer tries to provide a general solution for pattern-based analysis by deploying vector-similarity computation techniques, that cover the full-breadth of a price chart and generate a list of top-n matches based on the criteria selected by the user. Most of these techniques come from the data science space, where vector similarity is often implemented to solve classification & clustering problems. Sniffer uses same principles of vector comparison, and computes a degree of similarity for every single candle formation within the selected range, and as a result generates a similarity matrix that captures how similar or dissimilar a set of candles is to the input set selected by the user.
How It Works
A brief overview of how the tool is implemented:
- Every bar is processed, and a set of features are mapped to it.
- Bars selected by the user are captured, and saved for later use.
- Once the all the bars have been processed, candles are back-tracked and degree of similarity is computed for every single bar(max-limit is 5000 bars).
- Degree of similarity is computed by comparing attributes like price range, candle breadth & volume etc.
- Similarity matrix is sorted and top-n results are highlighted on the chart through boxes of different colors.
A brief overview of the features space for bars:
- Range: Difference between high & low
- Body: Difference between close & open
- Volume: Traded volume for that candle
- Head: Upper wick for green candles & lower wick for red candles
- Tail: Lower wick for green candles & upper wick for red candles
- BTR: Body to Range ratio
- HTR: Head to Range ratio
- TTR: Tail to Range ratio
- HTB: Head to Body ratio
- TTB: Tail to Body ratio
- ROC: Rate of change for HL2 for four different periods
- RSI: Relative Strength Index
- CCI: Commodity Channel Index
- Stochastic: Stochastic Index
- ADX: DMI+, DMI- & ADX
A brief overview of how degree of similarity is calculated:
- Each bar set is compared to the inout bar set within the selected feature space
- Features are represented as vectors, and distance between the vectors is calculated
- Shorter the distance, greater the similarity
- Different distance calculation methods are available to choose from, such as Cosine, Euclidean, Lorentzian, Manhattan, & Pearson
- Each method is likely to generate slightly different results, users are expected to select the method & the feature space that best fits their use-case
How To Use It
- Usage of this tool is relatively straightforward, users can add this indicator to their chart and similar clusters will be highlighted automatically
- Users need to select a time range that will be treated as input, and bars within that range become the input formation for similarity calculations
- Boxes will be draw around the clusters that fit the matching criteria
- Boxes are color-coded, green color boxes represent the top one-third of the top-n matches, yellow boxes represent the middle third, red boxes are for bottom third, and white box represents user-input
- Boxes colors will be adjusted as you adjust input parameters, such as number of matches or look-back period
User Settings
Users can configure the following options:
- Select the time-range to set input bars
- Select the look-back period, number of candles to backtrack for similarity search
- Select the number of top-n matches to show on the chart
- Select the method for similarity calculation
- Adjust the feature space, this enables addition of custom features, such as pattern recognition, technical indicators, rate of change etc
- Toggle verbosity, shows degree of similarity as a percentage value inside the box
Top Features
- Pattern Agnostic: Designed to work with variable number of candles & complex patterns
- Customisable Feature Space: Users get to add custom features to each bar
- Comprehensive Comparison: Generates a degree of similarity for all possible combinations
Final Note
- Similarity matches will be shown only within last 4500 bars.
- In theory, it is possible to compute similarity for any size candle formations, indicator has been tested with formations of 50+ candles, but it is recommended to select smaller range for faster & cleaner results.
- As you move to smaller time frames, selected time range will provide a larger number of candles as input, which can produce undesired results, it is advised to adjust your selection when you change time frames. Seeking suggestions on how to directly receive bars as user input, instead of time range.
- At times, users may see array index out of bound error when setting up this indicator, this generally happens when the input range is not properly configured. So, it should disappear after you select the input range, still trying to figure out where it is coming from, suggestions are welcome.
Credits
- @HeWhoMustNotBeNamed for publishing such a handy PineScript Logger, it certainly made the job a lot easier.
Lex_3CR_Functions_Library2Library "Lex_3CR_Functions_Library2"
This is a source code for a technical analysis library in Pine Script language,
designed to identify and mark Bullish and Bearish Three Candle Reversal (3CR) chart patterns.
The library provides three functions to be used in a trading algorithm.
The first function, Bull_3crMarker, adds a dashed line and label to a Bullish 3CR chart pattern, indicating the 3CR point.
The second function, Bear_3crMarker, adds a dashed line and label to a Bearish 3CR chart pattern.
The third function, Bull_3CRlogicals, checks for a Bullish 3CR pattern where the first candle's low is greater than the second candle's low and the second candle's low is less than the third candle's low.
If found, creates a line at the breakout point and a label at the fail point,
if specified. All functions take parameters such as the chart pattern's characteristics and output colors, labels, and markers.
Bull_3crMarker(bulllinearray, barnum, breakpoint, failpointB, failpoint, linecolorbull, bulllabelarray, labelcolor, textcolor, labelon)
Bull_3crMarker Adds a 3CR marker to a Bullish 3CR chart pattern
@description Adds a dashed line and label to a 3CR up chart pattern, indicating the 3CR (3 Candle Reversal) point.
Parameters:
bulllinearray (line )
barnum (int)
breakpoint (float)
failpointB (float )
failpoint (float)
linecolorbull (color)
bulllabelarray (label )
labelcolor (color)
textcolor (color)
labelon (bool)
Bear_3crMarker(bearlinearray, barnum, breakpoint, failpointB, failpoint, linecolorbear, bearlabelarray, labelcolor, textcolor, labelon)
Bear_3crMarker Adds a 3CR marker to a Bearish 3CR chart pattern
@description Adds a dashed line and label to a 3CR down chart pattern, indicating the 3CR (3 Candle Reversal) point.
Parameters:
bearlinearray (line )
barnum (int)
breakpoint (float)
failpointB (float )
failpoint (float)
linecolorbear (color)
bearlabelarray (label )
labelcolor (color)
textcolor (color)
labelon (bool)
Bull_3CRlogicals(low1, low2, low3, bulllinearray, bulllabelarray, failpointB, linecolorbull, labelcolor, textcolor, labelon)
Checks for a bullish three candle reversal pattern and creates a line and label at the breakout point if found
@description Checks for a bullish three candle reversal pattern where the first candle's low is greater than the second candle's low and the second candle's low is less than the third candle's low. If found, creates a line at the breakout point and a label at the fail point, if specified.
Parameters:
low1 (float)
low2 (float)
low3 (float)
bulllinearray (line )
bulllabelarray (label )
failpointB (float )
linecolorbull (color)
labelcolor (color)
textcolor (color)
labelon (bool)
Bear_3CRlogicals(high1, high2, high3, bearlinearray, bearlabelarray, failpointB, linecolorbear, labelcolor, textcolor, labelon)
Checks for a Bearish 3CR pattern and draws a bearish marker on the chart at the appropriate location
@description This function checks for a Bearish 3CR (Three-Candle Reversal) pattern, which is defined as the second candle having a higher high than the first and third candles, and the third candle having a lower high than the first candle. If the pattern is detected, a bearish marker is drawn on the chart at the appropriate location, and an optional label can be added to the marker.
Parameters:
high1 (float)
high2 (float)
high3 (float)
bearlinearray (line )
bearlabelarray (label )
failpointB (float )
linecolorbear (color)
labelcolor (color)
textcolor (color)
labelon (bool)
bullLineDelete(i, bulllinearray, failarray, bulllabelarray, labelon)
Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line
@description Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line.
Parameters:
i (int)
bulllinearray (line )
failarray (float )
bulllabelarray (label )
labelon (bool)
bearLineDelete(i, bearlinearray, failarray, bearlabelarray, labelon)
Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line
@description Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line.
Parameters:
i (int)
bearlinearray (line )
failarray (float )
bearlabelarray (label )
labelon (bool)
bulloffsetdelete(i, bulllinearray, failarray, bulllabelarray, labelon)
Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line
@description Removes a bullish line from a specified position in a line array, and optionally removes a label associated with that line.
Parameters:
i (int)
bulllinearray (line )
failarray (float )
bulllabelarray (label )
labelon (bool)
bearoffsetdelete(i, bearlinearray, failarray, bearlabelarray, labelon)
Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line
@description Removes a bearish line from a specified position in a line array, and optionally removes a label associated with that line.
Parameters:
i (int)
bearlinearray (line )
failarray (float )
bearlabelarray (label )
labelon (bool)
BullEntry_setter(i, bulllinearray, failpointB, entrystopB, entryB, entryboolB)
Checks if the specified value is greater than the break point of any bullish line in an array, and removes that line if true
@description Checks if the s pecified value is greater than the break point of any bullish line in an array, and removes that line if true.
Parameters:
i (int)
bulllinearray (line )
failpointB (float )
entrystopB (float )
entryB (float )
entryboolB (bool )
Bull3CRchecker(close1, bulllinearray, FailpointB, rsiB, bulllabelarray, labelt, bullcolored, directionarray, rsi, secondbullline, entrystopB, entryB, entryboolB)
Parameters:
close1 (float)
bulllinearray (line )
FailpointB (float )
rsiB (float )
bulllabelarray (label )
labelt (bool)
bullcolored (color)
directionarray (label )
rsi (float)
secondbullline (line )
entrystopB (float )
entryB (float )
entryboolB (bool )
Bear3CRchecker(close1, bearlinearray, FailpointB, bearlabelarray, labelt, bearcolored, directionarray, rsi, secondbearline, rsiB)
Checks if the specified value is less than the break point of any bearish line in an array, and removes that line if true
@description Checks if the specified value is less than the break point of any bearish line in an array, and removes that line if true.
Parameters:
close1 (float)
bearlinearray (line )
FailpointB (float )
bearlabelarray (label )
labelt (bool)
bearcolored (color)
directionarray (label )
rsi (float)
secondbearline (line )
rsiB (float )
Bulloffsetcheck(FailpointB, bulllabelarray, linearray, labelt, offset)
Checks the offset of bullish lines and deletes them if they are beyond a certain offset from the current bar index
@description Checks the offset of bullish lines and deletes them if they are beyond a certain offset from the current bar index
Parameters:
FailpointB (float )
bulllabelarray (label )
linearray (line )
labelt (bool)
offset (int)
Bearoffsetcheck(FailpointB, bearlabelarray, linearray, labelt, offset)
Checks the offset of bearish lines and deletes them if they are beyond a certain offset from the current bar index
@description Checks the offset of bearish lines and deletes them if they are beyond a certain offset from the current bar index
Parameters:
FailpointB (float )
bearlabelarray (label )
linearray (line )
labelt (bool)
offset (int)
Bullfailchecker(close1, FailpointB, bulllabelarray, linearray, labelt)
Checks if the current price has crossed above a bullish fail point and deletes the corresponding line and label
@description Checks if the current price has crossed above a bullish fail point and deletes the corresponding line and label
Parameters:
close1 (float)
FailpointB (float )
bulllabelarray (label )
linearray (line )
labelt (bool)
Bearfailchecker(close1, FailpointB, bearlabelarray, linearray, labelt)
Checks for bearish lines that have failed to trigger and removes them from the chart
@description This function checks for bearish lines that have failed to trigger (i.e., where the current price is above the fail point) and removes them from the chart along with any associated label.
Parameters:
close1 (float)
FailpointB (float )
bearlabelarray (label )
linearray (line )
labelt (bool)
rsibullchecker(rsiinput, rsiBull, secondbullline)
Checks for bullish RSI lines that have failed to trigger and removes them from the chart
@description This function checks for bullish RSI lines that have failed to trigger (i.e., where the current RSI value is below the line's trigger level) and removes them from the chart along with any associated line.
Parameters:
rsiinput (float)
rsiBull (float )
secondbullline (line )
rsibearchecker(rsiinput, rsiBear, secondbearline)
Checks for bearish RSI lines that have failed to trigger and removes them from the chart
@description This function checks for bearish RSI lines that have failed to trigger (i.e., where the current RSI value is above the line's trigger level) and removes them from the chart along with any associated line.
Parameters:
rsiinput (float)
rsiBear (float )
secondbearline (line )
FunctionProbabilityViterbiLibrary "FunctionProbabilityViterbi"
The Viterbi Algorithm calculates the most likely sequence of hidden states *(called Viterbi path)*
that results in a sequence of observed events.
viterbi(observations, transitions, emissions, initial_distribution)
Calculate most probable path in a Markov model.
Parameters:
observations (int ) : array . Observation states data.
transitions (matrix) : matrix . Transition probability table, (HxH, H:Hidden states).
emissions (matrix) : matrix . Emission probability table, (OxH, O:Observed states).
initial_distribution (float ) : array . Initial probability distribution for the hidden states.
Returns: array. Most probable path.
ICT Macros by CryptoforICT Macros by Cryptofor
Time periods in which the price is most volatile. At this time, the algorithm is programmed to attack liquidity or fill a significant FVG from which the OF can continue.
Plots of macros:
1. London Macros:
02:33 - 03:00
04:03 - 04:30
2. New York AM Macros:
08:50 - 09:10
09:50 - 10:10
10:50 - 11:10
3. New York Lunch + PM Macros:
11:50 - 12:10
13:10 - 13:40
15:15 - 15:45
Features:
Flexible line settings
Flexible text settings
Display data for all time or for the last 24 hours
Switch for each type of macro
Macro background color settings
Advanced VWAP_Pullback Strategy_Trend-Template QualifierGeneral Description and Unique Features of this Script
Introducing the Advanced VWAP Momentum-Pullback Strategy (long-only) that offers several unique features:
1. Our script/strategy utilizes Mark Minervini's Trend-Template as a qualifier for identifying stocks and other financial securities in confirmed uptrends. Mark Minervini, a 2x US Investment Champion, developed the Trend-Template, which covers eight different and independent characteristics that can be adjusted and optimized in this trend-following strategy to ensure the best results. The strategy will only trigger buy-signals in case the optimized qualifiers are being met.
2. Our strategy is based on the supply/demand balance in the market, making it timeless and effective across all timeframes. Whether you are day trading using 1- or 5-min charts or swing-trading using daily charts, this strategy can be applied and works very well.
3. We have also integrated technical indicators such as the RSI and the MA / VWAP crossover into this strategy to identify low-risk pullback entries in the context of confirmed uptrends. By doing so, the risk profile of this strategy and drawdowns are being reduced to an absolute minimum.
Minervini’s Trend-Template and the ‘Stage-Analysis’ of the Markets
This strategy is a so-called 'long-only' strategy. This means that we only take long positions, short positions are not considered.
The best market environment for such strategies are periods of stable upward trends in the so-called stage 2 - uptrend.
In stable upward trends, we increase our market exposure and risk.
In sideways markets and downward trends or bear markets, we reduce our exposure very quickly or go 100% to cash and wait for the markets to recover and improve. This allows us to avoid major losses and drawdowns.
This simple rule gives us a significant advantage over most undisciplined traders and amateurs!
'The Trend is your Friend'. This is a very old but true quote.
What's behind it???
• 98% of stocks made their biggest gains in a Phase 2 upward trend.
• If a stock is in a stable uptrend, this is evidence that larger institutions are buying the stock sustainably.
• By focusing on stocks that are in a stable uptrend, the chances of profit are significantly increased.
• In a stable uptrend, investors know exactly what to expect from further price developments. This makes it possible to locate low-risk entry points.
The goal is not to buy at the lowest price – the goal is to buy at the right price!
Each stock goes through the same maturity cycle – it starts at stage 1 and ends at stage 4
Stage 1 – Neglect Phase – Consolidation
Stage 2 – Progressive Phase – Accumulation
Stage 3 – Topping Phase – Distribution
Stage 4 – Downtrend – Capitulation
This strategy focuses on identifying stocks in confirmed stage 2 uptrends. This in itself gives us an advantage over long-term investors and less professional traders.
By focusing on stocks in a stage 2 uptrend, we avoid losses in downtrends (stage 4) or less profitable consolidation phases (stages 1 and 3). We are fully invested and put our money to work for us, and we are fully invested when stocks are in their stage 2 uptrends.
But how can we use technical chart analysis to find stocks that are in a stable stage 2 uptrend?
Mark Minervini has developed the so-called 'trend template' for this purpose. This is an essential part of our JS-TechTrading pullback strategy. For our watchlists, only those individual values that meet the tough requirements of Minervini's trend template are eligible.
The Trend Template
• 200d MA increasing over a period of at least 1 month, better 4-5 months or longer
• 150d MA above 200d MA
• 50d MA above 150d MA and 200d MA
• Course above 50d MA, 150d MA and 200d MA
• Ideally, the 50d MA is increasing over at least 1 month
• Price at least 25% above the 52w low
• Price within 25% of 52w high
• High relative strength according to IBD.
NOTE: In this basic version of the script, the Trend-Template has to be used as a separate indicator on TradingView (Public Trend-Template indicators are available in TradingView – community scripts). It is recommended to only execute buy signals in case the stock or financial security is in a stage 2 uptrend, which means that the criteria of the trend-template are fulfilled.
This strategy can be applied to all timeframes from 5 min to daily.
The VWAP Momentum-Pullback Strategy
For the JS-TechTrading VWAP Momentum-Pullback Strategy, only stocks and other financial instruments that meet the selected criteria of Mark Minervini's trend template are recommended for algorithmic trading with this startegy.
A further prerequisite for generating a buy signals is that the individual value is in a short-term oversold state (RSI).
When the selling pressure is over and the continuation of the uptrend can be confirmed by the MA / VWAP crossover after reaching a price low, a buy signal is issued by this strategy.
Stop-loss limits and profit targets can be set variably. You also have the option to make use of the trailing stop exit strategy.
Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a technical indicator developed by Welles Wilder in 1978. The RSI is used to perform a market value analysis and identify the strength of a trend as well as overbought and oversold conditions. The indicator is calculated on a scale from 0 to 100 and shows how much an asset has risen or fallen relative to its own price in recent periods.
The RSI is calculated as the ratio of average profits to average losses over a certain period of time. A high value of the RSI indicates an overbought situation, while a low value indicates an oversold situation. Typically, a value > 70 is considered an overbought threshold and a value < 30 is considered an oversold threshold. A value above 70 signals that a single value may be overvalued and a decrease in price is likely , while a value below 30 signals that a single value may be undervalued and an increase in price is likely.
For example, let's say you're watching a stock XYZ. After a prolonged falling movement, the RSI value of this stock has fallen to 26. This means that the stock is oversold and that it is time for a potential recovery. Therefore, a trader might decide to buy this stock in the hope that it will rise again soon.
The MA / VWAP Crossover Trading Strategy
This strategy combines two popular technical indicators: the Moving Average (MA) and the Volume Weighted Average Price (VWAP). The MA VWAP crossover strategy is used to identify potential trend reversals and entry/exit points in the market.
The VWAP is calculated by taking the average price of an asset for a given period, weighted by the volume traded at each price level. The MA, on the other hand, is calculated by taking the average price of an asset over a specified number of periods. When the MA crosses above the VWAP, it suggests that buying pressure is increasing, and it may be a good time to enter a long position. When the MA crosses below the VWAP, it suggests that selling pressure is increasing, and it may be a good time to exit a long position or enter a short position.
Traders typically use the MA VWAP crossover strategy in conjunction with other technical indicators and fundamental analysis to make more informed trading decisions. As with any trading strategy, it is important to carefully consider the risks and potential rewards before making any trades.
This strategy is applicable to all timeframes and the relevant parameters for the underlying indicators (RSI and MA/VWAP) can be adjusted and optimized as needed.
Backtesting
Backtesting gives outstanding results on all timeframes and drawdowns can be reduced to a minimum level. In this example, the hourly chart for MCFT has been used.
Settings for backtesting are:
- Period from Jan 2020 until March 2023
- Starting capital 100k USD
- Position size = 25% of equity
- 0.01% commission = USD 2.50.- per Trade
- Slippage = 2 ticks
Other comments
- This strategy has been designed to identify the most promising, highest probability entries and trades for each stock or other financial security.
- The combination of the Trend-Template and the RSI qualifiers results in a highly selective strategy which only considers the most promising swing-trading entries. As a result, you will normally only find a low number of trades for each stock or other financial security per year in case you apply this strategy for the daily charts. Shorter timeframes will result in a higher number of trades / year.
- Consequently, traders need to apply this strategy for a full watchlist rather than just one financial security.
Сoncentrated Market Maker Strategy by oxowlConcentrated Market Maker Strategy by oxowl. This script plots an upper and lower bound for liquidity provision, and checks for rebalancing conditions. It also includes alert conditions for when the price crosses the upper or lower bounds.
Here's an overview of the script:
It defines the input parameters: liquidity range percentage, rebalance frequency in minutes, and minimum trade size in assets.
It calculates the upper and lower bounds for liquidity provision based on the liquidity range percentage.
It initializes variables for the last rebalance time and price.
It defines a rebalance condition based on the frequency and current price within the specified range.
If the rebalance condition is met, it updates the last rebalance time and price.
It plots the upper and lower bounds on the chart as lines and adds price labels for both bounds.
It defines alert conditions for when the price crosses the upper or lower bounds.
Finally, it creates alert conditions with appropriate messages for when the price crosses the upper or lower bounds.
Concentrated liquidity is a concept often used in decentralized finance (DeFi) market-making strategies. It allows liquidity providers (LPs) to focus their liquidity within a specific price range, rather than across the entire price curve. Using an indicator with concentrated liquidity can offer several advantages:
Increased capital efficiency: Concentrated liquidity allows LPs to allocate their capital within a narrower price range. This means that the same amount of capital can generate more significant price impact and potentially higher returns compared to providing liquidity across a broader range.
Customized risk exposure: LPs can choose the price range they feel most comfortable with, allowing them to better manage their risk exposure. By selecting a range based on their market outlook, they can optimize their positions to maximize potential returns.
Adaptive strategies: Indicators that support concentrated liquidity can help traders adapt their strategies based on market conditions. For example, they can choose to provide liquidity around a stable price range during low-volatility periods or adjust their range when market conditions change.
To continue integrating this script into your trading strategy, follow these steps:
Import the script into your TradingView account. Navigate to the Pine editor, paste the code, and save it as a new script.
Apply the indicator to a trading pair chart. You can customize the input parameters (liquidity range percentage, rebalance frequency, and minimum trade size) based on your preferences and risk tolerance.
Set alerts for when the price crosses the upper or lower bounds. This will notify you when it's time to take action, such as adding or removing liquidity, or rebalancing your position.
Monitor the performance of your strategy over time. Adjust the input parameters as needed to optimize your returns and manage risk effectively.
(Optional) Integrate the script with a trading bot or automation platform. If you're using an API-based trading solution, you can incorporate the logic and conditions from the script into your bot's algorithm to automate the process of providing concentrated liquidity and rebalancing your positions.
Remember that no strategy is foolproof, and past performance is not indicative of future results. Always exercise caution when trading and carefully consider your risk tolerance.
JS-TechTrading: VWAP Momentum_Pullback StrategyGeneral Description and Unique Features of this Script
Introducing the VWAP Momentum-Pullback Strategy (long-only) that offers several unique features:
1. Our script/strategy utilizes Mark Minervini's Trend-Template as a qualifier for identifying stocks and other financial securities in confirmed uptrends.
NOTE: In this basic version of the script, the Trend-Template has to be used as a separate indicator on TradingView (Public Trend-Template indicators are available on TradingView – community scripts). It is recommended to only execute buy signals in case the stock or financial security is in a stage 2 uptrend, which means that the criteria of the trend-template are fulfilled.
2. Our strategy is based on the supply/demand balance in the market, making it timeless and effective across all timeframes. Whether you are day trading using 1- or 5-min charts or swing-trading using daily charts, this strategy can be applied and works very well.
3. We have also integrated technical indicators such as the RSI and the MA / VWAP crossover into this strategy to identify low-risk pullback entries in the context of confirmed uptrends. By doing so, the risk profile of this strategy and drawdowns are being reduced to an absolute minimum.
Minervini’s Trend-Template and the ‘Stage-Analysis’ of the Markets
This strategy is a so-called 'long-only' strategy. This means that we only take long positions, short positions are not considered.
The best market environment for such strategies are periods of stable upward trends in the so-called stage 2 - uptrend.
In stable upward trends, we increase our market exposure and risk.
In sideways markets and downward trends or bear markets, we reduce our exposure very quickly or go 100% to cash and wait for the markets to recover and improve. This allows us to avoid major losses and drawdowns.
This simple rule gives us a significant advantage over most undisciplined traders and amateurs!
'The Trend is your Friend'. This is a very old but true quote.
What's behind it???
• 98% of stocks made their biggest gains in a Phase 2 upward trend.
• If a stock is in a stable uptrend, this is evidence that larger institutions are buying the stock sustainably.
• By focusing on stocks that are in a stable uptrend, the chances of profit are significantly increased.
• In a stable uptrend, investors know exactly what to expect from further price developments. This makes it possible to locate low-risk entry points.
The goal is not to buy at the lowest price – the goal is to buy at the right price!
Each stock goes through the same maturity cycle – it starts at stage 1 and ends at stage 4
Stage 1 – Neglect Phase – Consolidation
Stage 2 – Progressive Phase – Accumulation
Stage 3 – Topping Phase – Distribution
Stage 4 – Downtrend – Capitulation
This strategy focuses on identifying stocks in confirmed stage 2 uptrends. This in itself gives us an advantage over long-term investors and less professional traders.
By focusing on stocks in a stage 2 uptrend, we avoid losses in downtrends (stage 4) or less profitable consolidation phases (stages 1 and 3). We are fully invested and put our money to work for us, and we are fully invested when stocks are in their stage 2 uptrends.
But how can we use technical chart analysis to find stocks that are in a stable stage 2 uptrend?
Mark Minervini has developed the so-called 'trend template' for this purpose. This is an essential part of our JS-TechTrading pullback strategy. For our watchlists, only those individual values that meet the tough requirements of Minervini's trend template are eligible.
The Trend Template
• 200d MA increasing over a period of at least 1 month, better 4-5 months or longer
• 150d MA above 200d MA
• 50d MA above 150d MA and 200d MA
• Course above 50d MA, 150d MA and 200d MA
• Ideally, the 50d MA is increasing over at least 1 month
• Price at least 25% above the 52w low
• Price within 25% of 52w high
• High relative strength according to IBD.
NOTE: In this basic version of the script, the Trend-Template has to be used as a separate indicator on TradingView (Public Trend-Template indicators are available in TradingView – community scripts). It is recommended to only execute buy signals in case the stock or financial security is in a stage 2 uptrend, which means that the criteria of the trend-template are fulfilled.
This strategy can be applied to all timeframes from 5 min to daily.
The VWAP Momentum-Pullback Strateg y
For the JS-TechTrading VWAP Momentum-Pullback Strategy, only stocks and other financial instruments that meet the selected criteria of Mark Minervini's trend template are recommended for algorithmic trading with this startegy.
A further prerequisite for generating a buy signals is that the individual value is in a short-term oversold state (RSI).
When the selling pressure is over and the continuation of the uptrend can be confirmed by the MA / VWAP crossover after reaching a price low, a buy signal is issued by this strategy.
Stop-loss limits and profit targets can be set variably.
Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a technical indicator developed by Welles Wilder in 1978. The RSI is used to perform a market value analysis and identify the strength of a trend as well as overbought and oversold conditions. The indicator is calculated on a scale from 0 to 100 and shows how much an asset has risen or fallen relative to its own price in recent periods.
The RSI is calculated as the ratio of average profits to average losses over a certain period of time. A high value of the RSI indicates an overbought situation, while a low value indicates an oversold situation. Typically, a value > 70 is considered an overbought threshold and a value < 30 is considered an oversold threshold. A value above 70 signals that a single value may be overvalued and a decrease in price is likely , while a value below 30 signals that a single value may be undervalued and an increase in price is likely.
For example, let's say you're watching a stock XYZ. After a prolonged falling movement, the RSI value of this stock has fallen to 26. This means that the stock is oversold and that it is time for a potential recovery. Therefore, a trader might decide to buy this stock in the hope that it will rise again soon.
The MA / VWAP Crossover Trading Strategy
This strategy combines two popular technical indicators: the Moving Average (MA) and the Volume Weighted Average Price (VWAP). The MA VWAP crossover strategy is used to identify potential trend reversals and entry/exit points in the market.
The VWAP is calculated by taking the average price of an asset for a given period, weighted by the volume traded at each price level. The MA, on the other hand, is calculated by taking the average price of an asset over a specified number of periods. When the MA crosses above the VWAP, it suggests that buying pressure is increasing, and it may be a good time to enter a long position. When the MA crosses below the VWAP, it suggests that selling pressure is increasing, and it may be a good time to exit a long position or enter a short position.
Traders typically use the MA VWAP crossover strategy in conjunction with other technical indicators and fundamental analysis to make more informed trading decisions. As with any trading strategy, it is important to carefully consider the risks and potential rewards before making any trades.
This strategy is applicable to all timeframes and the relevant parameters for the underlying indicators (RSI and MA/VWAP) can be adjusted and optimized as needed.
Backtesting
Backtesting gives outstanding results on all timeframes and drawdowns can be reduced to a minimum level. In this example, the hourly chart for MCFT has been used.
Settings for backtesting are:
- Period from April 2020 until April 2021 (1 yr)
- Starting capital 100k USD
- Position size = 25% of equity
- 0.01% commission = USD 2.50.- per Trade
- Slippage = 2 ticks
Other comments
• This strategy has been designed to identify the most promising, highest probability entries and trades for each stock or other financial security.
• The RSI qualifier is highly selective and filters out the most promising swing-trading entries. As a result, you will normally only find a low number of trades for each stock or other financial security per year in case you apply this strategy for the daily charts. Shorter timeframes will result in a higher number of trades / year.
• As a result, traders need to apply this strategy for a full watchlist rather than just one financial security.
Advanced Price Direction AlgorithmPrices can go up or down or falter in their movement.
This code evaluates this by looking at two consecutive bars or sets of bars.
If you put the set size to 1, the current and previous bar is evaluated.
If put to 2, the last2 and the 2 before these are evaluated.
Default is 12 because this seems to coincide with trend changes.
This code provides an advanced way to evaluate what the price does in a sort of three-value Boolean with the values up, down or falter.
I use this code in indicators I develop where price direction is taken into account.
The simple output makes it possible to use it as an indicator on its own.
Weis V5 zigzag jayySomehow, I deleted version 5 of the zigzag script. Same name. I have added some older notes describing how the Weis Wave works.
I have also changed the date restriction that stopped the script from working after Dec 31, 2022.
What you see here is the Weis zigzag wave plotted directly on the price chart. This script is the companion to the Weis cumulative wave volume script.
What is a Weis wave? David Weis has been recognized as a Wyckoff method analyst he has written two books one of which, Trades About to Happen, describes the evolution of the now-popular Weis wave. The method employed by Weis is to identify waves of price action and to compare the strength of the waves on characteristics of wave strength. Chief among the characteristics of strength is the cumulative volume of the wave. There are other markers that Weis uses as well for example how the actual price difference between the start of the Weis wave from start to finish. Weis also uses time, particularly when using a Renko chart
David Weis did a futures io video which is a popular source of information about his method. (Search David Weis and futures.io. I strongly suggest you also read “Trades About to Happen” by David Weis.
This will get you up and running more quickly when studying charts. However, you should choose the Traditional method to be true to David Weis technique as described in his book "Trades About to Happen" and in the Futures IO Webcast featuring David Weis
. The Weis pip zigzag wave shows how far in terms of bar close price a Weis wave has traveled through the duration of a Weis wave. The Weis zigzag wave is used in combination with the Weis cumulative volume wave. The two waves should be set to the same "wave size".
To use this script, you must set the wave size: Using the traditional Weis method simply enter the desired wave size in the box "How should wave size be calculated", in this example I am using a traditional wave size of .25. Each wave for each security and each timeframe requires its own wave size. Although not the traditional method devised by David Weis a more automatic way to set wave size would be to use Average True Range (ATR). Using ATR is not the true Weis method but it does give you similar waves and, importantly, without the hassle described above. Once the Weis wave size is set then the zigzag wave will be shown with volume. Because Weis used the closing price of a wave to define waves a line Bar highs and bar lows are not captured by the Weis Wave. The default script setting is now cumulative volume waves using an ATR of 7 and a multiplication factor of .5.
To display volume in a way that does not crowd out neighbouring volumes Weis displayed volume as a maximum of 3 digits (usually). Consider two Weis Wave volumes 176,895,570 and 2,654,763,889. To display wave volume as three digits it is necessary to take a number such as 176,895,570 and truncate it. 176,895,570 can be represented as 177 X 10 to the power of 6. The number displayed must also be relative to other numbers in the field. If the highest volume on the page is: 2,654,763,889 and with only three numbers available to display the result the value shown must be 265 (265 X 10 to the power of 7). Since 176,895,570 is an order of magnitude smaller than 2,654,763,889 therefore 175,895,570 must be shown as 18 instead of 177. In this way, the relative magnitudes of the two volumes can be understood. All numbers in the field of view must be truncated by the same order of magnitude to make the relative volumes understandable. The script attempts to calculate the order of magnitude value automatically. If you see a red number in the field of view it means the script has failed to do the calculation automatically and you should use the manual method – use the dialogue box “Calculate truncated wave value automatically or manually”. Scroll down from the automatic method and select manual. Once "manual" is selected the values displayed become the power values or multipliers for each wave.
Using the manual method you will select a “Multiplier” in the next dialogue box. Scan the field and select the largest value in the field of view (visible chart) is the multiplier of interest. If you select a lower number than the maximum value will see at least one red “up”. If you are too high you will see at least one red “down”. Scroll in the direction recommended or the values on the screen will be totally incorrect. With volume truncated to the highest order values, the eye can quickly get a feel for relative volumes. It also reduces the crowding and overlapping of values on the screen. You can opt to show the full volume to help get a sense of the magnitude of the true volumes.
How does the script determine if a Weis wave is continuing to grow or not?
The script evaluates the closing price of each new bar relative to the "Weis wave size". Suppose the current bar closes at a new low close, within the current down wave, at $30.00. If the Weis wave size is $0.10 then the algorithm will remember the $30.00 close and compare it to the close of the next bar. If the bar close price does not close equal to or lower than $30.00 or close equal to or higher than $30.10 then the wave is still a down wave with a current low of $30.00. This is true even if the bar low is less than $30.00 or the bar high is greater than 30.10 – only the bar’s closing price matters. If a bar's closing price climbs back up to a close of $30.11 then because the closing price has moved more than $0.10 (the Weis wave size) then that is a wave reversal with a new up-trending wave. In the above example if there was currently a downward trending wave and the bar closes were as follows $30.00, $30.09, $30.01, $30.05, $30.10 The wave direction would continue to stay downward trending until the close of $30.10 was achieved. As such $30.00 would be the low and the following closes $30.09, $30.01, $30.05 would be allocated to the new upward-trending wave. If however There was a series of bar closes like this $30.00, $30.09, $30.01, $30.05, $29.99 since none of the closes was equal to above the 10-cent reversal target of $30.10 but instead, a new Weis wave low was achieved ($29.99). As such the closes of $30.09, $30.01, $30.05 would all be attributed to the continued down-trending wave with a current low of $29.99, even though the closing price for the interim bars was above $30.00. Now that the Weis Wave low is now 429.99 then, in order to reverse this continued downtrend price will need to close at or above $30.09 on subsequent bar closes assuming now new low bar close is achieved. With large wave sizes, wave direction can be in limbo for many bars before a close either renews wave direction or reverses it and confirms wave direction as either a reversal or a continuation. On the zig-zag, a wave line and its volume will not be "printed" until a wave reversal is confirmed.
The wave attribution is similar when using other methods to define wave size. If ATR is used for wave size instead of a traditional wave constant size such as $0.10 or $2 or 2000 pips or ... then the wave size is calculated based on current ATR instead of the Weis wave constant (Traditional selected value).
I have the option to display pseudo-Ord volume. In truth, Ord used more traditional zig-zag pivots of bar highs and lows. Waves using closes as pivots can have some significant differences. This difference can be lessened by using smaller time frames and larger wave sizes.
There are other options such to display the delta price or pip size of a Weis Wave, the number of bars in a wave, and a few other options.