Higher TimeFrame Smooth Moving AveragesScript is designed for those who dislike how plotting a moving average from a higher timeframe on a lower timeframe chart results in a choppy zigzag line when using the standard request.security(syminfo.ticker,"x",ta.sma(src,len)) method.
My more elegant solution was to translate the chart's current timeframe, and the selected higher timeframe into seconds, then check if selected timeframe is Larger than chart timeframe, but not so large that too many bars would be necessary. Then the quotient is calculated by dividing the chosen timeframe (value in seconds) by the chart's timeframe (value in seconds).
Then take that quotient and multiply it by the chosen length. This gives us how many bars of the chart's timeframe would be used in calculating the higher timeframe Moving Average
Use the value to calculate a moving average of choice (SMA,EMA,WMA,LRC,DEMA,TEMA,TRIMA,FRAMA) thanks to @TradingView 's ta library () and @alexgrover 's () for their functions supporting series as length, making this possible.
Basically, get how many of the current chart's bars are in the higher timeframe moving average and use that as the length for calculation using chart's timeframe.
If the higher timeframe relative is too large relative to chart's timeframe, due to bar referencing limits some combinations may not be possible under current limitations, but most will work by either moving chart's timeframe higher or higher timeframe lower assuming you aren't trying to do something too extreme like plotting a weekly moving average onto a 30 second chart etc.
Moving Averages
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
KDJ Indicator with RSI FilterThe KDJ indicator is a technical analysis tool used by traders to identify potential buy and sell signals in financial markets. It is an extension of the Stochastic Oscillator, which consists of two lines, %K and %D, that move within a range of 0 to 100. The KDJ indicator introduces a third line, called %J, which is derived from the %K and %D lines. The KDJ indicator is primarily used to identify overbought and oversold conditions, as well as potential trend reversals.
Here's a brief overview of the KDJ indicator's components:
%K line: It is calculated by comparing the current closing price to the range of high and low prices over a specific period (usually 9 days).
%D line: It is a moving average of the %K line
%J line: It is calculated using the %K and %D lines
The KDJ indicator generates buy signals when the %K line crosses above the %D line and sell signals when the %K line crosses below the %D line. Additionally, when the %J line is above 100, it suggests that the asset is overbought, and when the %J line is below 0, it suggests that the asset is oversold. Traders often use these overbought and oversold signals to identify potential trend reversals.
I have taken KDJ script from and added RSI filter and alerts with and without RSI filter.
I was requested to create this script with alerts. And here it is. I have added alerts. And, I have added abilities to turn on and off the RSI filters from settings.
BB_MDL_V1Simple indicator that is based on the average line of the bollinger bands and the exponential average of 200 periods.
The customizable variable is bollinger bands length, currently the default is 35, you can tweak it to your liking and see how trend identification changes.
My recommendation is to work in 5-minute time frames in values such as SOL, FTM or MASK (cryptos)
This simple strategy can be combined with many others to gain more insight and get better market entries and exits.
[blackcat] L1 An Adaptive Moving Average For Swing TradingLevel 1
Background
Scott Cong published an article of “An Adaptive Moving Average For Swing Trading” on April 2023. I rewrite it for pine script.
Function
In "An Adaptive Moving Average For Swing Trading," author Scott Cong introduces a new adaptive moving average that is designed to be responsive, smooth, and robust. He begins with a discussion of Perry Kaufman's adaptive moving average and explains how an adaptive moving average (AMA) can adapt to different market environments. Later he explains his methods of adjusting and changing the smoothing factor, which has better response than traditional EMA and SMA. I rewrited this new kind of moving average in pine script and use yellow color for its fast line while fuchsia color for its trigger signal as a slow line. By the way, divergence detector is also added for divergence notification. You can change period or length, and signal source parameters in setting dialog.
Remarks
Feedbacks are appreciated.
Universal MA Trend(Republishing in Open source)
Hello traders,
Many existing moving average indicators have not been satisfactory in terms of the number, types, and length adjustments of moving averages.
Feeling the inconvenience, I created a moving average indicator and collected numerous famous moving averages.
Fortunately, there was a PineCoder "andre_007" who had already compiled various Moving Averages,
so I was able to find a new Moving Average and combine it with the indicator. Here is the link below
Among these, for the JMA, which has not been publicly disclosed, I utilized the source code from TradingView Wizard everget:
For VIDYA, I also used everget's source code:
And also MAMA / FAMA Coded from Pinescript Wizard everget :
Ehlers MESA Adaptive Moving Averages (MAMA & FAMA)
For Frama, I used the code from nemozny's source code :
Thanks to all these Pinecoders.
---
By using these excellent moving averages together, I found that the simultaneous Up/Down changes of various moving averages with different characteristics tend to be maintained for quite a long time.
Therefore, this indicator not only collects various moving averages but also displays areas with simultaneous trends as background.
An example can be found here:
Furthermore, to prevent the up/down changes of the moving averages due to factors like whipsaws, a smoothing filter has been introduced.
And Also, Alert is able when trend changes.
---
(오픈소스화 후 재발행)
안녕하세요 트레이더여러분.
기존의 이동평균선 지표들은, 이동평균선의 갯수, 종류, 길이조절 등에서 만족스럽지 못한 점들이 많았습니다.
불편함을 느끼고 직접 이동평균선 지표를 만들면서, 유명한 수 많은 이동평균선들을 모았습니다.
그리고 이미 이러한 수많은 이동평균선을 손수 모아서 정리해주신 고마우신 파인코더(andere_007 님)가 있어서, 그 분의 코드를 많이 이용했습니다. 링크는 아래와 같습니다.
이 중 소스가 공개되지 않은 이동평균선 중 JMA는 트레이딩뷰 위자드이신 everget의 소스코드를 이용했습니다.
VIDYA 역시 everget의 소스코드를 이용했습니다.
MAMA와 FAMA의 코드 역시 everget님의 코드를 가져왔습니다.
Ehlers MESA Adaptive Moving Averages (MAMA & FAMA)
Frama는 nemozny님의 코드를 이용했습니다.
의 코드를 이용했습니다.
이 자리를 빌어 위의 파인코더님들께 감사의 말씀을 전합니다.
---
이러한 좋은 이동평균선을 모아서 사용해보니, 다양한 특성을 갖고 있는 이동평균선의 동시적인 Up/Down 변화는 꽤 오랫동안 유지된다는 점을 발견했습니다.
그래서 이 지표는, 위의 여러가지 이동평균선을 모아놓은 것 뿐만 아니라,
그것에서 동시적인 트랜드가 나오는 곳을 배경화면으로 표시해두었습니다.
예시는 다음과 같습니다.
나아가 휩쏘 등으로 이동평균선의 up/down이 바뀌는 것을 막고자, Smoothing 필터도 도입했습니다.
또한 트랜드가 바뀔 때 얼러트가 울리도록, 얼러트 기능을 설정해놓을 수 있게 해놓았으며, 현재 이동평균선과 상태를 보기 쉽도록 테이블을 만들어놓았습니다.
Ema Short Long Indicator[CHE]█ CONCEPTS
This Pine Script is an EMA Short Long indicator that displays the crossing EMA lines on the chart. The indicator uses three exponential moving averages (EMAs) to generate the buy and sell signals. The EMA lines are plotted as green (uptrend) and red (downtrend) lines. When the green line is above the white signal line, the indicator generates a buy signal, when the green line is below the white signal line, the indicator generates a sell signal. Arrows are also displayed marking the buy and sell signals. There is also an option to allow indicator repainting or not. Finally, users can also set alerts to be alerted to potential trading opportunities.
Note: please do not disable "time frame gaps". Allows to calculate the indicator on a Timeframe (TF) different from that of the chart Time window. The TF should ideally be higher than the charts to provide a broader perspective than
the TF of the chart. Using TFs lower than the chart's will deliver fragmentary results, since only the last value of intrabar is displayed (multiple values cannot be displayed for a single chart bar). The Gaps setting determines the behavior when the TF is higher than the TF of the chart. If 'gaps' is checked, higher TF values only come in and are interconnected on the diagram when the higher TF completed. This has the advantage of avoidance Real-time epainting. If Gaps is not enabled, Gaps are filled with the last higher TF value calculated, which will not produce a repaint Values on historical bars but repaint values realtime.
█ HOW TO USE IT
Load the indicator on an active chart (see the Help Center if you don't know how).
Time period
By default, the script uses an auto-stepping mechanism to adjust the time period of its moving window to the chart's timeframe. The following table shows chart timeframes and the corresponding time period used by the script. When the chart's timeframe is less than or equal to the timeframe in the first column, the second column's time period is used to calculate the Ema Short Long Indicator :
Chart Time
timeframe period
1min 🠆 1H
5min 🠆 4H
1H 🠆 1D
4H 🠆 3D
12H 🠆 1W
1D 🠆 1M
1W 🠆 3M
█ DESCRIPTION
The script begins by setting up the chart indicator with a short title, "ESLI", and enabling it as an overlay. It then initializes several variables for time conversions, to be used later in the script.
The timeStep_translate() function converts the timeframe of the chart into a string representing a larger time interval, based on the number of seconds in the timeframe. The resulting string is used to label the horizontal axis of the chart.
Next, the script defines several input variables that can be modified by the user. These include the colors of the EMA lines and the signals, whether or not the indicator is allowed to repaint (i.e. update past values based on future data), and the number of periods used to calculate the EMA and signal lines.
The f_security() function calls the request.security() function to fetch data from the specified security and timeframe, and is used to calculate the EMA and signal lines using the ta.ema() function. The clo variable is assigned the closing price data, adjusted for repainting and timeframe.
The EMA line is calculated using a weighted average of the EMA over the specified period and two times that period, as well as three times that period, divided by six. The signal line is calculated as the EMA of the EMA line over the specified period.
The col_css variable sets the color of the EMA line based on whether it is currently above or below the signal line. The script then plots the EMA and signal lines, and uses the plotshape() function to indicate long and short signals based on the crossovers and crossunders of the EMA and signal lines.
Finally, the script sets up alert conditions using the alertcondition() function to notify the user when a long or short signal is generated, including information about the symbol and closing price.
█ SPECIAL THANKS
Special thanks to LOXX, I wanted to take a moment to express my gratitude for his valuable input in the EMA calculation. His insights and expertise have greatly helped me in improving my Pine Script coding skills. Thanks to his suggestion, I was able to better understand the EMA formula and implement it effectively in my script.
Your generosity in sharing your knowledge and experience is truly appreciated. It is through collaboration and exchanging ideas that we can all grow and become better in our craft.
This script provides exact signals that, with suitable additional indicators, provide very good results.
Best regards
Chervolino
TASC 2023.05 Cong Adaptive Moving Average█ OVERVIEW
TASC's May 2023 edition of Traders' Tips features an article titled "An Adaptive Moving Average For Swing Trading" by Scott Cong. The article presents a new adaptive moving average (AMA) that adjusts its parameters automatically based on market volatility. The AMA tracks price closely during trending movements and remains flat during congestion areas.
█ CONCEPTS
Conventional moving averages (MAs) use a fixed lookback period, which may lead to limited performance in constantly changing market conditions. Perry Kaufman's adaptive moving average , first described in his 1995 book Smarter Trading, is a great example of how an AMA can self-adjust to adapt to changing environments. Scott Cong draws inspiration from Kaufman's approach and proposes a new way to calculate the AMA smoothing factor.
█ CALCULATIONS
Following Perry Kaufman's approach, Scott Cong's AMA is calculated progressively as:
AMA = α * Close + (1 − α) * AMA(1),
where:
Close = Close of the current bar
AMA(1) = AMA value of the previous bar
α = Smoothing factor between 0 and 1, defined by the lookback period
The smoothing factor determines the performance of AMA. In Cong's approach, it is calculated as:
α = Result / Effort,
where:
Result = Highest price of the n period − Lowest price of the n period
Effort = Sum(TR, n ), where TR stands for Wilder’s true range values of individual bars of the n period
n = Lookback period
As the price range is always no greater than the total journey, α is ensured to be between 0 and 1.
SAR MACDSAR MACD is an idea of implementing Directional MACD with Parabolic SAR to exactly detect and confirm Trend. This p-SAR MACD consist of a HYBRID MACD which acts as MACD TREND oscillator, MACD Oscillator, PSAR Indicator combined with MA line. thus Fake MACD Signals can be eliminated using this SAR MACD. Sideways can be detected using Threshold Levels must be adjusted based on timeframe.
Indicators Hybrid model contains:
1.MACD (12,26,9) Standard with MA Crossovers
2.MACD Trend
3.Parabolic SAR with 0.02
4.Threshold level - indicates Sideways
How to use.
Histogram:
-> HIST MODE: normal MACD indicator
MA Line Color is based on PSAR Direction Blue-Up/ Pink -Down
A crossover upside with a Blue MA line denotes Up confirmation
A Crossover downwards with a red MA line denotes Down Confirmation
Additionally Histogram above zero line and below zero line are to be confirmed
-> MACD MODE: MACD Trend indicator
MA Line Color is based on PSAR Direction Blue-Up/ Pink -Down
A crossover upside with a Blue MA line denotes Up confirmation
A Crossover downwards with a red MA line denotes Down Confirmation
Additionally Histogram above zero line and below zero denotes long term Trend
-> Histogram Color: Indicates candles direction
Yellow indicates Unconfirmed Direction
Green Indicates up direction
Red Indicates Down Direction
Buy Condition:
MA Color - Blue
Histogram- Above Zero
Histogram/Candle -Green
MA Crossover is must
Sell Condition:
MA Color - Red
Histogram- Below Zero
Histogram/Candle -Red
MA Cross under is must
Warning: Must not be used as a standalone indicator. Use for confirmation of your Buy Sell Signals and Entry only.
Reverse PMAR & PMARPIntroducing the Reverse PMAR & PMARP
Concept
The PMAR/PMARP is an indicator which calculates :
The ratio between a chosen source price and a user defined moving average ( Price Moving Average Ratio ).
The percentile of the PMAR over an adjustable lookback period ( Price Moving Average Ratio Percentile ).
Here I have reverse engineered the PMAR / PMARP formulas to derive several functions.
These functions calculate the chart price at which the PMAR/PMARP will cross a particular scale value.
I have employed those functions here to give the "crossover" price levels for :
Upper alert level
Upper test level
Mid-Line
Lower test level
Lower alert level
Knowing the price at which these various user defined PMARP levels will be crossed can be useful in setting price levels that trigger components of various strategies.
For example: using the reverse engineered upper test price level, to set take a take profit limit order on a long trade, which was entered when PMARP was low.
The indicator displays either the PMAR or PMARP as a line plot with optional signal moving average.
It also plots optional visual alert level lines, test level lines, background signal bars, and a display panel with reverse engineered prices.
Main Properties :
Price Source :- Choice of price values or external value from another indicator ( default *Close ).
Indicator :- Choice between PMAR or PMARP ( default *PMAR ).
Price Moving Average Ratio Properties :
PMAR Length :- User defined time period to be used in calculating the Moving Average for the Price Moving Average Ratio and the PMAR component of the PMARP ( default *21 ).
MA Type :- User defined type of Moving Average which creates the MA for the Price Moving Average Ratio and the PMAR component of the PMARP ( default *EMA ).
PMAR Multiplier :- User defined multiplier which moves the decimal place to the right in order to make the scale readable in PMAR mode ( default *x1 ).
Price Moving Average Ratio Percentile Properties :
PMARP Length :- The lookback period to be used in calculating the Price Moving Average Ratio Percentile ( default *350 ).
PMAR Levels :
Hi PMAR Alert :- High alert level ( default *1.02 ).
Hi PMAR Test :- High test level ( default *1.01 ).
Lo PMAR Test :- Low test level ( default *0.99 ).
Lo PMAR Alert :- Low alert level ( default *0.98 ).
PMARP Levels :
Hi PMARP Alert :- High alert level ( default *99 ).
Hi PMARP Test :- High test level ( default *70 ).
Lo PMARP Test :- Low test level ( default *30 ).
Lo PMARP Alert :- Low alert level ( default *1 ).
Line Plot Settings :
Color Type :- User choice from dropdown between "solid" or "spectrum" line coloring ( default *Solid ).
Solid Color :- Color selection box ( default *Yellow ).
Spectrum :- User choice from dropdown between "high to low", or "high to mid to low" spectrum line coloring ( default *high to mid to low ).
High Color :- Color selection box ( default *Red ).
Mid Color :- Color selection box ( default *Green ).
Low Color :- Color selection box ( default *Blue ).
Line Width :- Defines the width of the signal line from 1 - 4 ( default *1 ).
Signal Moving Average Settings :
Signal MA Length :- The time period to be used in calculating the signal Moving Average for the Line Plot ( default *20 ).
Signal MA Type :- The type of Moving Average which creates the signal Moving Average for the Line Plot ( default *EMA ).
Color Type :- User choice from dropdown between "single" or "dual" line color ( default *dual ).
Single Color :- Color selection box ( default *White ).
Dual Color :- Color selection box ( default *Red ). Note: Defines the color of the signal MA when the MA is falling in "dual" line coloring mode.
Line Width :- Defines the width of the signal line from 1 - 4 ( default *1 ).
Visual Alert Level Settings :
Checkboxes and color selection boxes for Upper/Lower alert lines, midline & test lines.
Signal Bars Transparency :- Sets the transparency of the vertical signal bars ( default *50 ).
Checkboxes and color selection boxes for Upper/Lower signal bars.
Panel Properties :
Checkboxes and color selection boxes for the various info. panel components.
Text Size :- User choice from dropdown between Tiny, Small, Normal and Large ( default *Normal ).
Decimal Places :- Sets the decimal places shown for the values in the info. panel ( default *2 ).
Simple Chop ZoneThe original Chop Zone indicator by Trading View is good, but has a few limitations which I've addressed in this one
Too many colors which confuse and/or overwhelm users like me
Inability to change the EMA period
This one has just 3 customizable colors for
Uptrend - default = Turquoise
Downtrend - default = red
Everything else - default = lime
And you can set your own EMA length. The default is 34 as per the original Chop Zone indicator
Anchored Moving Averages - InteractiveWhat is an Anchored Moving Average?
An anchored moving average (AMA) is created when you select a point on the chart and start calculating the moving average from there.
Thus the moving average’s denominator is not fixed but cumulative and dynamic. It is similar to an Anchored VWAP, but neglecting the volume data, which may be useful when this data is not reliable and you want to focus just on price.
Main Features
This interactive indicator allows you to select 3 different points in time to plot their respective moving averages. As soon as you add the indicator to your chart you will be asked to click on the 3 different points where you want to start the calculation for each moving average.
Each AMA (Anchored Moving Average) will be colored according to its slope, using a gradient defined by two user chosen colors in the indicator menu.
The default source for the calculation is the pivot price (HLC3) but can also be modified in the menu.
Examples:
Enjoy!
Fundamental Value and Dividend Growth InvestingThis script is an original implementation of a Fundamental Value and Dividend Growth Investing Strategy for traders who want to incorporate these concepts in their trading decisions. The script uses technical indicators to determine buy and sell signals based on a set of criteria.
To use the script, traders can input various parameters, such as the length of the simple moving averages (SMA), the rate of change (ROC) length, and the dividend yield. The script calculates the SMA for the long and short periods, the ROC, and the dividend.
The buy signal is triggered when the current closing price is greater than the short-term SMA, the short-term SMA crosses above the long-term SMA, the ROC is positive, and the closing price is greater than the dividend. The sell signal is triggered when the current closing price is less than the long-term SMA, the long-term SMA crosses above the short-term SMA, and the ROC is negative.
The script plots the signals and the indicators, such as the SMA200, the SMS50, the dividend, and the ROC. The script also includes alert conditions for the buy and sell signals.
The concept underlying the calculations of this script is the Fundamental Value and Dividend Growth Investing Strategy. This strategy aims to identify stocks that are trading below their intrinsic value and have a history of increasing dividends. The SMA and ROC indicators help identify the trends in the stock price, while the dividend yield helps identify stocks with a history of dividend growth.
Overall, this script offers traders an original and useful tool for incorporating Fundamental Value and Dividend Growth Investing Strategy into their trading decisions.
Acceleration-Based MA Slope PredictionHello traders,
I developed this indicator while working on a trading strategy using moving average slope and acceleration, and I found the concept interesting enough to share it.
Let me briefly explain this indicator.
----About White Plot----
1. Calculate the first derivative approximation at the current point of the Moving Average, and then calculate the second derivative approximation to obtain the 'Acceleration'.
2. Where the acceleration is 0, it signifies a change in the force of the moving average.
3. Therefore, by drawing a parabola based on the acceleration at that time, can depict the parabolic shape of the moving average.
This is represented as a white circle on the indicator.
4. These circles are reset at the next point where the acceleration is 0, indicating a change in the parabolic force.
If the moving average rises more sharply than the predicted value of the rising parabola, a more drastic increase is expected.
5. In this case, you can start risk management around the time the drawn parabola breaks.
(The actual MA is represented by green/red lines)
6. Before the trend changes, i.e., before the direction of the moving average changes, there is a section where the acceleration is 0, and this is represented on the chart as follows.
(The lower indicator shows the acceleration of the corresponding parabola)
----About Red Plot----
1. Calculate the first derivative approximation of the moving average value, the 'slope'.
2. Where the slope is 0, it represents the extreme point of the parabola.
3. Therefore, by using the acceleration at that point as the coefficient of the quadratic function and setting the extreme point as a vertex, we can draw a quadratic function. This is represented as a red circle on the indicator.
(Keep in mind that the actual moving average is not a quadratic function; this is a "forced" quadratic function assuming the parabola is maintained)
4. These circles are reset at the next extreme point where the slope is 0, and a new quadratic function is created.
Based on the formula obtained in the above process, you can predict the future moving average through 'offset'.
5. That is, if the x value at the current point is 'k', you can predict the moving average one candle ahead by substituting (k+1) into the quadratic function.
The predicted value at the past position is shown as a red circle.
6. The smoother the chosen moving average, the fewer extreme points will appear, and the higher the likelihood of the parabola fitting.
For the T3 set as the default value, it shows very high accuracy even when predicting about 20 candles ahead.
On the other hand, rough moving averages like SMA have limited prediction value.
(SMA 60, offset = 10)
--------
The moving average with a very high level of accuracy is JMA (Jurik Moving Average). However, since the code for this moving average is not public, I recommend those interested to check it through my code.
Additionally, I believe the code of this indicator I've uploaded has significant utility.
As an example, you can use the breaking point of the parabola predicted by the acceleration to determine when the force changes again for entries/losses. There are many other possible applications as well.
I look forward to seeing more excellent results from this indicator.
--------
안녕하세요 트레이더여러분.
이 지표는, 제가 이동평균선의 기울기와 가속도를 이용하여 매매를 하기 위한 지표를 개발하다가, 흥미로운 내용이라고 판단하여 만들게 되었습니다.
이 지표에 대해 간단히 설명드리겠습니다.
----하얀색 플롯에 대해----
1. 이동평균선이 진행되는 현재 시점에서 미분의 근사값을 구하고, 다시 한 번 미분의 근사값을 구해서 '가속도'를 얻습니다.
2. 가속도가 0이 되는 곳은, 곧 해당 이동평균선의 힘이 바뀌는 곳을 의미합니다.
3. 따라서, 그 당시 시점 기준으로 포물선을 그려낸다면, 가속도를 이용하여 해당 이동평균선의 포물선을 그려낼 수 있습니다. 이것은 지표의 하얀색점로서 표기됩니다.
4. 이 때, 이러한 점들은 다음의 가속도가 0이 되는 지점, 즉 포물선의 힘이 바뀌는 곳에서 다시 초기화됩니다.
5. 올라가고 있던 포물선에서의 예측치보다 이동평균선이 더 급하게 올라간다면, 더욱 급격한 상승이 예상됩니다. 이 경우, 그려지고있는 포물선이 깨질 때쯤부터 리스크 관리를 시작할 수 있습니다.
(녹색/빨간색의 선으로 실제 MA를 표현했습니다. 거슬리시면 '모습'가셔서 끄셔도 좋습니다. )
6. 추세가 변경되기 전, 즉 이동평균선의 방향이 바뀌기 전에는 가속도가 0이 되는 구간이 존재하고, 그것이 차트 위에 다음과같이 표현됩니다.
(하단의 지표는, 해당 포물선의 가속도을 나타냅니다)
----붉은색 플롯에 대해----
1. 이동평균선 값을 미분 근사값 즉, '기울기'를 구합니다.
2. 기울기가 0이 되는 곳은, 포물선이 극점이 되는 곳을 뜻합니다.
3. 따라서, 해당 시점의 가속도를 2차함수의 계수로 하여, 또한 해당 극점을 하나의 꼭지점으로 설정하여,이차함수를 그려낼 수 있습니다. 이것은 지표의 빨간색점으로서 표현됩니다.
(실제 이동평균선은 2차함수가 아니기에, 포물선이 유지된다는 가정 하에 "억지로"만들어낸 이차함수입니다)
4. 이 때, 이러한 점은 다음 극점이 0이 되는 곳에서 초기화되고 이차함수가 만들어집니다.
5. 위의 과정에서 얻은 식을 바탕으로 'offset'을 통해 미래의 이동평균선을 예측할 수 있습니다.
즉, 현재시점의 x값을 'k'라고 한다면, (k+1)을 이차함수에 대입하여 1캔들 앞의 이동평균선을 예측할 수 있습니다.
해당 예측치가 지나간 자리는, 빨간색점을 통해 보여집니다.
6. 선택한 이동평균선이 스무스할수록 극점은 덜 등장하게되고, 포물선의 위치가 맞아들어갈 가능성이 높습니다.
현재 디폴트값으로 설정된 T3의 경우, 약 20캔들 앞을 예측해도 매우 높은 정확도를 보여줍니다.
반면에, SMA와 같이 울퉁불퉁한 이동평균선은 가능한 예측치가 크지 않습니다.
(SMA 60, offset=10)
--------
매우 높은 수준의 정확도를 보여준 이동평균선은 JMA(Jurik Moving Average)입니다. 다만 이 이동평균선은 코드가 공개되지 않았기때문에, 관심있으신 분은 저의 코드를 통해 한번 확인해보시길 권장드립니다.
추가로, 제가 올린 이 지표의 코드는 이용가치가 높다고 생각합니다.
하나의 예시로서, 가속도로 예측한 포물선이 깨지는 곳을 기준으로, 힘이 다시 한 번 바뀌는 것을 이용해 진입/로스를 할 수 있습니다. 그 외에도 매우 다양한 활용이 가능합니다.
이 지표를 통해 더욱 좋은 새로운 결과물이 나오길 기대해봅니다.
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
Trend Bands [starlord_xrp]This indicator uses multiple trendlines to determine the overall trend and trend changes. It also highlights areas of potential pullbacks to entry.
Ignition Cha Cha ChaIgnition Cha Cha Cha (ICCC) is a 3 color coded moving average indicator which numerically quantify the angle of their trends. I have labeled them as fast, medium and slow. The trend colors are Green for bullish, Red for bearish and Grey for sideways. The sideways movement can be user defined for all 3 in the settings under Threshold. If you regard for example anything under 10º as sideways then place 10 in the corresponding threshold and any angle under 10º will give a grey moving average and a grey labeled text. I use this chart in several ways. If you don't want moving averages all over your Chartistic Masterpiece you can turn off the plots and leave the numeric angles which will give you an overview of the trend. Conversely if you want to make the ultimate trend chart you can setup a 4 chart layout, Weekly, Daily, 12 hour and 4 hour and add the indicator with 200/50/25 moving averages and look for confluence. I find the best way for this is turn off the candles and use the moving averages with the numeric labels. You also have the ability to turn off and on different aspects of the indicator so that there is good control over its look. Also I have given the indicator lots of Alert presets for all 3 of the moving averages so you can avoid demented screen-stairing. Please forgive the name, my mother made me do Ballroom dancing lessons as a kid.
[MiV] MA Screener v1.0In my trading I stick to the following strategy: I buy an asset above the 100/200 moving average and then sell it.
The most problematic thing in all this is to look for assets that are above the 100 or 200 moving average, and to assess how "far" the price is from that moving average.
In fact, to solve this problem I created this indicator.
It works with 30 different assets and displays the state of its two moving averages, whether the price is higher or not, and how much higher the price is from that level.
Multiple Moving Average ToolkitFeatures Overview:
Multiple Moving Averages: The script allows you to plot up to five different Moving Averages (MAs) on your chart at the same time. You can choose the type of MA (EMA, SMA, HMA, WMA, DEMA, VWMA, VWAP) and the length of each one.
Color Ribbon: You can turn the MAs into a color ribbon by selecting the "Turn into Color Ribbon?" option. This will make the area between the MAs colored and can help you identify trends more easily.
MA Value Table: You can draw a table on your chart that displays the current values of each MA, whether the trend is bullish or bearish along with the length of the MAs. The current ATR value is also shown in the last cell of the table. You can choose the location of the table (Top Left, Top Right, Bottom Left, Bottom Right) and the transparency of the background color.
Crosses: The script can detect when two MAs cross over each other (1st MA crosses 5th MA and vice versa), indicating a potential trend reversal. It will plot crosses on the chart at the point of the crossover and give an alert if the "Bullish Cross Detected" or "Bearish Cross Detected" condition is met.
How to use:
Once the script is added to your chart, you can customize the settings to fit your preferences. You can choose the type and length of each MA, whether to turn them into a color ribbon, whether to plot crosses, and whether to draw the MA Value Table.
The MA Value Table can be moved to a different location on the chart by selecting the "Location of Table" option and choosing Top Left, Top Right, Bottom Left, or Bottom Right.
Watch for MA crossovers and alerts to identify potential trend reversals. The script can help you identify bullish and bearish trends by color-coding the area between the MAs and displaying the current values of each MA in the table.
Breakdown of the script:
User Inputs
The first section of the script defines several user inputs that allows you to customize the indicator. These include options for turning the MAs into a color ribbon, plotting crosses when there is a bullish or bearish cross of the MAs, drawing a table of the MA values, and setting the transparency of the ribbon. You can also select the location of the MA value table and customize the settings for each individual MA.
Moving Average Calculation
The script defines a function called "getMA" that calculates the moving average for a given type and length. The function uses a switch statement to determine which type of moving average to use, such as an exponential moving average (EMA), simple moving average (SMA), Hull moving average (HMA), weighted moving average (WMA), double exponential moving average (DEMA), volume-weighted moving average (VWMA), or volume-weighted average price (VWAP).
The script then calls this function to calculate the values of up to five different MAs, depending on the user input. The ATR (average true range) is also calculated using the TA library.
Color Filter and Cross Detection
The script sets a color filter based on the relationship between the MAs. If the shorter-term MAs are above the longer-term MAs, the filter is set to green to indicate a bullish trend, and if the shorter-term MAs are below the longer-term MAs, the filter is set to red to indicate a bearish trend. You can adjust the transparency of the ribbon to make it more or less visible.
The script also detects when there is a bullish or bearish cross of the MAs and can generate alerts to notify you.
MA Plotting
The script plots up to five MAs on the chart, depending on the user input. The MAs are plotted as lines with different colors and thicknesses, and you can choose to turn them into a color ribbon if desired.
Cross Plotting
The script plots crosses on the chart when there is a bullish or bearish cross of the MAs. The crosses are plotted as X shapes at the location of the cross and are color-coded to indicate the direction of the cross.
MA Value Table
Finally, the script draws a table of the MA values on the chart, displaying the values of each MA as well as the current trend and the ATR. You can customize the location of the table, and the table is colored to match the color filter of the MAs.
Feel free to message me or comment on the post with any questions or issues!
Much more to come!
Thanks for reading, enjoy!
KST con HMA---------- ENGLISH DESCRIPTION ----------
The indicator created is called "KST with HMA" and is used to measure the impulse of an asset's price.
The code begins by defining four variables representing ROC (Rate of Change) period lengths for calculating the KST (Know Sure Thing) and a variable for the length of the HMA (Hull Moving Average).
Next, an HMA function is defined to calculate the Hull Moving Average, a type of weighted moving average that adjusts for price volatility.
ROC values are then calculated for the four periods defined above and KST values are calculated as a weighted sum of the ROC values. These values are then normalized with the HMA and the standard deviation of the HMA is calculated. The normalized value is finally plotted with three different color lines: black for values greater than 1, red for values less than -1, and green for values between -1 and 1.
Finally, a black dashed line is plotted to represent the zero line. The green line indicates a phase of market uncertainty or lateralization, while the indicator can be used to identify buy points above zero and sell points below zero.
---------- ITALIAN DESCRIPTION ----------
L'indicatore creato è chiamato "KST con HMA" e viene utilizzato per misurare l'impulso del prezzo di un asset.
Il codice inizia definendo quattro variabili che rappresentano le lunghezze dei periodi di ROC (Rate of Change) per il calcolo del KST (Know Sure Thing) e una variabile per la lunghezza dell'HMA (Hull Moving Average).
Successivamente viene definita una funzione HMA per il calcolo della Hull Moving Average, un tipo di media mobile ponderata che si adatta alla volatilità del prezzo.
Vengono poi calcolati i valori ROC per i quattro periodi definiti in precedenza e calcolati i valori KST come somma ponderata dei valori ROC. Questi valori vengono poi normalizzati con l'HMA e viene calcolata la deviazione standard dell'HMA. Il valore normalizzato viene infine plottato con tre diverse linee di colore: nero per valori superiori a 1, rosso per valori inferiori a -1 e verde per valori tra -1 e 1.
Infine, viene plottata una linea tratteggiata nera per rappresentare la linea zero. La linea verde indica una fase di incertezza o lateralizzazione del mercato, mentre l'indicatore può essere utilizzato per individuare punti di acquisto sopra lo zero e di vendita al di sotto dello zero.
TradeEasy - KintroThe TradingView script provided is a custom indicator named "TradeEasy - Kintro". It is created by the author Kintro and is designed to help traders identify potential buy and sell signals in the market. The indicator is based on the Exponential Moving Average (EMA) and uses two different EMAs, one with a period of 20 and the other with a period of 50.
The indicator is meant to be used on the 5-minute timeframe and it is recommended to use TradingView in Dark Mode for better appearance. The author also reminds users that no strategy works 100% accurately and backtesting should be done before trading with a real account. The author is not responsible for any losses incurred by traders.
The indicator uses a simple set of rules to generate trading signals. The thick line on the chart represents the 50 EMA while the thin line represents the 20 EMA. When the thin line crosses upwards over the thick line, it indicates a bullish signal. After the crossover, traders are advised to wait for the price to pullback between the two lines. A range should then be created while the price moves through the thin line.
On the break of the range, an entry signal is generated, and the stop loss should be set below the range. The author advises traders to exit their profits according to their own analysis or price action and not to re-enter on the next pullback of the same trend. The same rules apply when the thin line crosses downwards over the thick line.
The author emphasizes that range creation is mandatory on crossing and that traders should not try to go against the trend. If the price is above both lines, traders should only go for buy orders, and vice versa.
If there is no range created while crossing, traders are advised not to enter the market. Traders should wait for the opportunity and not force a trade.
The indicator also includes a plot of the 34 EMA, and a range is created above and below the price action using the "up" and "down" variables. The author uses the "fill" function to color the background of the chart to highlight the range. The "dummy" variable is used to plot circles above or below the price action, depending on the trend.
In summary, the "TradeEasy - Kintro" indicator is a custom indicator designed to help traders identify potential buy and sell signals based on the crossing of two EMAs. The author provides a set of rules to generate trading signals and advises traders to wait for the opportunity and not force a trade. The indicator also includes a visual representation of the range created on the chart. As always, traders are advised to conduct their own research and analysis before entering any trades.
Smoothing R-Squared ComparisonIntroduction
Heyo guys, here I made a comparison between my favorised smoothing algorithms.
I chose the R-Squared value as rating factor to accomplish the comparison.
The indicator is non-repainting.
Description
In technical analysis, traders often use moving averages to smooth out the noise in price data and identify trends. While moving averages are a useful tool, they can also obscure important information about the underlying relationship between the price and the smoothed price.
One way to evaluate this relationship is by calculating the R-squared value, which represents the proportion of the variance in the price that can be explained by the smoothed price in a linear regression model.
This PineScript code implements a smoothing R-squared comparison indicator.
It provides a comparison of different smoothing techniques such as Kalman filter, T3, JMA, EMA, SMA, Super Smoother and some special combinations of them.
The Kalman filter is a mathematical algorithm that uses a series of measurements observed over time, containing statistical noise and other inaccuracies, and produces estimates of unknown variables that tend to be more accurate than those based on a single measurement.
The input parameters for the Kalman filter include the process noise covariance and the measurement noise covariance, which help to adjust the sensitivity of the filter to changes in the input data.
The T3 smoothing technique is a popular method used in technical analysis to remove noise from a signal.
The input parameters for the T3 smoothing method include the length of the window used for smoothing, the type of smoothing used (Normal or New), and the smoothing factor used to adjust the sensitivity to changes in the input data.
The JMA smoothing technique is another popular method used in technical analysis to remove noise from a signal.
The input parameters for the JMA smoothing method include the length of the window used for smoothing, the phase used to shift the input data before applying the smoothing algorithm, and the power used to adjust the sensitivity of the JMA to changes in the input data.
The EMA and SMA techniques are also popular methods used in technical analysis to remove noise from a signal.
The input parameters for the EMA and SMA techniques include the length of the window used for smoothing.
The indicator displays a comparison of the R-squared values for each smoothing technique, which provides an indication of how well the technique is fitting the data.
Higher R-squared values indicate a better fit. By adjusting the input parameters for each smoothing technique, the user can compare the effectiveness of different techniques in removing noise from the input data.
Usage
You can use it to find the best fitting smoothing method for the timeframe you usually use.
Just apply it on your preferred timeframe and look for the highlighted table cell.
Conclusion
It seems like the T3 works best on timeframes under 4H.
There's where I am active, so I will use this one more in the future.
Thank you for checking this out. Enjoy your day and leave me a like or comment. 🧙♂️
---
Credits to:
▪@loxx – T3
▪@balipour – Super Smoother
▪ChatGPT – Wrote 80 % of this article and helped with the research
Relative Strength Index w/ STARC Bands and PivotsThis is an old script that I use with some useful RSI strategies from "Technical Analysis for the Trading Professional" 2nd edition by Constance Brown.
The base RSI comes with the option for custom length, and has some pre-configured ranges for looking at exits and entrances. The idea is to be bullish when bounces happen in the red zone during an already bullish trend or when the indicator enters green without a rejection. Be bearish if the indicator falls through the red zone or fails to enter green during an already bearish trend.
I have added the formulas used for creating STARC bands (just think fancier volatility bands) with adjustable tolerances. The idea is to look out for when the RSI touches one of the bands and reverses. This is usually indicative of a strong reversal (though the timing will be up to the trader). Best use this on shorter time frames during a volatile time of a stock's price action.
Although a little messy, there is a small segment of the script which includes pivot points. I like to use these because they make indicating local highs/lows for finding divergences easier.
Finally, I have added a couple of customizable EMAS for the RSI itself. Useful when combined with the other features!