[blackcat] L2 Ehlers Dual Differential Cycle Period MeasurerLevel: 2
Background
John F. Ehlers introuced Dual Differential Cycle Period Measurer in his "Rocket Science for Traders" chapter 7. The In-phase and Quadrature components are computed with the Hilbert Transformer using procedures identical to those in the Dual Differentiator.
Function
blackcat L2 Ehlers Homodyne Discriminator Cycle Period Measurer is used to measure Dominant Cycle (DC). This is one of John Ehlers three major methods to measure DC. These components undergo a complex averaging and are smoothed in an EMA to avoid any undesired cross products in the multiplication step that follows. The period is solved directly from the smoothed Inphase and Quadrature components. The interim calculation for the denominator is performed as Value1 to ensure that the denominator will not have a zero value. The sign of Valuel is reversed relative to the theoretical equation because the differences are looking backward in time.
Key Signal
Smooth --> 4 bar WMA w/ 1 bar lag
Detrender --> The amplitude response of a minimum-length HT can be improved by adjusting the filter coefficients by
trial and error. HT does not allow DC component at zero frequency for transformation. So, Detrender is used to remove DC component/ trend component.
Q1 --> Quadrature phase signal
I1 --> In-phase signal
Period --> Dominant Cycle in bars
SmoothPeriod --> Period with complex averaging
Pros and Cons
100% John F. Ehlers definition translation of original work, even variable names are the same. This help readers who would like to use pine to read his book. If you had read his works, then you will be quite familiar with my code style.
Remarks
The 4th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Dominantcycle
[blackcat] L2 Ehlers Phase Accumulator Cycle Period MeasurerLevel: 2
Background
John F. Ehlers introuced Phase Accumulation technique of cycle period measurement in his "Rocket Science for Traders" chapter 7. It is perhaps the easiest to comprehend. In this technique, John Ehlers measures the phase at each sample by taking the arctangent of the ratio of the Quadrature component to the In-phase component. A delta phase is generated by taking the difference of the phase between successive samples. At each sample Dr. Ehlers then looks backward, adding up the delta phases. When the sum of the delta phases reaches 360 degrees (2*pi in tradingview), we must have passed through one full cycle, on average. The process is repeated for each new sample.
Function
blackcat L2 Ehlers Phase Accumulator Cycle Period Measurer is used to measure Dominant Cycle (DC). This is one of John Ehlers three major methods to measure DC. The Phase Accumulation method of cycle measurement always uses one full cycle’s worth of historical data. This is both an advantage and disadvantage. The advantage is the lag in obtaining the answer scales directly with the cycle period. That is, the measurement of a short cycle period has less lag than the measurement of a longer cycle period. However, the number of samples used in making the measurement means the averaging period is variable with cycle period. Longer averaging reduces the noise level compared to the signal. Therefore, shorter cycle periods necessarily have a higher output Signal-to-Noise Ratio (SNR).
Key Signal
Smooth --> 4 bar WMA w/ 1 bar lag
Detrender --> The amplitude response of a minimum-length HT can be improved by adjusting the filter coefficients by
trial and error. HT does not allow DC component at zero frequency for transformation. So, Detrender is used to remove DC component/ trend component.
Q1 --> Quadrature phase signal
I1 --> In-phase signal
Period --> Dominant Cycle in bars
Pros and Cons
100% John F. Ehlers definition translation of original work, even variable names are the same. This help readers who would like to use pine to read his book. If you had read his works, then you will be quite familiar with my code style.
Remarks
The 2nd script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Strength Analyzer [DW]This is an experimental hybrid between relative strength and spectrum analysis methods aimed to deliver useful insights about cyclical dominance and momentum.
This study utilizes a modified RSI formula and a modified Goertzel algorithm to determine relative strength and spectral dominance for periods 8 through 50.
These periods are theorized by many analysts to be the main cyclical components of market movement.
In this study, you are given the option to apply equalization (EQ) to the dataset before estimating strength.
This enables you to transform your data and observe how strength estimates changes as well.
Whether you want to give emphasis to some frequencies, isolate specific bands, or completely alter the shape of your waveform, EQ filtration makes for an interesting experience.
The default EQ preset in this script cuts low end presence, dampens high frequency oscillations, and cleanly passes main cyclic components.
There are many ways to use EQ to transform your dataset, so play around with the settings and find the presets that work best for your analysis setup.
After EQ processing, the data is then passed through the modified RSI algorithm to generate momentum information
The modified RSI in this script is rescaled to oscillate between -1 and 1, and has the option to pass through a 2 pole Butterworth low pass filter before and after processing for a smoother output.
The strength thresholds are determined by the threshold value, which quantifies distance above and below 0.
The threshold value can also be thought of as conventional RSI distance from 50 rescaled so that an increment of 0.1 is equivalent to an increment of 5 on a conventional RSI.
A threshold value of 0.4 is equivalent to thresholds of 70 and 30 on a conventional RSI, so this is the default. The maximum threshold value is 1, which is equivalent to thresholds of 100 and 0.
This script plots colored sections for each period value using a gradient color scheme based on their respective strength estimates.
The color scheme in this script is a multicolored gradient that shows green scaled colors for bullish strength and red scaled colors for bearish strength.
Darker, less vibrant colors indicate lower strength. Brighter, more vibrant colors indicate higher strength.
Strength values near 0 will show the darkest colors, and values near the positive or negative threshold value will show the brightest.
The data is fed parallel through the modified Goertzel algorithm to obtain cyclic power information and to estimate the dominant cycle.
Gerald Goertzel's algorithm is a unique Fourier related transform that identifies tonal properties by quantifying resonance in a set of second order IIR filters with direct-form structure.
It is computationally more efficient than typical DFT or FFT algorithms, and yields decent spectral resolution.
In this variation of the algorithm, data is first passed through a 2 pole high pass filter to attenuate spectral dilation, then passed through a Hamming Window to tidy up the frequency range.
The clean windowed data is then passed through a recursive resonance loop over the frequency block to calculate filter coefficients, which are then used to identify real and imaginary magnitude components.
From there, the magnitude components are used to calculate cyclic power.
The power outputs of each period are then compared for dominant cycle estimation, which is plotted over the gradient.
The dominant cycle can also be optionally smoothed or halved based on your preferences.
Bar colors are included in this script. The color scheme is a gradient based on dominant cycle momentum.
Signals and alert conditions are included in this script as well, and can be customized to your liking.
The two main signal types in this script are:
-> Dominant Cycle - Signals based on dominant cycle or half dominant cycle changes from positive to negative strength or vice versa.
-> Confluence - Signals based on confluence emergence. Based on the majority of measured cycles or all measured cycles showing positive or negative strength.
The signals in this are also externally accessible by other scripts.
The output format is 1 for long signals, and -1 for short signals.
To integrate these signals with your own system, use a source input in your script and assign it to this script's "Direction Signals" output variable from the dropdown tab.
In addition, I included two external output variables that show dominant cycle strength and average cycle strength.
They can be integrated into your own scripts by using a source input and selecting the proper output variable, just like the signals.
The Strength Analyzer is a versatile and powerful analytical tool to have in the arsenal for generating unique insights about momentum and cycle dominance.
By analyzing strength on a spectral basis, we can look at relative price movements on a deeper level and gain insights that aren't necessarily obvious from simply looking at a price chart.
------------------------------------------------
This is a premium script, and access is provided on an invite-only basis.
To gain access, get a copy of the script overview, or for any other inquiries, send me a direct message!
I look forward to hearing from you!
------------------------------------------------
General Disclaimer:
Trading stocks, futures, Forex, options, ETFs, cryptocurrencies or any other financial instrument has large potential rewards, but also large potential risk.
You must be aware of the risks and be willing to accept them in order to invest in stocks, futures, Forex, options, ETFs or cryptocurrencies.
Don’t trade with money you can’t afford to lose.
This is neither a solicitation nor an offer to Buy/Sell stocks, futures, Forex, options, ETFs, cryptocurrencies or any other financial instrument.
No representation is being made that any account will or is likely to achieve profits or losses of any kind.
The past performance of any trading system or methodology is not necessarily indicative of future results.
------------------------------------------------
Note:
Because TV's UI can't handle displaying style options for 43 fills with 42 colors, the color scheme of the analyzer is currently not editable.
However, no other sacrifices to functionality or quality were made in this project.
As the TV team performs updates on the platform, the ability to customize this color scheme will likely come as well.
Also, it's important to note that this script uses a heavy amount of calculations to generate this output.
At times (very infrequently), TV will throw an error message saying "Calculation Takes Too Long", likely due to a momentary lull in available server space.
If you receive this error, simply hide then unhide the indicator, and everything should function as expected.
Ehlers Spectrum Derived Filter Bank [CC]The Spectrum Derived Filter Bank was created by John Ehlers (Stocks & Commodities V. 26:3 (16-22)) and this is technically two indicators in one. This will let you know the current cycle period which is in blue and the other indicator will let you know if you should buy the stock or not. Buy when it is green and sell when it is red.
Let me know if you would like me to publish other scripts or if you want something custom done!
Note: I'm republishing this because the original script couldn't be found in searches so this will fix that.
Ehlers Dominant Cycle Tuned Bypass Filter [CC]The Dominant Cycle Tuned Bypass Filter was created by John Ehlers (Stocks & Commodities V. 26:3 (16-22)) and this is a particularly unique indicator because this does a pretty good job at predicting the future stock movements. If the blue line crosses over the red then a few bars from now the stock price will most likely go up and if the blue line crosses below the red then a few bars from now the stock price should go down. Since this is such a unique indicator to use with entry and exit points, I don't have them color coded but try this out and let me know what you think.
This was a special request so let me know what other scripts you would like to see me publish or if you want anything custom done!
Note: I'm republishing this because the original script couldn't be found in searches so this will fix that.
Ehlers Discrete Fourier TransformThe Discrete Fourier Transform Indicator was written by John Ehlers and more details can be found at www.mesasoftware.com
I have color coded everything as follows: blue line is the dominant cycle, orange line is the power converted to decibels, and I have marked the other line as red if you should sell or green if you should buy
Let me know if you would like to see me write any other scripts!
ZenTrading CyclePhaseThis is a script for beta testing only.
Used to mainly to spot (short-term) divergences
Enhanced Autocorrelation Periodogram RasterChart - EhlersFirstly, this is NOT an indicator. It's an advanced cycle period detector for advanced developers OR scripts providing a "Period Source" they may have developed that can utilize this detector. Be forewarned! I would only recommend this for advanced developers, not novice. If you are up to the challenge of manually altering period adjustments on the daily chart of an indicator by hand in real time, you may still obtain this indicator after negotiating a proper request for access, but I will say this, it is NOT suitable for all indicators.
Understand all of the above aforementioned? Proceed...
For those of you wondering how I did it without Pine support for arrays, I had to emulate them, totaling over 600+ lines of code. This was a formidable task to achieve. This may be the hardest task I have ever accomplished, as of yet, in Pine.
Now, on to the Description...
This is my enhanced and heavily* modified version of Dr. John Ehlers' autocorellation periodogram for detecting dominant cycles(frequencies) in an asset using Pine Script version 4.0. The original concept comes from chapter 8 of his book "Cycle Analytics for Traders" and may also be found in TASC magazine in the September 2016 issue. I did heavily modify the original computations for the purpose of providing the "maximum" amount of adjustability there is to possibly offer, but left the original settings intact. I also provided an assortment of vibrant color changing techniques to choose from for anyone who may have vision impairments. This also displays that color scheming is VERY possible in Pine ...if only I could get "chart.theme" for auto-detection.
I once again would personally like to thank the talented individuals at TV for providing a platform that embraces an initial free membership, which I first obtained myself, for individuals like me to freely code in Pine with mathemagical ideas and mental wizardry, creating ultimately, inventions like this eye candy display above.
Features List Includes:
"Source" Selection
Color schemes (displayed above)
Transparency for the heat map to reduce or intensify color brightness ( Thank you TV! For this feature...)
The detected dominant cycle can be 'Sourced' by another specially** modified script providing an integer, float, or a rounded float.
Resolution enhancement has 3 settings
Smoother period control
Highpass period control
Pearson correlation period control
Minimal Power Threshold Tweak(Experimental***)
Adjustment for the smoothing coefficients of the Fourier Transforms(Experimental!)
This is not a freely available indicator, FYI. To witness my Pine poetry in action, properly negotiated requests for unlimited access, per indicator, may ONLY be obtained by direct contact with me using TV's "Private Chats" or by "Message" in my member name above. The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... If you do have any questions or comments regarding this indicator, I will consider your inquiries, thoughts, and ideas presented below in the comments section, when time provides it. As always, "Like" it if you simply just like it, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
* This has additional features/tweaks not included in the original.
** Many Pine built-in functions WILL NOT support the use of this detector if 'Sourced' to control a period setting. You have to totally rewrite those built-in Pine functions in Pine script. Yes, it is very possible! BUT ...in many cases, not all.
*** This "modification" reduces large spikes in the detected dominant cycle period with increased adjustment. Increasing this value may reduce dominant cycle spikes around 0.3-ish
Dominant Cycle Tuned Rsi BackgroundBackground version of the Dominant Cycle Tuned Rsi Background published here
Dominant Cycle Tuned RsiIntroduction
Adaptive technical indicators are importants in a non stationary market, the ability to adapt to a situation can boost the efficiency of your strategy. A lot of methods have been proposed to make technical indicators "smarters" , from the use of variable smoothing constant for exponential smoothing to artificial intelligence.
The dominant cycle tuned rsi depend on the dominant cycle period of the market, such method allow the rsi to return accurate peaks and valleys levels. This indicator is an estimation of the cycle finder tuned rsi proposed by Lars von Thienen published in Decoding the Hidden Market Rhythm/Fine-tuning technical indicators using the dominant market vibration/2010 using the cycle measurement method described by John F.Ehlers in Cybernetic Analysis for Stocks and Futures .
The following section is for information purpose only, it can be technical so you can skip directly to the The Indicator section.
Frequency Estimation and Maximum Entropy Spectral Analysis
“Looks like rain,” said Tom precipitously.
Tom would have been a great weather forecaster, but market patterns are more complex than weather ones. The ability to measure dominant cycles in a complex signal is hard, also a method able to estimate it really fast add even more challenge to the task. First lets talk about the term dominant cycle , signals can be decomposed in a sum of various sine waves of different frequencies and amplitudes, the dominant cycle is considered to be the frequency of the sine wave with the highest amplitude. In general the highest frequencies are those who form the trend (often called fundamentals) , so detrending is used to eliminate those frequencies in order to keep only mid/mid - highs ones.
A lot of methods have been introduced but not that many target market price, Lars von Thienen proposed a method relying on the following processing chain :
Lars von Thienen Method = Input -> Filtering and Detrending -> Discrete Fourier Transform of the result -> Selection using Bartels statistical test -> Output
Thienen said that his method is better than the one proposed by Elhers. The method from Elhers called MESA was originally developed to interpret seismographic information. This method in short involve the estimation of the phase using low amount of information which divided by 360 return the frequency. At first sight there are no relations with the Maximum entropy spectral estimation proposed by Burg J.P. (1967). Maximum Entropy Spectral Analysis. Proceedings of 37th Meeting, Society of Exploration Geophysics, Oklahoma City.
You may also notice that these methods are plotted in the time domain where more classic method such as : power spectrum, spectrogram or FFT are not. The method from Elhers is the one used to tune our rsi.
The Indicator
Our indicator use the dominant cycle frequency to calculate the period of the rsi thus producing an adaptive rsi . When our adaptive rsi cross under 70, price might start a downtrend, else when our adaptive rsi crossover 30, price might start an uptrend. The alpha parameter is a parameter set to be always lower than 1 and greater than 0. Lower values of alpha minimize the number of detected peaks/valleys while higher ones increase the number of those. 0.07 for alpha seems like a great parameter but it can sometimes need to be changed.
The adaptive indicator can also detect small top/bottoms of small periods
Of course the indicator is subject to failures
At the end it is totally dependent of the dominant cycle estimation, which is still a rough method subject to uncertainty.
Conclusion
Tuning your indicator is a great way to make it adapt to the market, but its also a complex way to do so and i'm not that convinced about the complexity/result ratio. The version using chart background will be published separately.
Feel free to tune your indicators with the estimator from elhers and see if it provide a great enhancement :)
Thanks for reading !
References
for the calculation of the dominant cycle estimator originally from www.davenewberg.com
Decoding the Hidden Market Rhythm (2010) Lars von Thienen
Ehlers , J. F. 2004 . Cybernetic Analysis for Stocks and Futures: Cutting-Edge DSP Technology to Improve Your Trading . Wiley
Cosine, In-Phase & Quadrature IFM [Ehlers]Yet another method for determining the cycle of a market: this time, you have access to the two fastest and most accurate methods
as well as the option to average these methods together.
The controls are pretty straight forward:
Source lets you select the price data to perform calculations on (close, open, etc..)
Max Period is simply the cap for the algorithm when it's checking the validity of Periods.
-> If you notice your plots have a flat top, then increase this value to accept a wider range of Periods.
-> This setting has a min. value of 8 to reduce noise and a max of 100 to ignore waves from higher time frames.
Average? simply averages the two methods of calculation.
-> You may want to do this if you notice the two plots diverging a lot.
-> Cosine IFM tends to favor shorter periods; I-Q IFM tends to favor longer.
Cheers,
- DasanC
Adaptive Bandpass Filter [Ehlers]This is my latest bandpass filter - used to determine if a security is in a trend or cycle.
Now with an adaptive period setting! I use Ehlers in-phase & quadrature dominant cycle measurement (IQ IFM) method to set the period dynamically.
This method favors longer periods which tend to produce smoother, albeit laggier bandpass oscillator plots. From my quick tests, I tend to have lag between 4 and 8 bars, depending on the Timeframe.
The lower timeframes tend to have more noise and thus produce more interfering frequencies that may cause lag.
>Settings
Source: Select the data source to perform calc's on (close, open, etc...)
Period: Select the period to tune. Periods outside of this value will be attenuated (reduced)
Adaptive: Enable to have the I-Q IFM set the period for you (disables Period setting)
Bandpass Tolerance: Allow periods that are plus/minus the chosen period to pass.
Cycle Tolerance: Sensitivity of cycle mode. Lower values consider trends more frequent, higher values consider cycles more frequent.
Bandpass tolerance example: for instance, if this setting is 0.1 (10%) and Period is set to 20, then waves with a period of 18 - 22 will pass.
>How to read
Red line is the bandpass output, showing a lagged version of the dominant cycle representing the
Black lines are the upper and lower bounds for a cycle
Green Background indicates an uptrend
Red background indicates a downtrend
Adaptive Zero Lag EMA Strategy [Ehlers + Ric]Behold! A strategy that makes use of Ehlers research into the field of signal processing and wins so consistently, on multiple time frames AND on multiple currency pairs.
The Adaptive Zero Lag EMA (AZLEMA) is based on an informative report by Ehlers and Ric .
I've modified it by using Cosine IFM, a method by Ehlers on determining the dominant cycle period without using fast-Fourier transforms
Instead, we use some basic differential equations that are simplified to approximate the cycle period over a 100 bar sample size.
The settings for this strategy allow you to scalp or swing trade! High versatility!
Since this strategy is frequency based, you can run it on any timeframe (M1 is untested) and even have the option of using adaptive settings for a best-fit.
>Settings
Source : Choose the value for calculations (close, open, high + low / 2, etc...)
Period : Choose the dominant cycle for the ZLEMA (typically under 100)
Adaptive? : Allow the strategy to continuously update the Period for you (disables Period setting)
Gain Limit : Higher = faster response. Lower = smoother response. See for more information.
Threshold : Provides a bit more control over entering a trade. Lower = less selective. Higher = More selective. (range from 0 to 1)
SL Points : Stop Poss level in points (10 points = 1 pip)
TP Points : Take Profit level in points
Risk : Percent of current balance to risk on each trade (0.01 = 1%)
www.mesasoftware.com
www.jamesgoulding.com(Measuring%20Cycles).doc
Ehlers Smoothed Adaptive MomentumEhlers Smoothed Adaptive Momentum script.
This indicator was developed and described by John F. Ehlers in his book "Cybernetic Analysis for Stocks and Futures" (2004, Chapter 12: Adapting to the Trend).