Zero-Lag MA Trend Levels [ChartPrime] The Zero-Lag MA Trend Levels indicator combines a Zero-Lag Moving Average (ZLMA) with a standard Exponential Moving Average (EMA) to provide a dynamic view of the market trend. This indicator uses a color-changing cloud to represent shifts in trend momentum and plots key levels when trend reversals are detected. The addition of trend level boxes helps identify significant price zones where market shifts occur, with retest signals aiding in spotting potential continuation or reversal points.
⯁ KEY FEATURES & HOW TO USE
⯌ Zero-Lag Moving Average (ZLMA) with EMA Cloud :
The indicator employs a Zero-Lag Moving Average (ZLMA) alongside a standard EMA.
series float emaValue = ta.ema(close, length) // EMA of the closing price
series float correction = close + (close - emaValue) // Correction factor for zero-lag calculation
series float zlma = ta.ema(correction, length) // Zero-Lag Moving Average (ZLMA)
The cloud between these averages changes color depending on the trend direction. During a downtrend, if the ZLMA begins to increase, the cloud partially turns green, signaling potential strength. Conversely, during an uptrend, if the ZLMA decreases, the cloud partially turns to the downtrend color (blue by default), indicating potential weakness.
Use : Traders can monitor the cloud's color shifts for early signs of changing momentum. A fully colored cloud aligning with the current trend indicates a strong directional move, while mixed colors suggest a potential trend change.
⯌ Trend Shift and Level Boxes :
Each time a crossover between the EMA and the ZLMA occurs, indicating a trend shift, the indicator plots a box around the price level where the shift occurred. This box remains on the chart to mark the price zone of the trend change.
Use : The boxes provide clear visual markers of where market sentiment shifted. These levels can act as support and resistance zones. Traders can use these boxes to identify potential entry or exit points when the market retests these key levels.
⯌ Retest Detection with Labels :
If the price action crosses a previously plotted trend level box, the indicator marks this event with triangle labels. An upward triangle (▲) appears when the price retests the top of a box during a bullish crossover, and a downward triangle (▼) appears when the price retests the bottom of a box during a bearish crossunder.
Use : These labels help traders identify potential continuation or reversal points at critical price levels, offering additional confirmation for trading decisions.
⯌ Dynamic Color-Coding :
The color of the ZLMA and the EMA is adjusted according to their current trend direction, with the ZLMA adopting green for upward trends and blue for downward trends. This visual representation makes it easier to quickly gauge the market's momentum at a glance.
Use : Traders can use the color-coding to quickly assess the strength and direction of the current trend, allowing for more informed decision-making.
⯁ USER INPUTS
Length : Sets the period for both the ZLMA and EMA calculations.
Trend Levels : Toggle to display the trend level boxes on the chart.
Colors (+ / -) : Define the colors for bullish and bearish trends.
⯁ CONCLUSION
The Zero-Lag MA Trend Levels - ChartPrime indicator offers a nuanced approach to trend detection by combining the ZLMA with a traditional EMA. Its dynamic cloud color changes, trend level boxes, and retest labels make it a versatile tool for traders seeking to identify trend shifts and key price zones effectively. By incorporating elements of support and resistance along with trend momentum, this indicator provides a comprehensive view of market dynamics for both trend-following and counter-trend trading strategies.
Zero-lag
ZLSMA - Zero Lag LSMAAn almost zero lag version of the LSMA (Least Squares Moving Average)
Gives instant linear regression of current price action.
This line works with the same rules as its "laggy" counterpart the LSMA:
When price crosses over it signals a bull trend.
When price crosses under it signals bear trend.
When price stays close or on the line sideways action is to be expected.
The direction of the line shows the direction of the trend.
[blackcat] L2 Ehlers Zero-lag SmootherLevel: 2
Background
John F. Ehlers introuced Zero-Lag Data Smoothers in Jul, 2002.
Function
John Ehlers introduced "Zero-Lag Data Smoothers", the infinite impulse response (IIR) filter and finite impulse response (FIR) filter.
In his article this issue on zero-lag smoothing, John Ehlers notes that his favorite filter is the symmetrically weighted six-bar finite impulse response (FIR) filter. This is also known as a triangular moving average, and can be conveniently implemented as a double-smoothed simple moving average. Per Ehlers, since this filter has six elements, its lag is 2.5 bars. Via further processing, this lag can be reduced to zero, but this produces too much overshoot. As a compromise, Ehlers suggests reducing the lag to one bar. To enable a user to adjust the lag easily, I provide the pine v4 code for an Adjustable Lag Filter indicator below. The first input, Price, should typically be set to OHLC, hl2, hl3, ohlc4 etc. The second input, LagReduction, should be set to a value in the zero-to-2.5 range. Setting it to zero will result in no adjustment, and the output will match that of the raw triangular average. Setting it to 2.5 will reduce the lag to zero. Setting it to 1.5 will reduce the lag to one bar.
Key Signal
Filter--> Zero-Lag Data Smoother fast line
Trigger--> Zero-Lag Data Smoother slow line
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 67th 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.
Zalligator - Zero-Lag Alligator IndicatorI applied the zero-lag moving average theory to the Alligator Indicator. It seems like some different rules would would be required versus the traditional Alligator. Let me know what you think!
Moving Average Compendium===========
Moving Average Compendium (16 MA Types)
===========
A selection of the most popular, widely used, interesting and most powerful Moving Averages we can think of. We've compiled 16 MA's into this script, and allowed full access to the source code so you can use what you need, as you need it.
-----------
From very simple moving averages using built-in functions, all the way through to Fractal Adaptive Averages, we've tried to cover as much as we can think of! BUT, if you would like to make a suggestion or recommendation to be added to this compendium of MA's please let us know! Together we can get a complete list of many dozens of types of Moving Average.
Full List (so far)
---
SMA - Simple Moving Average
EMA - Exponential Moving Average
WMA - Weighted Moving Average
VWMA - Volume Weighted Moving Average
DEMA - Double Exponential Moving Average
TEMA - Triple Exponential Moving Average
SMMA - Smoothed Moving Average
HMA - Hull Moving Average
ZLEMA - Zero-Lag Exponential Moving Average
KAMA - Kaufman Adaptive Moving Average
JMA - Jurik Moving Average
SWMA - Sine-Weighted Moving Average
TriMA - Triangular Moving Average
MedMA - Moving Median Average
GeoMA - Geometric Mean Moving Average
FRAMA - Fractal Adaptive Moving Average
Line color changes from green (upward) to red (downward) - some of the MA types will "linger" without moving up or down and when they are in this state they should appear gray in color.
Thanks to all involved -
Good Luck and Happy Trading!
Grand Trend Forecasting - A Simple And Original Approach Today we'll link time series forecasting with signal processing in order to provide an original and funny trend forecasting method, the post share lot of information, if you just want to see how to use the indicator then go to the section "Using The Indicator".
Time series forecasting is an area dealing with the prediction of future values of a series by using a specific model, the model is the main tool that is used for forecasting, and is often an expression based on a set of predictor terms and parameters, for example the linear regression (model) is a 1st order polynomial (expression) using 2 parameters and a predictor variable ax + b . Today we won't be using the linear regression nor the LSMA.
In time series analysis we can describe the time series with a model, in the case of the closing price a simple model could be as follows :
Price = Trend + Cycles + Noise
The variables of the model are the components, such model is additive since we add the component with each others, we should be familiar with each components of the model, the trend represent a simple long term variation of high amplitude, the cycles are periodic fluctuations centered around 0 of varying period and amplitude, the noise component represent shorter term irregular variations with mean 0.
As a trader we are mostly interested by the cycles and the trend, altho the cycles are relatively more technical to trade and can constitute parasitic fluctuations (think about retracements in a trend affecting your trend indicator, causing potential false signals).
If you are curious, in signal processing combining components has a specific name, "synthesis" , here we are dealing with additive synthesis, other type of synthesis are more specific to audio processing and are relatively more complex, but could be used in technical analysis.
So what to do with our components ? If we want to trade the trend, we should estimate right ? Estimating the trend component involve removing the cycle and noise component from the price, if you have read stuff about filters you should know where i'am going, yep, we should use filters, in the case of keeping the trend we can use a simple moving average of relatively high period, and here we go.
However the lag problem, which is recurrent, come back again, we end up with information easier to interpret (here the trend, which is a simple fluctuation such as a line or other smooth curve) at the cost of decision timing, that is unfortunate but as i said the information, here the moving average output, is relatively simple, and could be easily forecasted right ? If you plot a moving average of high period it would be easier for you to forecast its future values. And thats what we aim to do today, provide an estimate of the trend that should be easy to forecast, and should fit to the price relatively well in order to produce forecast that could determine the position of future closing prices observations.
Estimating And Forecasting The Trend
The parameter of the indicator dealing with the estimation of the trend is length , with higher values of length attenuating the cycle and noise component in the price, note however that high values of length can return a really long term trend unlike a simple moving average, so a small value of length, 14 for example can still produce relatively correct estimate of trend.
here length = 14.
The rough estimate of the trend is t in the code, and is an IIR filter, that is, it is based on recursion. Now i'll pass on the filter design explanation but in short, weights are constants, with higher weights allocated to the previous length values of the filter, you can see on the code that the first part of t is similar to an exponential moving average with :
t(n) = 0.9t(n-length) + 0.1*Price
However while the EMA only use the precedent value for the recursion, here we use the precedent length value, this would just output a noisy and really slow output, therefore in order to create a better fit we add : 0.9*(t(n-length) - t(n-2length)) , and this create the rough trend estimate that you can see in blue. On the parameters, 0.9 is used since it gives the best estimate in my opinion, higher values would create more periodic output and lower values would just create a rougher output.
The blue line still contain a residual of the cycle/noise component, this is why it is smoothed with a simple moving average of period length. If you are curious, a filter estimating the trend but still containing noisy fluctuations is called "Notch" filter, such filter would depending on the cutoff remove/attenuate mid term cyclic fluctuations while preserving the trend and the noise, its the opposite of a bandpass filter.
In order to forecast values, we simply sum our trend estimate with the trend estimate change with period equal to the forecasting horizon period, this is a really really simple forecasting method, but it can produce decent results, it can also allows the forecast to start from the last point of the trend estimate.
Using The Indicator
We explained the length parameter in the precedent section, src is the input series which the trend is estimated, forecast determine the forecasting horizon, recommend values for forecast should be equal to length, length/2 or length*2, altho i strongly recommend length.
here length and forecast are both equal to 14 .
The corrective parameter affect the trend estimate, it reduce the overshoot and can led to a curve that might fit better to the price.
The indicator with the non corrective version above, and the corrective one below.
The source parameter determine the source of the forecast, when "Noisy" is selected the source is the blue line, and produce a noisy forecast, when "Smooth" is selected the source is the moving average of t , this create a smoother forecast.
The width interval control...the width of the intervals, they can be seen above and under the forecast plot, they are constructed by adding/subtracting the forecast with the forecast moving average absolute error with respect to the price. Prediction intervals are often associated with a probability (determining the probability of future values being between the interval) here we can't determine such probability with accuracy, this require (i think) an analysis of the forecasting distribution as well as assumptions on the distribution of the forecasting error.
Finally it is possible to see historical forecasts, that is, forecasts previously generated by checking the "Show Historical Forecasts" option.
Examples
Good forecasts mostly occur when the price is close to the trend estimate, this include the following highlighted periods on AMD 15TF with default settings :
We can see the same thing at the end of EURUSD :
However we can't always obtain suitable fits, here it is isn't sufficient on BTCUSD :
We can see wide intervals, we could change length or use the corrective option to get better results, another option is to use a log scale.
We will end the examples with the log SPX, who posses a linear trend, so for example a linear model such as a linear regression would be really adapted, lets see how the indicator perform :
Not a great fit, we could try to use an higher length value and use "Smooth" :
Most recent fits are quite decent.
Conclusions
A forecasting indicator has been presented in this post. The indicator use an original approach toward estimating the trend component in the closing price. Of course i should have given statistics related to the forecasting error, however such analysis is worth doing with better methods and in more advanced environment allowing for optimization.
But we have learned some stuff related to signal processing as well as time series analysis, seeing a time series as the sum of various components is really helpful when it comes to make sense of chaotic and noisy series and is a basic topic in time series analysis.
You can see that in this new year i work harder on the visual of my indicators without trying to fall in the label addict trap, something that i wasn't really doing before, let me know what do you think of it.
Thanks for reading !
[e2] Reflex & TrendflexNew Indicator from John F. Ehlers issued in the February 2020 Technical Analysis of Stocks and Commodities article "Reflex: A New Zero-Lag Indicator"
This indicator includes both studies described in the article and intend to significantly reduce the lag of the signal compared to other oscillators.
Reflex for the cycle component and is more sensitive to major reversals, Trendflex for the trend component.
Pivot Max range as the borders for top and bottom reading of the indicators (the script will plot separate borders for both components) and divergences were added.
Divergence function is the interpretation of built-in divergence script, optimized the code and added option to show real-time divs (without offset), all credits to ...)
daily*tip: I must say that very quickly I began to realize how fragmented and imperfectly modern economic knowledge is and how little can be taken from fundamental science in terms of practical recipes. (c) Andrey Movchans.
stay safe ;)
Autonomous Recursive Moving AverageIntroduction
People often ask me what is my best indicators, i can't really respond to this question with a straight answer but i would say you to check this indicator. The Autonomous Recursive Moving Average (ARMA) is an adaptive moving average that try to minimize the sum of squares thanks to a ternary operator, this choice can seem surprising since most of the adaptive moving averages adapt to a smoothing variable thanks to exponential averaging, but there are lot of downsides to this method, i really wanted to have a flat filter during flat markets and this is what i achieved.
The Indicator
length control the amount of smoothing during trending periods, gamma is the trend sensitivity threshold, higher values of gamma will make an overall flat filter, adjust gamma to skip ranging markets.
gamma = 2, we can adjust to 3 while preserving smoothing reactivity with trading periods.
gamma = 3
low length and higher gamma create more boxy result, the filter add overshoots directly in the output, its unfortunate.
The Zero-Lag option can reduce the lag as well as getting additional flat results without changing gamma.
Conclusion
The indicator need work, but i can't leave without publishing it, the overshoots are a big problems, changing sma for another stable filter can help. I hope you find an use to it, i really like this indicator.
Thanks for reading
Zero-Lag Smoothed CycleOld indicator ! But its a simple trick to have a zero-lag smoothing effect, i think i did it because the smoothing was kinda asymmetrical with the detrended line. So even if the result appear quite good take into account that the detrended line isn't always correlated with the price.
Fast Z-ScoreIntroduction
The ability of the least squares moving average to provide a great low lag filter is something i always liked, however the least squares moving average can have other uses, one of them is using it with the z-score to provide a fast smoothing oscillator.
The Indicator
The indicator aim to provide fast and smooth results. length control the smoothness.
The calculation is inspired from my sample correlation coefficient estimation described here
Instead of using the difference between a moving average of period length/2 and a moving average of period length , we use the difference between a lsma of period length/2 and a lsma of period length , this difference is then divided by the standard deviation. All those calculations use the price smoothed by a moving average as source.
The yellow version don't divide the difference by a standard deviation, you can that it is less reactive. Both version have length = 200
Conclusion
I presented a smooth and responsive version of a z-score, the result could be used to estimate an even faster lsma by using the line rescaling technique and our indicator as correlation coefficient.
Hope you like it, feel free to modify it and share your results ! :)
Notes
I have been requested a lot of indicators lately, from mt4 translations to more complex time series analysis methods, this accumulation of work made that it is impossible for me to publish those within a short period of time, also some are really complex. I apologize in advance for the inconvenience, i will try to do my best !
Zero Phase Filtering [Repaint] - ExperimentalImportant !
The indicator is for experimental purpose only, it must not be used as a decisional tool but only as a visual one (like Zig-Zag, Fractal etc). The information this indicator display is uncertain and subject to drastic changes over time. If you have further question feel free to pm me.
Introduction
Most of the filters you will find are causal, this mean that they depend on present and past input values, this explain the lag they produce. Non causal filters however will use future input values. A well know way to get a zero-phase filter is by using the forward backward method, but this is not possible in pinescript as i recall. So we have to use some kind of function that will display future values, this is possible using the security function in version 2 or the one in version 3 using barmerge.lookahead_on .
The Use Of A Repainting Indicator
Its always better to filter data in order to have a clearer view of what is happening, this can be useful when doing some forecasting or doing less formal kind of analysis. However since it repaint you cant use it as a signal provider or use signals of other indicators using this filter as source.
For example if you want to forecast a smooth indicator, the forecast of this indicator under normal circumstances could still have lag associated with it, so you would have to react before your forecast, this wont happen if you apply this filter as your indicator source.
The Filter
We smooth with a simple moving average the price provided by the security function twice, length control the smoothing level. Since security depend on the time frame you are in you must select your time frame in the indicator parameter selection window.
Filtering using 45 minutes time frame close price in a 5 minutes chart, we fix this by selecting our time frame.
Consider the fact that the input of the indicator is just periodic price, so sometimes the lag can sometimes be less or more than 0 and the estimation not centered.
The indicator can work on time frames up to 1h, after that the filter have some lag, i tried fixing this and i ended up having data errors.
Applying our filter as source for the rsi oscillator.
Conclusion
It is possible to have a kind of zero-phase filters, but it would be better if pinescript could support backward indexing thus making us able to do forward backward filtering.
Since noise can affect our analysis, applying smoothing without having to use offset in plot can be considered useful.
Light LSMAEstimating the LSMA Without Classics Parameters
I already mentioned various methods in order to estimate the LSMA in the idea i published. The parameter who still appeared on both the previous estimation and the classic LSMA was the sample correlation coefficient. This indicator will use an estimate of the correlation coefficient using the standard score thus providing a totally different approach in the estimation of the LSMA. My motivation for such indicator was to provide a different way to estimate a LSMA.
Standardization
The standard score is a statistical tool used to measure at how many standard deviations o a data point is bellow or above its mean. It can also be used to rescale variables, this conversion process is called standardizing or normalizing and it will be the basis of our estimation.
Calculation : (x - x̄)/o where x̄ is the moving average of x and o the standard deviation.
Estimating the Correlation Coefficient
We will use standardization to estimate the correlation coefficient r . 1 > r > -1 so in (y - x̄)/o we want to find y such that y is always above or below 1 standard deviation of x̄ , i had for first idea to pass the price through a band-stop filter but i found it was better to just use a moving average of period/2 .
Estimating the LSMA
We finally rescale a line through the price like mentioned in my previous idea, for that we standardize a line and we multiply the result by our correlation estimation, next we multiply the previous calculation by the price standard deviation, then we sum this calculation to the price moving average.
Comparison of our estimate in white with a LSMA in red with both period 50 :
Working With Different Independents Variables
Here the independent variable is a line n (which represent the number of data point and thus create a straight line) but a classic LSMA can work with other independent variables, for exemple if a LSMA use the volume as independent variable we need to change our correlation estimate with (ȳ - x̄)/ô where ȳ is the moving average of period length/2 of y, y is equal to : change(close,length)*change(volume,length) , x̄ is the moving average of y of period length , and ô is the standard deviation of y. This is quite rudimentary and if our goal is to provide a easier way to calculate correlation then the product-moment correlation coefficient would be more adapted (but less reactive than the sample correlation) .
Conclusion
I showed a way to estimate the correlation coefficient, of course some tweaking could provide a better estimate but i find the result still quite close to the LSMA.
Zero Lag Exponential Moving AverageZero Lag Exponential Moving Average indicator script based on the original version by John Ehlers and Ric Way
GreenMood inchart MACD Zero LagMACD Zero lag Visual inchart view.
Threshold / Settings can be changed in Format view.
Threshold to be adapted depending on timeframe.