FRAMA & CPMA Strategy [CSM]The script is an advanced technical analysis tool specifically designed for trading in financial markets, with a particular focus on the BankNifty market. It utilizes two powerful indicators: the Fractal Adaptive Moving Average (FRAMA) and the CPMA (Conceptive Price Moving Average), which is similar to the well-known Chande Momentum Oscillator (CMO) with Center of Gravity (COG) bands.
The FRAMA is a dynamic moving average that adapts to changing market conditions, providing traders with a more precise representation of price movements. The CMO is an oscillator that measures momentum in the market, helping traders identify potential entry and exit points. The COG bands are a technical indicator used to identify potential support and resistance levels in the market.
Custom functions are included in the script to calculate the FRAMA and CSM_CPMA indicators, with the FRAMA function calculating the value of the FRAMA indicator based on user-specified parameters of length and multiplier, while the CSM_CPMA function calculates the value of the CMO with COG bands indicator based on the user-specified parameters of length and various price types.
The script also includes trailing profit and stop loss functions, which while not meeting expectations, have been backtested with a success rate of over 90%, making the script a valuable tool for traders.
Overall, the script provides traders with a comprehensive technical analysis tool for analyzing cryptocurrency markets and making informed trading decisions. Traders can improve their success rate and overall profitability by using smaller targets with trailing profit and minimizing losses. Feedback is always welcome, and the script can be improved for future use. Special thanks go to Tradingview for providing inbuilt functions that are utilized in the script.
Candlestick analysis
AI-Bank-Nifty Tech AnalysisThis code is a TradingView indicator that analyzes the Bank Nifty index of the Indian stock market. It uses various inputs to customize the indicator's appearance and analysis, such as enabling analysis based on the chart's timeframe, detecting bullish and bearish engulfing candles, and setting the table position and style.
The code imports an external script called BankNifty_CSM, which likely contains functions that calculate technical indicators such as the RSI, MACD, VWAP, and more. The code then defines several table cell colors and other styling parameters.
Next, the code defines a table to display the technical analysis of eight bank stocks in the Bank Nifty index. It then defines a function called get_BankComponent_Details that takes a stock symbol as input, requests the stock's OHLCV data, and calculates several technical indicators using the imported CSM_BankNifty functions.
The code also defines two functions called get_EngulfingBullish_Detection and get_EngulfingBearish_Detection to detect bullish and bearish engulfing candles.
Finally, the code calculates the technical analysis for each bank stock using the get_BankComponent_Details function and displays the results in the table. If the engulfing input is enabled, the code also checks for bullish and bearish engulfing candles and displays buy/sell signals accordingly.
The FRAMA stands for "Fractal Adaptive Moving Average," which is a type of moving average that adjusts its smoothing factor based on the fractal dimension of the price data. The fractal dimension reflects self-similarity at different scales. The FRAMA uses this property to adapt to the scale of price movements, capturing short-term and long-term trends while minimizing lag. The FRAMA was developed by John F. Ehlers and is commonly used by traders and analysts in technical analysis to identify trends and generate buy and sell signals. I tried to create this indicator in Pine.
In this context, "RS" stands for "Relative Strength," which is a technical indicator that compares the performance of a particular stock or market sector against a benchmark index.
The "Alligator" is a technical analysis tool that consists of three smoothed moving averages. Introduced by Bill Williams in his book "Trading Chaos," the three lines are called the Jaw, Teeth, and Lips of the Alligator. The Alligator indicator helps traders identify the trend direction and its strength, as well as potential entry and exit points. When the three lines are intertwined or close to each other, it indicates a range-bound market, while a divergence between them indicates a trending market. The position of the price in relation to the Alligator lines can also provide signals, such as a buy signal when the price crosses above the Alligator lines and a sell signal when the price crosses below them.
In addition to these, we have several other commonly used technical indicators, such as MACD, RSI, MFI (Money Flow Index), VWAP, EMA, and Supertrend. I used all the built-in functions for these indicators from TradingView. Thanks to the developer of this TradingView Indicator.
I also created a BankNifty Components Table and checked it on the dashboard.
Stophunt WickAcknowledgement
This indicator is dedicated to my friend Alexandru who saved me from one of these liquidation raids which almost liquidated me.
Alexandru is one of the best scalpers out there and he always nails his entries at the tip of these wicks.
This inspired me to create this indicator.
What's a Liquidation Wick?
It's that fast stop-hunting wick that stophunts everyone by triggering their stop-loss and liquidation.
Liquidity is the lifeblood of stock market and liquidation is the process that moves price.
This indicator will identify when a liquidity pool is getting raided to trigger buy or sell stops, they are also know as stop-hunts.
How does it work?
When market consolidates in one direction, it builds up liquidity zones.
Market maker will break out of these consolidation phases by having dramatic price action to either pump or dump to raid these liquidity zones.
This is also called stop-hunts or liquidity raids. After that it will start reversing back to the opposite direction.
This is most noticeable by the length of the wick of a given candle in a very short amount of time and the total size of the candle.
This indicator highlights them accordingly.
Settings
Wick and Candle ratio works with default values but finetune will enhance user experience and usability.
Wick Ratio: Size of the wick compared to body of a candle.
Adjust this to higher ratio on smaller timeframe or smaller ratio on bigger timeframe to your trading style to spot a trend reversal.
Candle Ratio: The size of the candle, by default it is 0.75% of the current price.
For example, if BTC is at 20,000 then the size of the candle has to be minimum 150.
This can be fine tuned to bigger candle size on higher time frames or smaller for shorter timeframe depending on the trade type.
How to use it?
This indicator will identify when a liquidity pool is getting raided to trigger buy or sell stops, they are also know as stop-hunts. It can be used of its own for scalping but there are also a good few indicators which would most definitely help to confluence bigger timeframe trades.
Scalp
This indicator shows the most chaotic moments in price action; therefore it works best on smaller timeframes, ideally 3 or 5 minute candle.
- Wait for the market to start pumping or dumping.
- Current candle will change colour (Bullish/Bearish).
- Enter trade as soon as price starts to reverse back.
- Place the stop-loss outside of the current candle.
- Wait for the Liquidation Wick to appear as confirmation.
Price is very chaotic during a liquidity stop-hunt raid but there is a saying:
"In the midst of chaos, there is also opportunity" - Sun-Tzu
Since this is a very high risk, high reward strategy; it is advised to practice on paper trade first.
Practice until perfection and this indicator would be the perfect bread and butter scalp confirmation.
Fair Value Gap
FVG strategy is the most accurate in conjunction with this indicator.
Normally price would reverse after consuming fair value gaps but often it's difficult to know when and where.
This indicator would identify those crucial entry points for reverse course direction of the price action.
Support and Resistance
This indicator can also be used in conjunction with support and resistance lines.
Generally the stophunt will go deep below the support or spike much further up the resistance lines to liquidate positions.
Bollinger Bands
Bolling Bands strategy would be to wait until the price breaks out of the band.
Once the wick is formed, it would be an ideal entry point.
Script change
This is an open-source script and feel free to modify according to your need and to amplify your existing strategy.
Height of Candle BodyUnderstanding the Height of Candlestick Body
Candlestick charts are a popular method of displaying price data in financial markets. They provide a visual representation of price movements and are used by traders to make informed decisions about buying and selling assets. Understanding the height of a candlestick body is an important aspect of technical analysis and can help traders identify trends and make profitable trades.
The height of a candlestick body is the distance between the opening and closing price of an asset over a given time period. When the closing price is higher than the opening price, the candlestick body is typically colored green or white and is considered bullish. Conversely, when the closing price is lower than the opening price, the candlestick body is typically colored red or black and is considered bearish.
The height of the candlestick body is important because it can provide valuable information about market sentiment. If the candlestick body is relatively small, it suggests that there is indecision in the market and that buyers and sellers are evenly matched. Conversely, if the candlestick body is relatively large, it suggests that there is a significant amount of buying or selling pressure in the market.
User Defined Momentum Change with Swing VisualsThis script is a groundbreaking, math-centric technical analysis tool that blends two well-established indicators, the Stochastic Oscillator and the Exponential Moving Average (EMA), to deliver a unique and visually engaging way of identifying momentum swings and stochastic indicators. Unlike mashups, this script is tailored to accommodate a wide range of trading strategies, providing traders with a distinctive perspective on market trends.
The innovation in this script lies in its mathematically-driven ability to effectively combine the Stochastic Oscillator and EMA, setting it apart from other available tools that simply offer a rehash of old ideas or slight modifications to popular indicators. The EMA is employed instead of a Simple Moving Average (SMA), enhancing the uniqueness of the calculations. This novel approach creates a new dimension for traders to evaluate potential momentum swings and visualize them on the chart, proving it to be more than just a mere mashup of existing indicators.
Central to the script's utility is its extensive customization options, which allow traders to adjust various inputs to suit their preferences and trading strategies. Users can modify the EMA length, swing range signal offsets, and smoothing factors for both the fast and slow components of the Stochastic Oscillator. Additionally, the script offers the ability to personalize the color thresholds, transparency, and line properties for the Stochastic Oscillator and swing range signal.
This script's visually dynamic representation of momentum swings empowers traders to make more informed trading decisions, particularly on the 6-hour timeframe. The swing range signal, represented by vertical lines on the chart, acts as a valuable visual aid for identifying potential entry or exit points. Furthermore, the Stochastic Oscillator provides insights into the strength and direction of momentum, which is beneficial for confirming potential trade signals.
To conclude, this script is not just another combination of MAs or a slightly modified version of a popular indicator. Instead, it offers traders a comprehensive, visually appealing, and customizable tool for technical analysis, which is both original and useful. By uniquely combining the EMA and the Stochastic Oscillator with a strong mathematical foundation, and allowing traders to adjust a variety of settings, this script adds value to the TradingView community and enhances the body of knowledge available for traders. It is designed to support traders in tailoring their analysis based on their own strategies and preferences, enabling them to make well-informed decisions in the financial markets.
ChArt Path"ChArt Path" shows the same datas as the candles, but as a channel, instead of individual candles.
It allows to focus on the direction of the price (instead of wondering the meaning of each candle), which hopefully simplifies the analysis, and reduces the confusion.
Also, it is artistically customizable!
A little time might be necessary to get used to this indicator.
NOTES FOR INSTALLATION:
- Japanese candles might be more expressive than Heiken Ashi, with this indicator.
- Hide the candles in the chart settings (right click on an empty space in the chart, then "Settings", "Symbol", and uncheck "Body", "Borders" and "Wick").
- Add "ChArt Path" to the chart.
- In the indicator's settings, choose the options you prefer. The Advanced setting are tuned by default for dark themes (bgcolor: black/#0a0c12). Feel free to make them your own!
HOW TO READ THE CHART?
- The path is between 2 borders (black by default) that represent the body of the candle (without the wicks).
- The wicks are represented around the path, as a gradient. This makes a price rejection very easy to spot, as a spike for ex.
SETTINGS
The standard settings are simple. You can pick 2 colors (bullish and bearish) for the path. And 1 color for the wicks.
The advanced settings let you customize the wicks' colors and opacity. You can also activate the gradient of volumes inside the path, to indicate the volume behind each candle.
HOW TO USE CHART PATH?
I use it on 2 timeframes (direction/entry), both with FREMA Trend (See below).
When there is a wick spike (price rejection), followed by an arrow signal in FREMA Trend, then there might be an opportunity. I look for confirmations from different origins, like volume, momentum, and cycles.
DO NOT BASE YOUR TRADING DECISIONS ON 1 SINGLE INDICATOR'S SIGNALS.
Always confirm your ideas by other means, like price action and indicators of a different nature.
NOTES ABOUT THE GRADIENT OF VOLUMES:
The more intense is the color, the bigger is the volume.
The unit is a 400 periods moving average of the volumes, considered as 1 volume.
Each color represents half of this volume. For ex: Grays indicate under (or equal) to the 400 MA (low volumes). Bright yellow represents above 7 times the 400 MA (very high volumes).
When there's no available volume datas, the candles turn bright green by default.
Reversal Points [CC]This original script was created based on a suggestion from @kerpiciwuasile. My original Reversal Points script was removed because I modeled it after an indicator by Demark, but this script will have no such issues. Reversal points are an exciting concept for me because it is such a useful tool when placing trades. This is my first attempt at a new overall layout for my script and I included a bunch of customization so let me know what you think.
My script works by finding lows that are surrounded by bars that have higher lows and highs that are surrounded by lower highs. I use this logic to find short term lows or highs and I use the same concept to find mid-term lows or highs but a mid-term high is a short term high surrounded by lower short term highs and a mid-term low is a short term low surrounded by higher short term lows. And of course this means that long term highs or lows use the same logic to find highs or lows that are surrounded by mid-term highs or lows. I would recommend to buy at the long term low points or sell at the long term high points.
Keep in mind of course that short term highs and lows are very common and reversal points will get rarer as you look for longer term reversal points. I would recommend to experiment and see which reversal points work best for you and of course, know that there is no magical formula to use for all stocks.
Also there are a few scenarios where you want to enable or disable the inside bar setting. You would want to ignore inside bars if the market is currently very volatile or if you are using this indicator on a crypto chart. This is not an exact science but more of a recommendation, so feel free to experiment with it.
Reversal points are crucial for traders as they signal a potential change in the market trend, providing opportunities for entry or exit.
In summary, this code snippet is a powerful tool for traders to detect and visualize reversal points on a trading chart, providing valuable insights into potential trend changes and facilitating more informed trading decisions.
Let me know if you would like me to publish other scripts or if you want me to do something custom for you!
Crypto Uptrend Script + Pullback//Volume CandlesDescription: his is an adaption of my Pullback candle - This works on all timeframes and Markets (Forex//Stocks//)
Crypto Uptrend Script with Pullback Candle allows traders to get into a trend when the price is at end of a pullback and entering a balance phase in the market (works on all markets). The use of Moving averages to help identify a Trends and the use of Key levels to help traders be aware of where strong areas are in the market.
This script can work really well in Crypto Bull Runs when used on HTF and with confluences
The script has key support and resistance zones which are made up of quarterly data. Price reacts to these areas but patience is required as price will take time to come into these areas
I have updated the Pullback Candle with the use of Volume to filter out the weak Pullback Candles -
There are new candles to the script.
The First candle is the Bullish Volume Candle - This candle is set to a multiplier of 2x with a crossover of 50/100 on Volume - this then will paint a purple candle.
Uses of the Bullish Volume Candle:
Breakthrough of key areas // special chart patterns
Rejection of key areas
End of a impulse wave (Profit Takers)
The second candle is a Hammer - I prefer using the Hammers on Higher Timeframes however they do work on all timeframes. .
The third candle is a Exhaustion of impulse downward move.
Uses of this candle - can denote a new trend but has to be with confluence to a demand area // support area or with any use of technical analysis - using this alone is not advised
The fourth candle is a indecision candle in the shape of a Doji - this candle can help identify if the trend is in a continuation or a reversal
This script can work really well in Crypto Bull Runs
Disclaimer: There will be Pullbacks with High Volume (Breakouts) and not go the way as intended but this script is to allow traders to get into trends at good price levels. The script can paint signals in areas where price is too expensive so please do your own due diligence on the markets as this script is to help get into good areas of price
Please leave a thumbs up if you like this script and message me for information on how to use the script.
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
Dual timeframe calculated candlesA script example to show how you can calculate the value of certain indicators from a higher timeframe at the moment that a bar closes on a shorter timeframe.
In this example the base chart is set to 5 mins and the multiplier is set to 6, so the HTF arrays hold data equivalent to that from the 30 minute chart which will hopefully appear below it on this display.
Each time a 5 minute bar completes, the arrays are updated by checking whether a new high or low has been set. The values for the HTF ATR and EMA are also updated by removing the most recent value from that array and replacing it with the value that would have been calculated based on the close at that time. As such for back testing purposes you'd know exactly what the 30 min chart would have been showing you at any one of the 5 minute intervals. Useful for backtesting strategies if you would rather act on the "up to the minute" HTF data, rather than the HTF data from the last HTF close, which could be significantly delayed if you're using a high enough multiplier.
Sunset candlesDisplays the volume behind each candle with colors, to visualise their evolution over time, directly in the chart.
This indicator is best suited for dark mode (Suggested background color: #0a0c12).
The more intense is the color, the bigger is the volume.
The unit is a 400 periods moving average of the volume, considered as 1 volume.
Each color represents half of this volume. For ex: Grays indicate under (or equal) to the 400 MA (low volumes). Bright yellow represents above 7 times the 400 MA (very high volumes).
When there's no available volume datas, the candles turn bright green by default.
The wicks' colors stay the same, and can still indicate the direction of the candle.
In the settings, you can show/hide the gradient of the volume. By moving your chart over this gradient, it is possible to compare the candles to the colors, and read the corresponding volume number.
Multi-Time Period Chart[1] 3 overlays w/ Halfbacks These are 3 High-Low ranges that uses the code of TradingView's built-in Multi-Time Period Chart indicator as well as adds on optional midpoint (or "halfback") to the overlays. Finally, there are labels offset on the right margin that indicate the open price for each of those timeframes. One thing I adjusted is that range of each timeframe is omitted. This is because the original TV indicator's boxes have their right edge completely covering the wicks (Thus, the title for this indicator). This script has plenty of utility, but it designed specifically with the STRAT (Rob Smith) methodology in mind.
Optimized Zhaocaijinbao strategyIntroduction:
The Optimized Zhaocaijinbao strategy is a mid and long-term quantitative trading strategy that combines momentum and trend factors. It generates buy and sell signals by using a combination of exponential moving averages, moving averages, volume and slope indicators. It generates buy signals when the stock is above the 35-day moving average, the trading volume is higher than the 20-day moving average, and the stock is in an upward trend on a weekly timeframe."招财进宝" is a Chinese phrase that can be translated to "Attract Wealth and Bring in Treasure" in English. It is a common expression used to wish for good luck and prosperity in various contexts, such as in business or personal finances.
Highlights:
The strategy has several special optimizations that make it unique.
Firstly, the strategy is optimized for T+1 trading in the Chinese stock market and is only suitable for long positions. The optimizations are also applicable to international stock markets.
Secondly, the trend strategy is optimized to only show indicators on the right side and oscillations. This helps to prevent false signals in choppy markets.
Thirdly, the strategy uses a risk factor for dynamic position sizing to ensure position sizes are adjusted according to the current net asset value and risk preferences. This helps to lower drawdown risks.
The strategy has good resilience even without using stop loss modules in backtesting, making it suitable for trading hourly, 2-hourly, and daily K-line charts (depending on the stock being traded). We recommend experimenting with backtesting using SSE 1-hour or 2-hour or daily Kline charts.
Backtesting outcomes:
The strategy was backtested over the period from October 13th, 2005 to April 14th, 2023, using daily candlestick charts for the commodity code SSE:600763, with a currency of CNY and tick size of 0.01. The strategy used an initial capital of 1,000,000 CNY, with order sizes set to 10% equity and a pyramid of 1 order. The strategy also had a Max Position Size of 0.01 and a Risk Factor of 2.
Here is a summary of the performance of the trading strategy:
Total net profit: 288,577.32 CNY, representing a return of 128.86%
Total number of closed trades: 61
Winning trades: 37, representing a win rate of 60.66%
Profit factor: 2.415
Largest losing trade: 222,021.46 CNY, representing a loss of 14.08%
Average trade: 21,124.22 CNY, representing a return of 3.1%
Average holding period for all trades: 12 days
Conclusion:
In conclusion, the Optimized Zhaocaijinbao strategy is a mid and long-term quantitative trading strategy that combines momentum and trend factors. It is suitable for both Chinese stocks and global stocks. While the Optimized Zhaocaijinbao strategy has performed well in backtesting, it is important to note that past performance is not a guarantee of future results. Traders should conduct their own research and analysis and exercise caution when using any trading strategy.
SuperCloudSupercloud is a MA based Trend Representation. Its different from a normal MA Cloud. Cloud starts from '0' level and rise or fall based on price.
Supercloud is plotted based on the difference of the price movement between various MA's of different length. All MA's are plotted with reference to EMA 200. So when the MA's converge or Diverge or Bounce back we can still be in the Trend unless the Cloud goes below or above Zero Line.
works in all Timeframes.
Up Trend:
-> All MA's are Above Zero and Cloud color is complete green
-> A decrease in Cloud Volume indicates a weaker Momentum
Down Trend:
-> All MA's are Below Zero and Cloud color is complete red
-> A decrease in Cloud Volume indicates a weaker Momentum
Sideways:
-> A Mixed color indicates a Sideways moment.
Cloud Outlines:
1) The outer edge of Cloud shows the actual trend.
2) its based on MA-5, when price is above MA 5 or Below MA 5 a bright green and bright red outlines are plotted.
Buy Signals Confirmation:
upper Outer Cloud must be Bright Green
Cloud under must be fully Shaded Green
Alternatively EMA crossover can be used and confirmed.
Sell Signals Confirmation:
lower Outer Cloud must be Bright Red
Cloud under must be fully Shaded Red
Alternatively EMA cross under can be used and confirmed.
MACD
MACD is also plotted within the cloud.
Color ribbon is used to plot MACD
Histogram is not present. Instead use the width of the MACD Ribbon
Correspondingly Outer Cloud represents the Histogram.
Zero Line:
Zero line is actually EMA5 which is to be treated as EMA200 for our visual representation.
A sideway channel is plotted around Zero line.
When price reaches this sideways Zone price usually get rejections and starts moving side ways.
Trend is established only after price crosses the sideway band.
Sideway is calculated based on mintick of the Asset which varies. a min value equivalent to 10EMA or value 10 must be used for better usage.
Market Relative Candle Ratio ComparatorIntroducing the Market Relative Candle Ratio Comparator, a visually captivating script that eases the way you compare two financial assets, such as cryptocurrencies and market indices. Leveraging a distinctive calculation method based on percentage changes and their averages, this tool presents a crystal-clear view of how your chosen assets perform in relation to each other, both for individual candles and over a range of previous candles.
Tailoring the script to your preferences is a walk in the park, as it allows you to easily adjust input symbols, moving average lengths, and other parameters to match your analytical approach. The visually arresting column chart it creates employs vivid red and green colors to underscore the differences between the two assets on each candle. Simultaneously, the lower-opacity columns depict the accumulated differences over a specified lookback period. This vibrant blend of colors and opacities results in a dynamic visual experience, enabling you to better grasp market trends relative to each other.
The reverse bool input is a handy feature that lets you invert the effect of the input symbol (DXY by default) in the comparison. When you set the reverse input to true, the script multiplies the calculated DXY percentage change by -1, effectively reversing the comparison. This is particularly useful when examining assets with an inverse relationship or when you'd like to analyze the input symbol's impact in the opposite direction.
For instance, if the input symbol represents a market index that generally moves in the opposite direction of the selected cryptocurrency, enabling the reverse input will help you better visualize and understand the relationship between the two assets by inverting the input symbol's effect on the comparison.
In the accompanying chart, you can observe the comparison of Bitcoin's movement relative to the Dollar, Gold, Bonds, and the S&P 500. The indicator reveals that in the last day, Bitcoin outperformed Bonds, Gold, and the Dollar but not the S&P 500!
Sushi Trend [HG]🍣 The Sushi Roll, a trading concept conceived at a restaurant by Mark Fisher.
While the indicator itself goes by Sushi Trend, it is completely backed by the idea of Mark Fisher's Sushi Roll Reversal Pattern. No, it has nothing to do with raw fish, it just so happens that somebody was ordering sushi during the discussion of the idea, and that's how it got its name.
📝 Origin
First mentioned in his book, The Logical Trader --- the idea of the Sushi Roll is to serve as an early warning system to identify reversals in the market. Fisher defines the pattern as a series of 10 bars, split into two different sections, seen as 5 and 5. In order for the pattern to be emitted, the 5 bars to the right must completely engulf the 5 bars to the left. It's not a super complex system and is in fact extremely simple to grasp.
📈 Supertrend Similarities
Instead of displaying the pattern in the way Fisher meant for it to be portrayed (as seen in the photo above), I instead turned it into an indicator similar to that of Supertrend while also inheriting the same concepts from the pattern. I did this because the pattern itself has inconsistencies which can be quite noticeable when trading with it after a while. For example, these patterns can occur even during consolidating periods, and even though the pattern is meant to be recognized during trending markets, the engulfing bars can sometimes be left with indecisive directions.
➡️ The Result
Here is the result, visualized to be better in a trending format. (The indicator will not contain the boxes.)
While Fisher does mention the pattern to include 10 bars, you can actually use this pattern with any number of bars. At the end of the day, it's a concept derived from a discussion at a Japanese restaurant, and a pattern that has been around for years that has seen results. Due to this, I added an input option to control the series of bars for right-bar engulf detection.
To reassure the meaning of the pattern --> "A series of 10 bars" means 5 left bars and 5 right bars. So if you want to check if 5 right bars are engulfing the previous 5 bars (as seen in the photo above), you would want to select 5 in the input settings.
You can learn more about it from the following links
Market Reversals and the Sushi Roll Technique
The Logical Trader
ADX Trend FilterADX Trend Filter Indicator is a traditional ADX indicator with a different presentation. its consist of two indicators EMA TREND and ADX / DMI
About Indicator:
1. BAND / EMA band to represent EMA Trend of EMA-12 and EMA-50
(Band is plotted at level-20 which is the Threshold level of DMI / ADX indicator)
2. Histogram showing the direction of ADX / DMI trend
3. Area behind the histogram showing ADX/DMI strength
How to use?
1. Histogram represents current Trend Red for Bearish / Green for Bullish
2. Area behind the histogram represents Strength of ADX / DMI Threshold level is 0-20(represented as band). (Area below the Band is Sideways)
3. Band represents the current MA Trend.
4. Buy Sell signals are plotted as triangles in red/green obtained from ADX / DMI Crossovers
Buy Signal (Green Triangle on band- ADX Crossover)
1.Band below Histogram must be Green
2.Histogram must be green
3.Area behind histogram must be above the lower trend band (20level) and visible
Sell Signal (Red Triangle on band- ADX Crossover)
1.Band below Histogram must be Red
2.Histogram must be Red
3.Area behind histogram must be above the lower trend band (20level) and visible
Alerts provided for ADX crossovers.
Adaptive Candlestick Pattern Recognition System█ INTRODUCTION
Nearly three years in the making, intermittently worked on in the few spare hours of weekends and time off, this is a passion project I undertook to flesh out my skills as a computer programmer. This script currently recognizes 85 different candlestick patterns ranging from one to five candles in length. It also performs statistical analysis on those patterns to determine prior performance and changes the coloration of those patterns based on that performance. In searching TradingView's script library for scripts similar to this one, I had found a handful. However, when I reviewed the ones which were open source, I did not see many that truly captured the power of PineScrypt or leveraged the way it works to create efficient and reliable code; one of the main driving factors for releasing this 5,000+ line behemoth open sourced.
Please take the time to review this description and source code to utilize this script to its fullest potential.
█ CONCEPTS
This script covers the following topics: Candlestick Theory, Trend Direction, Higher Timeframes, Price Analysis, Statistic Analysis, and Code Design.
Candlestick Theory - This script focuses solely on the concept of Candlestick Theory: arrangements of candlesticks may form certain patterns that can potentially influence the future price action of assets which experience those patterns. A full list of patterns (grouped by pattern length) will be in its own section of this description. This script contains two modes of operation for identifying candlestick patterns, 'CLASSIC' and 'BREAKOUT'.
CLASSIC: In this mode, candlestick patterns will be identified whenever they appear. The user has a wide variety of inputs to manipulate that can change how certain patterns are identified and even enable alerts to notify themselves when these patterns appear. Each pattern selected to appear will have their Profit or Loss (P/L) calculated starting from the first candle open succeeding the pattern to a candle close specified some number of candles ahead. These P/L calculations are then collected for each pattern, and split among partitions of prior price action of the asset the script is currently applied to (more on that in Higher Timeframes ).
BREAKOUT: In this mode, P/L calculations are held off until a breakout direction has been confirmed. The user may specify the number of candles ahead of a pattern's appearance (from one to five) that a pattern has to confirm a breakout in either an upward or downward direction. A breakout is constituted when there is a candle following the appearance of the pattern that closes above/at the highest high of the pattern, or below/at its lowest low. Only then will percent return calculations be performed for the pattern that's been identified, and these percent returns are broken up not only by the partition they had appeared in but also by the breakout direction itself. Patterns which do not breakout in either direction will be ignored, along with having their labels deleted.
In both of these modes, patterns may be overridden. Overrides occur when a smaller pattern has been detected and ends up becoming one (or more) of the candles of a larger pattern. A key example of this would be the Bearish Engulfing and the Three Outside Down patterns. A Three Outside Down necessitates a Bearish Engulfing as the first two candles in it, while the third candle closes lower. When a pattern is overridden, the return for that pattern will no longer be tracked. Overrides will not occur if the tail end of a larger pattern occurs at the beginning of a smaller pattern (Ex: a Bullish Engulfing occurs on the third candle of a Three Outside Down and the candle immediately following that pattern, the Three Outside Down pattern will not be overridden).
Important Functionality Note: These patterns are only searched for at the most recently closed candle, not on the currently closing candle, which creates an offset of one for this script's execution. (SEE LIMITATIONS)
Trend Direction - Many of the patterns require a trend direction prior to their appearance. Noting TradingView's own publication of candlestick patterns, I utilize a similar method for determining trend direction. Moving Averages are used to determine which trend is currently taking place for candlestick patterns to be sought out. The user has access to two Moving Averages which they may individually modify the following for each: Moving Average type (list of 9), their length, width, source values, and all variables associated with two special Moving Averages (Least Squares and Arnaud Legoux).
There are 3 settings for these Moving Averages, the first two switch between the two Moving Averages, and the third uses both. When using individual Moving Averages, the user may select a 'price point' to compare against the Moving Average (default is close). This price point is compared to the Moving Average at the candles prior to the appearance of candle patterns. Meaning: The close compared to the Moving Average two candles behind determines the trend direction used for Candlestick Analysis of one candle patterns; three candles behind for two candle patterns and so on. If the selected price point is above the Moving Average, then the current trend is an 'uptrend', 'downtrend' otherwise.
The third setting using both Moving Averages will compare the lengths of each, and trend direction is determined by the shorter Moving Average compared to the longer one. If the shorter Moving Average is above the longer, then the current trend is an 'uptrend', 'downtrend' otherwise. If the lengths of the Moving Averages are the same, or both Moving Averages are Symmetrical, then MA1 will be used by default. (SEE LIMITATIONS)
Higher Timeframes - This script employs the use of Higher Timeframes with a few request.security calls. The purpose of these calls is strictly for the partitioning of an asset's chart, splitting the returns of patterns into three separate groups. The four inputs in control of this partitioning split the chart based on: A given resolution to grab values from, the length of time in that resolution, and 'Upper' and 'Lower Limits' which split the trading range provided by that length of time in that resolution that forms three separate groups. The default values for these four inputs will partition the current chart by the yearly high-low range where: the 'Upper' partition is the top 20% of that trading range, the 'Middle' partition is 80% to 33% of the trading range, and the 'Lower' partition covers the trading range within 33% of the yearly low.
Patterns which are identified by this script will have their returns grouped together based on which partition they had appeared in. For example, a Bullish Engulfing which occurs within a third of the yearly low will have its return placed separately from a Bullish Engulfing that occurred within 20% of the yearly high. The idea is that certain patterns may perform better or worse depending on when they had occurred during an asset's trading range.
Price Analysis - Price Analysis is a major part of this script's functionality as it can fundamentally change how patterns are shown to the user. The settings related to Price Analysis include setting the number of candles ahead of a pattern's appearance to determine the return of that pattern. In 'BREAKOUT' mode, an additional setting allows the user to specify where the P/L calculation will begin for a pattern that had appeared and confirmed. (SEE LIMITATIONS)
The calculation for percent returns of patterns is illustrated with the following pseudo-code (CLASSIC mode, this is a simplified version of the actual code):
type patternObj
int ID
int partition
type returnsArray
float returns
// No pattern found = na returned
patternObj TEST_VAL = f_FindPattern()
priorTestVal = TEST_VAL
if not na( priorTestVal )
pnlMatrixRow = priorTestVal.ID
pnlMatrixCol = priorTestVal.partition
matrixReturn = matrix.get(PERCENT_RETURNS, pnlMatrixRow, pnlMatrixCol)
percentReturn = ( (close - open ) / open ) * 100%
array.push(matrixReturn.returns, percentReturn)
Statistic Analysis - This script uses Pine's built-in array functions to conduct the Statistic Analysis for patterns. When a pattern is found and its P/L calculation is complete, its return is added to a 'Return Array' User-Defined-Type that contains numerous fields which retain information on a pattern's prior performance. The actual UDT is as follows:
type returnArray
float returns = na
int size = 0
float avg = 0
float median = 0
float stdDev = 0
int polarities = na
All values within this UDT will be updated when a return is added to it (some based on user input). The array.avg , array.median and array.stdev will be ran and saved into their respective fields after a return is placed in the 'returns' array. The 'polarities' integer array is what will be changed based on user input. The user specifies two different percentages that declare 'Positive' and 'Negative' returns for patterns. When a pattern returns above, below, or in between these two values, different indices of this array will be incremented to reflect the kind of return that pattern had just experienced.
These values (plus the full name, partition the pattern occurred in, and a 95% confidence interval of expected returns) will be displayed to the user on the tooltip of the labels that identify patterns. Simply scroll over the pattern label to view each of these values.
Code Design - Overall this script is as much of an art piece as it is functional. Its design features numerous depictions of ASCII Art that illustrate what is being attempted by the functions that identify patterns, and an incalculable amount of time was spent rewriting portions of code to improve its efficiency. Admittedly, this final version is nearly 1,000 lines shorter than a previous version (one which took nearly 30 seconds after compilation to run, and didn't do nearly half of what this version does). The use of UDTs, especially the 'patternObj' one crafted and redesigned from the Hikkake Hunter 2.0 I published last month, played a significant role in making this script run efficiently. There is a slight rigidity in some of this code mainly around pattern IDs which are responsible for displaying the abbreviation for patterns (as well as the full names under the tooltips, and the matrix row position for holding returns), as each is hard-coded to correspond to that pattern.
However, one thing I would like to mention is the extensive use of global variables for pattern detection. Many scripts I had looked over for ideas on how to identify candlestick patterns had the same idea; break the pattern into a set of logical 'true/false' statements derived from historically referencing candle OHLC values. Some scripts which identified upwards of 20 to 30 patterns would reference Pine's built-in OHLC values for each pattern individually, potentially requesting information from TradingView's servers numerous times that could easily be saved into a variable for re-use and only requested once per candle (what this script does).
█ FEATURES
This script features a massive amount of switches, options, floating point values, detection settings, and methods for identifying/tailoring pattern appearances. All modifiable inputs for patterns are grouped together based on the number of candles they contain. Other inputs (like those for statistics settings and coloration) are grouped separately and presented in a way I believe makes the most sense.
Not mentioned above is the coloration settings. One of the aims of this script was to make patterns visually signify their behavior to the user when they are identified. Each pattern has its own collection of returns which are analyzed and compared to the inputs of the user. The user may choose the colors for bullish, neutral, and bearish patterns. They may also choose the minimum number of patterns needed to occur before assigning a color to that pattern based on its behavior; a color for patterns that have not met this minimum number of occurrences yet, and a color for patterns that are still processing in BREAKOUT mode.
There are also an additional three settings which alter the color scheme for patterns: Statistic Point-of-Reference, Adaptive coloring, and Hard Limiting. The Statistic Point-of-Reference decides which value (average or median) will be compared against the 'Negative' and 'Positive Return Tolerance'(s) to guide the coloration of the patterns (or for Adaptive Coloring, the generation of a color gradient).
Adaptive Coloring will have this script produce a gradient that patterns will be colored along. The more bullish or bearish a pattern is, the further along the gradient those patterns will be colored starting from the 'Neutral' color (hard lined at the value of 0%: values above this will be colored bullish, bearish otherwise). When Adaptive Coloring is enabled, this script will request the highest and lowest values (these being the Statistic Point-of-Reference) from the matrix containing all returns and rewrite global variables tied to the negative and positive return tolerances. This means that all patterns identified will be compared with each other to determine bullish/bearishness in Adaptive Coloring.
Hard Limiting will prevent these global variables from being rewritten, so patterns whose Statistic Point-of-Reference exceed the return tolerances will be fully colored the bullish or bearish colors instead of a generated gradient color. (SEE LIMITATIONS)
Apart from the Candle Detection Modes (CLASSIC and BREAKOUT), there's an additional two inputs which modify how this script behaves grouped under a "MASTER DETECTION SETTINGS" tab. These two "Pattern Detection Settings" are 'SWITCHBOARD' and 'TARGET MODE'.
SWITCHBOARD: Every single pattern has a switch that is associated with its detection. When a switch is enabled, the code which searches for that pattern will be run. With the Pattern Detection Setting set to this, all patterns that have their switches enabled will be sought out and shown.
TARGET MODE: There is an additional setting which operates on top of 'SWITCHBOARD' that singles out an individual pattern the user specifies through a drop down list. The names of every pattern recognized by this script will be present along with an identifier that shows the number of candles in that pattern (Ex: " (# candles)"). All patterns enabled in the switchboard will still have their returns measured, but only the pattern selected from the "Target Pattern" list will be shown. (SEE LIMITATIONS)
The vast majority of other features are held in the one, two, and three candle pattern sections.
For one-candle patterns, there are:
3 — Settings related to defining 'Tall' candles:
The number of candles to sample for previous candle-size averages.
The type of comparison done for 'Tall' Candles: Settings are 'RANGE' and 'BODY'.
The 'Tolerance' for tall candles, specifying what percent of the 'average' size candles must exceed to be considered 'Tall'.
When 'Tall Candle Setting' is set to RANGE, the high-low ranges are what the current candle range will be compared against to determine if a candle is 'Tall'. Otherwise the candle bodies (absolute value of the close - open) will be compared instead. (SEE LIMITATIONS)
Hammer Tolerance - How large a 'discarded wick' may be before it disqualifies a candle from being a 'Hammer'.
Discarded wicks are compared to the size of the Hammer's candle body and are dependent upon the body's center position. Hammer bodies closer to the high of the candle will have the upper wick used as its 'discarded wick', otherwise the lower wick is used.
9 — Doji Settings, some pulled from an old Doji Hunter I made a while back:
Doji Tolerance - How large the body of a candle may be compared to the range to be considered a 'Doji'.
Ignore N/S Dojis - Turns off Trend Direction for non-special Dojis.
GS/DF Doji Settings - 2 Inputs that enable and specify how large wicks that typically disqualify Dojis from being 'Gravestone' or 'Dragonfly' Dojis may be.
4 Settings related to 'Long Wick Doji' candles detailed below.
A Tolerance for 'Rickshaw Man' Dojis specifying how close the center of the body must be to the range to be valid.
The 4 settings the user may modify for 'Long Legged' Dojis are: A Sample Base for determining the previous average of wicks, a Sample Length specifying how far back to look for these averages, a Behavior Setting to define how 'Long Legged' Dojis are recognized, and a tolerance to specify how large in comparison to the prior wicks a Doji's wicks must be to be considered 'Long Legged'.
The 'Sample Base' list has two settings:
RANGE: The wicks of prior candles are compared to their candle ranges and the 'wick averages' will be what the average percent of ranges were in the sample.
WICKS: The size of the wicks themselves are averaged and returned for comparing against the current wicks of a Doji.
The 'Behavior' list has three settings:
ONE: Only one wick length needs to exceed the average by the tolerance for a Doji to be considered 'Long Legged'.
BOTH: Both wick lengths need to exceed the average of the tolerance of their respective wicks (upper wicks are compared to upper wicks, lower wicks compared to lower) to be considered 'Long Legged'.
AVG: Both wicks and the averages of the previous wicks are added together, divided by two, and compared. If the 'average' of the current wicks exceeds this combined average of prior wicks by the tolerance, then this would constitute a valid 'Long Legged' Doji. (For Dojis in general - SEE LIMITATIONS)
The final input is one related to candle patterns which require a Marubozu candle in them. The two settings for this input are 'INCLUSIVE' and 'EXCLUSIVE'. If INCLUSIVE is selected, any opening/closing variant of Marubozu candles will be allowed in the patterns that require them.
For two-candle patterns, there are:
2 — Settings which define 'Engulfing' parameters:
Engulfing Setting - Two options, RANGE or BODY which sets up how one candle may 'engulf' the previous.
Inclusive Engulfing - Boolean which enables if 'engulfing' candles can be equal to the values needed to 'engulf' the prior candle.
For the 'Engulfing Setting':
RANGE: If the second candle's high-low range completely covers the high-low range of the prior candle, this is recognized as 'engulfing'.
BODY: If the second candle's open-close completely covers the open-close of the previous candle, this is recognized as 'engulfing'. (SEE LIMITATIONS)
4 — Booleans specifying different settings for a few patterns:
One which allows for 'opens within body' patterns to let the second candle's open/close values match the prior candles' open/close.
One which forces 'Kicking' patterns to have a gap if the Marubozu setting is set to 'INCLUSIVE'.
And Two which dictate if the individual candles in 'Stomach' patterns need to be 'Tall'.
8 — Floating point values which affect 11 different patterns:
One which determines the distance the close of the first candle in a 'Hammer Inverted' pattern must be to the low to be considered valid.
One which affects how close the opens/closes need to be for all 'Lines' patterns (Bull/Bear Meeting/Separating Lines).
One that allows some leeway with the 'Matching Low' pattern (gives a small range the second candle close may be within instead of needing to match the previous close).
Three tolerances for On Neck/In Neck patterns (2 and 1 respectively).
A tolerance for the Thrusting pattern which give a range the close the second candle may be between the midpoint and close of the first to be considered 'valid'.
A tolerance for the two Tweezers patterns that specifies how close the highs and lows of the patterns need to be to each other to be 'valid'.
The first On Neck tolerance specifies how large the lower wick of the first candle may be (as a % of that candle's range) before the pattern is invalidated. The second tolerance specifies how far up the lower wick to the close the second candle's close may be for this pattern. The third tolerance for the In Neck pattern determines how far into the body of the first candle the second may close to be 'valid'.
For the remaining patterns (3, 4, and 5 candles), there are:
3 — Settings for the Deliberation pattern:
A boolean which forces the open of the third candle to gap above the close of the second.
A tolerance which changes the proximity of the third candle's open to the second candle's close in this pattern.
A tolerance that sets the maximum size the third candle may be compared to the average of the first two candles.
One boolean value for the Two Crows patterns (standard and Upside Gapping) that forces the first two candles in the patterns to completely gap if disabled (candle 1's close < candle 2's low).
10 — Floating point values for the remaining patterns:
One tolerance for defining how much the size of each candle in the Identical Black Crows pattern may deviate from the average of themselves to be considered valid.
One tolerance for setting how close the opens/closes of certain three candle patterns may be to each other's opens/closes.*
Three floating point values that affect the Three Stars in the South pattern.
One tolerance for the Side-by-Side patterns - looks at the second and third candle closes.
One tolerance for the Stick Sandwich pattern - looks at the first and third candle closes.
A floating value that sizes the Concealing Baby Swallow pattern's 3rd candle wick.
Two values for the Ladder Bottom pattern which define a range that the third candle's wick size may be.
* This affects the Three Black Crows (non-identical) and Three White Soldiers patterns, each require the opens and closes of every candle to be near each other.
The first tolerance of the Three Stars in the South pattern affects the first candle body's center position, and defines where it must be above to be considered valid. The second tolerance specifies how close the second candle must be to this same position, as well as the deviation the ratio the candle body to its range may be in comparison to the first candle. The third restricts how large the second candle range may be in comparison to the first (prevents this pattern from being recognized if the second candle is similar to the first but larger).
The last two floating point values define upper and lower limits to the wick size of a Ladder Bottom's fourth candle to be considered valid.
█ HOW TO USE
While there are many moving parts to this script, I attempted to set the default values with what I believed may help identify the most patterns within reasonable definitions. When this script is applied to a chart, the Candle Detection Mode (along with the BREAKOUT settings) and all candle switches must be confirmed before patterns are displayed. All switches are on by default, so this gives the user an opportunity to pick which patterns to identify first before playing around in the settings.
All of the settings/inputs described above are meant for experimentation. I encourage the user to tweak these values at will to find which set ups work best for whichever charts they decide to apply these patterns to.
Refer to the patterns themselves during experimentation. The statistic information provided on the tooltips of the patterns are meant to help guide input decisions. The breadth of candlestick theory is deep, and this was an attempt at capturing what I could in its sea of information.
█ LIMITATIONS
DISCLAIMER: While it may seem a bit paradoxical that this script aims to use past performance to potentially measure future results, past performance is not indicative of future results . Markets are highly adaptive and often unpredictable. This script is meant as an informational tool to show how patterns may behave. There is no guarantee that confidence intervals (or any other metric measured with this script) are accurate to the performance of patterns; caution must be exercised with all patterns identified regardless of how much information regarding prior performance is available.
Candlestick Theory - In the name, Candlestick Theory is a theory , and all theories come with their own limits. Some patterns identified by this script may be completely useless/unprofitable/unpredictable regardless of whatever combination of settings are used to identify them. However, if I truly believed this theory had no merit, this script would not exist. It is important to understand that this is a tool meant to be utilized with an array of others to procure positive (or negative, looking at you, short sellers ) results when navigating the complex world of finance.
To address the functionality note however, this script has an offset of 1 by default. Patterns will not be identified on the currently closing candle, only on the candle which has most recently closed. Attempting to have this script do both (offset by one or identify on close) lead to more trouble than it was worth. I personally just want users to be aware that patterns will not be identified immediately when they appear.
Trend Direction - Moving Averages - There is a small quirk with how MA settings will be adjusted if the user inputs two moving averages of the same length when the "MA Setting" is set to 'BOTH'. If Moving Averages have the same length, this script will default to only using MA 1 regardless of if the types of Moving Averages are different . I will experiment in the future to alleviate/reduce this restriction.
Price Analysis - BREAKOUT mode - With how identifying patterns with a look-ahead confirmation works, the percent returns for patterns that break out in either direction will be calculated on the same candle regardless of if P/L Offset is set to 'FROM CONFIRMATION' or 'FROM APPEARANCE'. This same issue is present in the Hikkake Hunter script mentioned earlier. This does not mean the P/L calculations are incorrect , the offset for the calculation is set by the number of candles required to confirm the pattern if 'FROM APPEARANCE' is selected. It just means that these two different P/L calculations will complete at the same time independent of the setting that's been selected.
Adaptive Coloring/Hard Limiting - Hard Limiting is only used with Adaptive Coloring and has no effect outside of it. If Hard Limiting is used, it is recommended to increase the 'Positive' and 'Negative' return tolerance values as a pattern's bullish/bearishness may be disproportionately represented with the gradient generated under a hard limit.
TARGET MODE - This mode will break rules regarding patterns that are overridden on purpose. If a pattern selected in TARGET mode would have otherwise been absorbed by a larger pattern, it will have that pattern's percent return calculated; potentially leading to duplicate returns being included in the matrix of all returns recognized by this script.
'Tall' Candle Setting - This is a wide-reaching setting, as approximately 30 different patterns or so rely on defining 'Tall' candles. Changing how 'Tall' candles are defined whether by the tolerance value those candles need to exceed or by the values of the candle used for the baseline comparison (RANGE/BODY) can wildly affect how this script functions under certain conditions. Refer to the tooltip of these settings for more information on which specific patterns are affected by this.
Doji Settings - There are roughly 10 or so two to three candle patterns which have Dojis as a part of them. If all Dojis are disabled, it will prevent some of these larger patterns from being recognized. This is a dependency issue that I may address in the future.
'Engulfing' Setting - Functionally, the two 'Engulfing' settings are quite different. Because of this, the 'RANGE' setting may cause certain patterns that would otherwise be valid under textbook and online references/definitions to not be recognized as such (like the Upside Gap Two Crows or Three Outside down).
█ PATTERN LIST
This script recognizes 85 patterns upon initial release. I am open to adding additional patterns to it in the future and any comments/suggestions are appreciated. It recognizes:
15 — 1 Candle Patterns
4 Hammer type patterns: Regular Hammer, Takuri Line, Shooting Star, and Hanging Man
9 Doji Candles: Regular Dojis, Northern/Southern Dojis, Gravestone/Dragonfly Dojis, Gapping Up/Down Dojis, and Long-Legged/Rickshaw Man Dojis
White/Black Long Days
32 — 2 Candle Patterns
4 Engulfing type patterns: Bullish/Bearish Engulfing and Last Engulfing Top/Bottom
Dark Cloud Cover
Bullish/Bearish Doji Star patterns
Hammer Inverted
Bullish/Bearish Haramis + Cross variants
Homing Pigeon
Bullish/Bearish Kicking
4 Lines type patterns: Bullish/Bearish Meeting/Separating Lines
Matching Low
On/In Neck patterns
Piercing pattern
Shooting Star (2 Lines)
Above/Below Stomach patterns
Thrusting
Tweezers Top/Bottom patterns
Two Black Gapping
Rising/Falling Window patterns
29 — 3 Candle Patterns
Bullish/Bearish Abandoned Baby patterns
Advance Block
Collapsing Doji Star
Deliberation
Upside/Downside Gap Three Methods patterns
Three Inside/Outside Up/Down patterns (4 total)
Bullish/Bearish Side-by-Side patterns
Morning/Evening Star patterns + Doji variants
Stick Sandwich
Downside/Upside Tasuki Gap patterns
Three Black Crows + Identical variation
Three White Soldiers
Three Stars in the South
Bullish/Bearish Tri-Star patterns
Two Crows + Upside Gap variant
Unique Three River Bottom
3 — 4 Candle Patterns
Concealing Baby Swallow
Bullish/Bearish Three Line Strike patterns
6 — 5 Candle Patterns
Bullish/Bearish Breakaway patterns
Ladder Bottom
Mat Hold
Rising/Falling Three Methods patterns
█ WORKS CITED
Because of the amount of time needed to complete this script, I am unable to provide exact dates for when some of these references were used. I will also not provide every single reference, as citing a reference for each individual pattern and the place it was reviewed would lead to a bibliography larger than this script and its description combined. There were five major resources I used when building this script, one book, two websites (for various different reasons including patterns, moving averages, and various other articles of information), various scripts from TradingView's public library (including TradingView's own source code for *all* candle patterns ), and PineScrypt's reference manual.
Bulkowski, Thomas N. Encyclopedia of Candlestick Patterns . Hoboken, New Jersey: John Wiley & Sons Inc., 2008. E-book (google books).
Various. Numerous webpages. CandleScanner . 2023. online. Accessed 2020 - 2023.
Various. Numerous webpages. Investopedia . 2023. online. Accessed 2020 - 2023.
█ AKNOWLEDGEMENTS
I want to take the time here to thank all of my friends and family, both online and in real life, for the support they've given me over the last few years in this endeavor. My pets who tried their hardest to keep me from completing it. And work for the grit to continue pushing through until this script's completion.
This belongs to me just as much as it does anyone else. Whether you are an institutional trader, gold bug hedging against the dollar, retail ape who got in on a squeeze, or just parents trying to grow their retirement/save for the kids. This belongs to everyone.
Private Beta for new features to be tested can be found here .
Vires In Numeris
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.
Inversion GapsAn inverted fair value gap (FVG) occurs when candles start closing below a bullish FVG or above a bearish FVG and in this case, support FVGs become resistances and vice versa. This is a smart money concept introduced by ICT. While we a number of have indicators for FVGs, we don't have any for inversion FVGs. This indicator is just for that - it shows FVGs only after they're inverted.
The meat of it comes from being able to plot HTF inverted FVGs in LTF. In the above BTC chart, you can see M15 inverted FVGs plotted on M1 chart and you can see price respecting them. Mitigations can also be shown as lines (as you can see in the chart).
You can also setup alerts for formation and mitigation of such inversion FVGs.
NSDT Fair Value GapThis script is our version of the "Fair Value Gap".
A Fair Value Gap is nothing more than a series of 3 candles with a gap between a candle high/low and a candle high/low two candles prior.
For example:
A Gap Up - the Low of a candle is higher than the High of two candles back.
A Gap Down - the High of a candle is lower than the Low of two candles back.
Typically, on a Gap Up, the trader would wait for the price to re-enter the Gap, and take a Long position.
Typically, on a Gap Down, the trader would wait for the price to re-enter the Gap, and take a Short position.
We found that simply trading through the Gaps (fill the gap) produced a better result. So we reversed the procedure and the colors to show our suggested direction.
We have added inputs so the trader can determine the size of the Gaps to be plotted on the chart. A minimum and maximum can be set.
The number of Gaps to be displayed can be adjusted.
There is a option to remove Gaps that had been filled, to help keep a clean chart.
Fair Value Gap - FVG - HistogramThis indicator uses a histogram to represent "fair value gaps" ("FVG"). FVG is a popular pattern among modern traders.
This document describes the purpose of the script and discusses the conceptual meaning of "fair value," as well as the connotations attached to it.
█🚀 Based on the previous script - improved clarity
This indicator is a modified version of the "Three Bar Gap (Simple Price Action - with 1 line plot)" indicator, which is also available as open source and can be applied to a chart as a complementary tool along with this indicator.
Differences:
The previous version introduced a "Threshold filter" to reduce the number of lines plotted on charts. This filter introduced two additional parameters for users to consider (ATR length and multiplier). These parameters made the indicator more complicated than intended.
To address this issue of having too many lines in the former version, I proposed a spin-off on this version: It's to consider plotting the magnitude of the FVGs on a histogram instead of using lines on a price chart. In my opinion, a histogram is more suitable for decision-making because it lays out data points side-by-side as bins, which makes comparisons much clearer.
Minor FVGs are expected to have smaller bins compared to their neighboring bins, and in extreme cases, the bins will become seemingly invisible due to the auto-adjusted scale of the y-axis. Therefore, there is no need to filter out any data, and all FVGs can be included in this spin-off version.
█🚀 Candlestick patterns - revisited
This script calculates the displacement of highs and lows over three consecutive bars.
A) Down move: When the high of the recent-confirmed bar is lower than the low of the previous-previous candle.
B) Up move: When the low of the recently-confirmed bar is higher than the high of the previous-previous candle.
█🚀 Parameters
Core Functionality
The purpose of this indicator is to generate bins representing the magnitude of FVGs in the form of a histogram to facilitate the visualization of price movements.
The act of "finding FVGs" does not require any inputs, but users can still customize the colors of the bins to indicate the direction of movement.
Auxiliary functionality: “Key level finder” by searching for large FVGs
The following inputs are optional, in fact, the entire feature can be toggled on/off.
In this example, setting the lookback at 20 means the script will generate a signal if the current histogram bin is taller than all previous bins over the past 20 bars.
█🚀 Applications
Tall histogram bins = key levels .
Traders should observe key levels for entry or exit opportunities.
It is important to note that this indicator was designed for standard time-based charts.
On a separate note, FVGs will not appear in Renko charts with fixed-size bricks. This is because the bricks align with their neighboring bricks. When the bricks are fixed, any displacement between highs and lows within less than or equal to three bars will be zero.
The concept of a "gap" is used to illustrate that price follows a jump-diffusion process, and time intervals can be assigned arbitrarily on the x-axis without needing fixed intervals. This idea was briefly discussed in the previous script's write-up.
█🚀 FAQ: Does it repaint?
No. And please continue reading.
Bins are plotted with a one-bar delay. It only takes one bar for the FVG to become confirmed. Lag is beneficial because it clarifies the need for traders to wait for the bar to close and for the signals to become confirmed before entering or exiting a trade. Experienced traders know that prices tend to retrace, so there is no need to chase. An added bar of delay proves to be useful.
█🚀 Opinion: The term “fair value” can be misleading
Those who come from traditional finance may find the term "fair value gap" somewhat insulting. When encountering the phrase, it can feel like a group of aliens from "Planet Technical Analysis" have intrusively landed on your planet and assertively redefined what "fair value" is supposed to mean.
So, what does "fair value" mean in the realm of technical analysis?
In the world of corporate finance, "fair value" is a subjective estimate of what buyers and sellers are hypothetically willing to pay or accept. Buy-side and sell-side analysts use their own methodologies to determine what constitutes "fair value". These approaches may be based on income, asset, or market comparables. Regardless of the approach used, subjectivity is inherent, and results depend on fundamental data provided by the numbers on financial statements. Valuations are unrelated to candlestick patterns .
When dealing with financial statements, finance professionals who are non-market-participants, such as those working in group reporting practices for reporting issuers, or those hired as external auditors, as required by regulators, may also question what constitutes "fair value". The main concerns always revolve around the assumptions used in valuation models; these are inputs that ultimately require management's judgment, and if not critically questioned, valuations as reported in the statements could end up becoming materially bogus. Both IFRS and U.S. GAAP define "fair value" with the same intended meaning in terms of definitions. We will not delve into the details here. The main point is that "fair value" from a financial reporting perspective has nothing to do with candlesticks .
If a price is already quoted in an actively traded market, you can refer to it to obtain what is known as "mark-to-market". This involves simply referring to the bid or ask price on the reporting date, and you're done - there's no need to read candlesticks !
"Fair value" is a neutral term used by finance professionals in all domains. It is not meant to imply that something is actually "fair." Paying the "fair value" for an asset can still result in overpaying or underpaying for what the asset is worth, depending on different model assumptions. The point is, candlesticks are irrelevant to the analysis of what is considered "fair value" in the realm of traditional finance.
That being said, there is no definitive answer as to why people refer to this pattern as a "fair value gap". It's like one of those oddball interview questions asking you to explain why tennis balls are fuzzy. Whatever answer you give, it's important to note that the subject itself is trivial.
Emphasis of matter on why "fair value" can be misleading
The previous paragraphs were not intended to attack ideas from the realm of technical analysis, nor to assert the true meaning, or lack of meaning, of the term "fair value". Words are constantly evolving. If the term "fair value gap" becomes more widely used to describe the displacement of highs and lows over three bars, then let's call it a "fair value gap".
To be clear, I argue that the term "fair value gap" should not be given a positive connotation. Traders should interpret the word "fair" neutrally. Although these signals occur frequently, if you trade every time there is a signal, you will overtrade and incur astronomical transaction costs over the long run, which can lead to losses.
█🚀 Conclusion:
In the end, what matters is how you apply FVG to trading. As mentioned in the "Applications" section above, traders should look for large FVGs - indicated by tall histogram bins - to identify key levels.
Probability of Candle Close Higher Than OpenThe "Probability of Candle Close Higher Than Open" indicator is designed to help traders assess the likelihood of a given candle closing higher than its open based on the previous candle's price action. It does this by calculating a probability score between 0 and 1 and displaying it on the chart, along with a horizontal line representing a user-defined probability threshold.
The indicator uses three input variables to determine the probability score:
lookback_period: This input defines the number of previous candles to consider when calculating the probability. By default, it is set to 2, meaning the indicator considers the previous two candles.
prev_high and prev_low: These variables are calculated using the highest() and lowest() functions, respectively, and represent the highest high and lowest low of the previous lookback_period candles.
prev_body: This variable calculates the absolute value of the difference between the open and close prices of the previous candle.
The probability score is then calculated based on the following conditions:
If the current candle's open price is higher than the previous lookback_period candles' highest high, the probability score is set to 0.1 (indicating a low probability of the candle closing higher than its open).
If the current candle's open price is lower than the previous lookback_period candles' lowest low, the probability score is set to 0.9 (indicating a high probability of the candle closing higher than its open).
If neither of the above conditions apply, the probability score is calculated using the following formula:
If the previous candle closed higher than its open, the probability score is set to 0.5 plus half of the previous candle's body (i.e., the absolute difference between its open and close prices).
If the previous candle closed lower than its open, the probability score is set to 0.1 plus half of the previous candle's body.
If the previous candle closed at the same price as its open, the probability score is set to 0.1.
Finally, the indicator plots the probability score as a label on the chart and a horizontal line representing the probability threshold.
Disclaimer:
Trading involves significant risk and is not suitable for all investors. The "Probability of Candle Close Higher Than Open" indicator is for informational purposes only and should not be used as the sole basis for making trading decisions. Always conduct your own research and due diligence before entering any trades. No guarantee or warranty is given as to the accuracy or completeness of the information provided by this indicator, and any reliance on this information is at your own risk. Past performance is not necessarily indicative of future results. Trading with margin carries the risk of losing more than your initial investment. Only trade with risk capital that you can afford to lose.