Two Pole Butterworth For Loop [BackQuant]Two Pole Butterworth For Loop
PLEASE read the following carefully, as understanding the underlying concepts and logic behind the indicator is key to incorporating it into your trading system in a sound and methodical manner.
Introducing BackQuant's Two Pole Butterworth For Loop (2P BW FL) — an advanced indicator that fuses the power of the Two Pole Butterworth filter with a dynamic for-loop scoring mechanism. This unique approach is designed to extract actionable trading signals by smoothing out price data and then analyzing it using a comparative scoring method. Let's delve into how this indicator works, why it was created, and how it can be used in various trading scenarios.
Understanding the Two Pole Butterworth Filter
The Butterworth filter is a signal processing tool known for its smooth response and minimal distortion. It's often used in electronic and communication systems to filter out unwanted noise. In trading, the Butterworth filter can be applied to price data to smooth out the volatility, providing traders with a clearer view of underlying trends without the whipsaws often associated with market noise.
The Two Pole Butterworth variant further enhances this effect by applying the filter with two poles, effectively creating a sharper transition between the passband and stopband. In simple terms, this allows the filter to follow the price action more closely, reacting to changes while maintaining smoothness.
In this script, the Two Pole Butterworth filter is applied to the Calculation Source (default is set to the closing price), creating a smoothed price series that serves as the foundation for further analysis.
Why Use a Two Pole Butterworth Filter?
The Two Pole Butterworth filter is chosen for its ability to reduce lag while maintaining a smooth output. This makes it an ideal choice for traders who want to capture trends without being misled by short-term volatility or market noise. By filtering the price data, the Two Pole Butterworth enables traders to focus on the broader market movements and avoid false signals.
The For-Loop Scoring Mechanism
In addition to the Butterworth filter, this script uses a for-loop scoring system to evaluate the smoothed price data. The for-loop compares the current value of the filtered price (referred to as "subject") to previous values over a defined range (set by the start and end input). The score is calculated based on whether the subject is higher or lower than the previous points, and the cumulative score is used to determine the strength of the trend.
Long and Short Signal Logic
Long Signals: A long signal is triggered when the score surpasses the Long Threshold (default set at 40). This suggests that the price has built sufficient upward momentum, indicating a potential buying opportunity.
Short Signals: A short signal is triggered when the score crosses under the Short Threshold (default set at -10). This indicates weakening price action or a potential downtrend, signaling a possible selling or shorting opportunity.
By utilizing this scoring system, the indicator identifies moments when the price momentum is shifting, helping traders enter positions at opportune times.
Customization and Visualization Options
One of the strengths of this indicator is its flexibility. Traders can customize various settings to fit their personal trading style or adapt it to different markets and timeframes:
Calculation Periods: Adjust the lookback period for the Butterworth filter, allowing for shorter or longer smoothing depending on the desired sensitivity.
Threshold Levels: Set the long and short thresholds to define when signals should be triggered, giving you control over the balance between sensitivity and specificity.
Signal Line Width and Colors: Customize the visual presentation of the indicator on the chart, including the width of the signal line and the colors used for long and short conditions.
Candlestick and Background Colors: If desired, the indicator can color the candlesticks or the background according to the detected trend, offering additional clarity at a glance.
Trading Applications
This Two Pole Butterworth For Loop indicator is versatile and can be adapted to various market conditions and trading strategies. Here are a few use cases where this indicator shines:
Trend Following: The Butterworth filter smooths the price data, making it easier to follow trends and identify when they are gaining or losing strength. The for-loop scoring system enhances this by providing a clear indication of how strong the current trend is compared to recent history.
Mean Reversion: For traders looking to identify potential reversals, the indicator’s ability to compare the filtered price to previous values over a range of periods allows it to spot moments when the trend may be losing steam, potentially signaling a reversal.
Swing Trading: The combination of smoothing and scoring allows swing traders to capture short to medium-term price movements by filtering out the noise and focusing on significant shifts in momentum.
Risk Management: By providing clear long and short signals, this indicator helps traders manage their risk by offering well-defined entry and exit points. The smooth nature of the Butterworth filter also reduces the risk of getting caught in false signals due to market noise.
Final Thoughts
The Two Pole Butterworth For Loop indicator offers traders a powerful combination of smoothing and scoring to detect meaningful trends and shifts in price momentum. Whether you are a trend follower, swing trader, or someone looking to refine your entry and exit points, this indicator provides the tools to make more informed trading decisions.
As always, it's essential to backtest the indicator on historical data and tailor the settings to your specific trading style and market. While the Butterworth filter helps reduce noise and smooth trends, no indicator can predict the future with absolute certainty, so it should be used in conjunction with other tools and sound risk management practices.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD

# Butterworth

Adaptive RSI-Stoch with Butterworth Filter [UAlgo]The Adaptive RSI-Stoch with Butterworth Filter is a technical indicator designed to combine the strengths of the Relative Strength Index (RSI), Stochastic Oscillator, and a Butterworth Filter to provide a smooth and adaptive momentum-based trading signal. This custom-built indicator leverages the RSI to measure market momentum, applies Stochastic calculations for overbought/oversold conditions, and incorporates a Butterworth Filter to reduce noise and smooth out price movements for enhanced signal reliability.
By utilizing these combined methods, this indicator aims to help traders identify potential market reversal points, momentum shifts, and overbought/oversold conditions with greater precision, while minimizing false signals in volatile markets.
🔶 Key Features
Adaptive RSI and Stochastic Oscillator: Calculates RSI using a configurable period and applies a dual-smoothing mechanism with Stochastic Oscillator values (K and D lines).
Helps in identifying momentum strength and potential trend reversals.
Butterworth Filter: An advanced signal processing filter that reduces noise and smooths out the indicator values for better trend identification.
The filter can be enabled or disabled based on user preferences.
Customizable Parameters: Flexibility to adjust the length of RSI, the smoothing factors for Stochastic (K and D values), and the Butterworth Filter period.
🔶 Interpreting the Indicator
RSI & Stochastic Calculations:
The RSI is calculated based on the closing price over the user-defined period, and further smoothed to generate Stochastic Oscillator values.
The K and D values of the Stochastic Oscillator provide insights into short-term overbought or oversold conditions.
Butterworth Filter Application:
What is Butterworth Filter and How It Works?
The Butterworth Filter is a type of signal processing filter that is designed to have a maximally flat frequency response in the passband, meaning it doesn’t distort the frequency components of the signal within the desired range. It is widely used in digital signal processing and technical analysis to smooth noisy data while preserving the important trends in the underlying data. In this indicator, the Butterworth Filter is applied to the trigger value, making the resulting signal smoother and more stable by filtering out short-term fluctuations or noise in price data.
Key Concepts Behind the Butterworth Filter:
Filter Design: The Butterworth filter works by calculating weighted averages of current and past inputs (price or indicator values) and outputs to produce a smooth output. It is characterized by the absence of ripple in the passband and a smooth roll-off after the cutoff frequency.
Cutoff Frequency: The period specified in the indicator acts as a control for the cutoff frequency. A higher period means the filter will remove more high-frequency noise and retain longer-term trends, while a lower period means it will respond more to short-term fluctuations in the data.
Smoothing Process: In this script, the Butterworth Filter is calculated recursively using the following formula,
butterworth_filter(series float input, int period) =>
float wc = math.tan(math.pi / period)
float k1 = 1.414 * wc
float k2 = wc * wc
float a0 = k2 / (1 + k1 + k2)
float a1 = 2 * a0
float a2 = a0
float b1 = 2 * (k2 - 1) / (1 + k1 + k2)
float b2 = (1 - k1 + k2) / (1 + k1 + k2)
wc: This is the angular frequency, derived from the period input.
k1 and k2: These are intermediate coefficients used in the filter calculation.
a0, a1, a2: These are the feedforward coefficients, which determine how much of the current and past input values will contribute to the filtered output.
b1, b2: These are feedback coefficients, which determine how much of the past output values will contribute to the current output, effectively allowing the filter to "remember" past behavior and smooth the signal.
Recursive Calculation: The filter operates by taking into account not only the current input value but also the previous two input values and the previous two output values. This recursive nature helps it smooth the signal by blending the recent past data with the current data.
float filtered_value = a0 * input + a1 * prev_input1 + a2 * prev_input2
filtered_value -= b1 * prev_output1 + b2 * prev_output2
input: The current input value, which could be the trigger value in this case.
prev_input1, prev_input2: The previous two input values.
prev_output1, prev_output2: The previous two output values.
This means the current filtered value is determined by the combination of:
A weighted sum of the current input and the last two inputs.
A correction based on the last two output values to ensure smoothness and remove noise.
In conclusion when filter is enabled, the Butterworth Filter smooths the RSI and Stochastic values to reduce market noise and highlight significant momentum shifts.
The filtered trigger value (post-Butterworth) provides a cleaner representation of the market's momentum.
Cross Signals for Trade Entries:
Buy Signal: A bullish crossover of the K value above the D value, particularly when the values are below 40 and when the Stochastic trigger is below 1 and the filtered trigger is below 35.
Sell Signal: A bearish crossunder of the K value below the D value, particularly when the values are above 60 and when the Stochastic trigger is above 99 and the filtered trigger is above 90.
These signals are plotted visually on the chart for easy identification of potential trading opportunities.
Overbought and Oversold Zones:
The indicator highlights the overbought zone when the filtered trigger surpasses a specific threshold (typically above 100) and the oversold zone when it drops below 0.
The color-coded fill areas between the Stochastic and trigger lines help visualize when the market may be overbought (likely a reversal down) or oversold (potential reversal up).
🔶 Disclaimer
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.

WaveTrend 3D█ OVERVIEW
WaveTrend 3D (WT3D) is a novel implementation of the famous WaveTrend (WT) indicator and has been completely redesigned from the ground up to address some of the inherent shortcomings associated with the traditional WT algorithm.
█ BACKGROUND
The WaveTrend (WT) indicator has become a widely popular tool for traders in recent years. WT was first ported to PineScript in 2014 by the user @LazyBear, and since then, it has ascended to become one of the Top 5 most popular scripts on TradingView.
The WT algorithm appears to have origins in a lesser-known proprietary algorithm called Trading Channel Index (TCI), created by AIQ Systems in 1986 as an integral part of their commercial software suite, TradingExpert Pro. The software’s reference manual states that “TCI identifies changes in price direction” and is “an adaptation of Donald R. Lambert’s Commodity Channel Index (CCI)”, which was introduced to the world six years earlier in 1980. Interestingly, a vestige of this early beginning can still be seen in the source code of LazyBear’s script, where the final EMA calculation is stored in an intermediate variable called “tci” in the code.
█ IMPLEMENTATION DETAILS
WaveTrend 3D is an alternative implementation of WaveTrend that directly addresses some of the known shortcomings of the indicator, including its unbounded extremes, susceptibility to whipsaw, and lack of insight into other timeframes.
In the canonical WT approach, an exponential moving average (EMA) for a given lookback window is used to assess the variability between price and two other EMAs relative to a second lookback window. Since the difference between the average price and its associated EMA is essentially unbounded, an arbitrary scaling factor of 0.015 is typically applied as a crude form of rescaling but still fails to capture 20-30% of values between the range of -100 to 100. Additionally, the trigger signal for the final EMA (i.e., TCI) crossover-based oscillator is a four-bar simple moving average (SMA), which further contributes to the net lag accumulated by the consecutive EMA calculations in the previous steps.
The core idea behind WT3D is to replace the EMA-based crossover system with modern Digital Signal Processing techniques. By assuming that price action adheres approximately to a Gaussian distribution, it is possible to sidestep the scaling nightmare associated with unbounded price differentials of the original WaveTrend method by focusing instead on the alteration of the underlying Probability Distribution Function (PDF) of the input series. Furthermore, using a signal processing filter such as a Butterworth Filter, we can eliminate the need for consecutive exponential moving averages along with the associated lag they bring.
Ideally, it is convenient to have the resulting probability distribution oscillate between the values of -1 and 1, with the zero line serving as a median. With this objective in mind, it is possible to borrow a common technique from the field of Machine Learning that uses a sigmoid-like activation function to transform our data set of interest. One such function is the hyperbolic tangent function (tanh), which is often used as an activation function in the hidden layers of neural networks due to its unique property of ensuring the values stay between -1 and 1. By taking the first-order derivative of our input series and normalizing it using the quadratic mean, the tanh function performs a high-quality redistribution of the input signal into the desired range of -1 to 1. Finally, using a dual-pole filter such as the Butterworth Filter popularized by John Ehlers, excessive market noise can be filtered out, leaving behind a crisp moving average with minimal lag.
Furthermore, WT3D expands upon the original functionality of WT by providing:
First-class support for multi-timeframe (MTF) analysis
Kernel-based regression for trend reversal confirmation
Various options for signal smoothing and transformation
A unique mode for visualizing an input series as a symmetrical, three-dimensional waveform useful for pattern identification and cycle-related analysis
█ SETTINGS
This is a summary of the settings used in the script listed in roughly the order in which they appear. By default, all default colors are from Google's TensorFlow framework and are considered to be colorblind safe.
Source: The input series. Usually, it is the close or average price, but it can be any series.
Use Mirror: Whether to display a mirror image of the source series; for visualizing the series as a 3D waveform similar to a soundwave.
Use EMA: Whether to use an exponential moving average of the input series.
EMA Length: The length of the exponential moving average.
Use COG: Whether to use the center of gravity of the input series.
COG Length: The length of the center of gravity.
Speed to Emphasize: The target speed to emphasize.
Width: The width of the emphasized line.
Display Kernel Moving Average: Whether to display the kernel moving average of the signal. Like PCA, an unsupervised Machine Learning technique whereby neighboring vectors are projected onto the Principal Component.
Display Kernel Signal: Whether to display the kernel estimator for the emphasized line. Like the Kernel MA, it can show underlying shifts in bias within a more significant trend by the colors reflected on the ribbon itself.
Show Oscillator Lines: Whether to show the oscillator lines.
Offset: The offset of the emphasized oscillator plots.
Fast Length: The length scale factor for the fast oscillator.
Fast Smoothing: The smoothing scale factor for the fast oscillator.
Normal Length: The length scale factor for the normal oscillator.
Normal Smoothing: The smoothing scale factor for the normal frequency.
Slow Length: The length scale factor for the slow oscillator.
Slow Smoothing: The smoothing scale factor for the slow frequency.
Divergence Threshold: The number of bars for the divergence to be considered significant.
Trigger Wave Percent Size: How big the current wave should be relative to the previous wave.
Background Area Transparency Factor: Transparency factor for the background area.
Foreground Area Transparency Factor: Transparency factor for the foreground area.
Background Line Transparency Factor: Transparency factor for the background line.
Foreground Line Transparency Factor: Transparency factor for the foreground line.
Custom Transparency: Transparency of the custom colors.
Total Gradient Steps: The maximum amount of steps supported for a gradient calculation is 256.
Fast Bullish Color: The color of the fast bullish line.
Normal Bullish Color: The color of the normal bullish line.
Slow Bullish Color: The color of the slow bullish line.
Fast Bearish Color: The color of the fast bearish line.
Normal Bearish Color: The color of the normal bearish line.
Slow Bearish Color: The color of the slow bearish line.
Bullish Divergence Signals: The color of the bullish divergence signals.
Bearish Divergence Signals: The color of the bearish divergence signals.
█ ACKNOWLEDGEMENTS
@LazyBear - For authoring the original WaveTrend port on TradingView
@PineCoders - For the beautiful color gradient framework used in this indicator
@veryfid - For the inspiration of using mirrored signals for cycle analysis and using multiple lookback windows as proxies for other timeframes

[DSPrated] Modified EMD for swing tradeModified Ehlers Empirical Mode Decomposition indicator for swing trade based on Butterworth 2nd order IIR filter
Description
This script is inspired by John Ehlers' TECHNICAL PAPERS - Truncating Indicators and Empirical Mode Decomposition. But instead of detecting trend it applies to finding swing regions.
Also here is suggested canonical DSP approach for designing coefficients for Butterworth 2nd order IIR filters - bandpass and lowpass.
Besides, truncated IIR filter with configurable length parameter is used. It worth mentioning, that although truncated filter is more robust than original IIR, it losses specified properties (bandpass) the more, the less is length parameter.
Butterworth Bandpass Infinite Impulse Response (IIR) Filter
This is the 2nd order Butterworth Bandpass Infinite Impulse Response (IIR) Filter based on the transform from the 1st order lowpass
Based on the example 8.8 on p476 from book Digital Signal Processing: A Practical Approach 2nd Edition by Emmanuel C. Ifeachor (Author), Barrie W. Jervis (Author)
It differs from Ehlers BandPass Filter only in the way you initialize input parameters. Here you can define cutoff periods of region of interest. For example on a timeframe, where one bar equals 1 hour you can define periods 18 and 22, which mean you'll see the swing intensity of price movement components within specified range.
Parameters
Source
Period 1 - cutoff period of bandpass begining
Period 2 - cutoff period of the end of bandpass
length - IIR truncation length
Concept of usage
Within specified bandpass this indicator eliminates the Trend line according to Ehlers EMD. The bandpass periods is recommended to choose accordingly to personal comfortable trading style and timeframe.
The trendline painted with 3 colors depending of the next modes:
up tend - green
cycling - black
downtrend - red
So the buy signal is generated when trend line in cycling mode and filtered component reaches it local minimum.
And the sell signal is generated when trend line in cycling mode and filtered component reaches it local maximum.
Secure long and short zones marked with color.
---
// TO DO
// - compare truncated and full version using signal generators
// - apply zero lag filter modification fordetectig ternd and swing peroids
// - implement strategy scripts
// - implement somewhat "true" EMD with sevral IMFs(intrinsic mode function)
// - better description?
// - parameter optimization
---
Please, feel free to report any issues and improvement suggestions.

[blackcat] L2 Ehlers Three Pole Butterworth FilterLevel: 2
Background
John F. Ehlers introuced Three-Pole Butterworth Filter in his "Cybernetic Analysis for Stocks and Futures" chapter 13 on 2004.
Function
The transfer responses of Butterworth filters have polynomials in both the numerator and denominator. There is a polynomial in the numerator as well as the denominator. The significance of the polynomial in the numerator is that it represents the finite impulse response (FIR) part of the filter. This part is like a simple moving average. The denominator forms the iterative part of the filter calculation and is the infinite impulse response (IIR) part of the filter. The FIR part of the filter sharpens the filter rejection response, but it also contributes to lag in the response. Recognizing that the parts of a Butterworth filter are separable, Dr. Ehlers formed the multipole super smoothing filters by simply deleting the polynomial in the numerator. Butterworth filters can have an arbitrarily large number of poles. The passband of Butterworth filters is prescribed by a single parameter. That parameter is the Cutoff Period, where the attenuation of the filter is 3 dB.
Key Signal
Butter ---> Two Pole Butterworth Filter fast line
Trigger ---> Two Pole Butterworth Filter slow line
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 30th 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.

[blackcat] L2 Ehlers Two Pole Butterworth FilterLevel: 2
Background
John F. Ehlers introuced Two Pole Butterworth Filter in his "Cybernetic Analysis for Stocks and Futures" chapter 13 on 2004.
Function
Dr. Ehlers translated analog Butterworth filters to their digital approximations. The transfer response is characterized by a single variable—the cutoff frequency. The cutoff frequency is that frequency where the input is attenuated by 3 dB. Below the cutoff frequency, the input frequency components are passed to the output; above the cutoff frequency, the input frequency components are rejected to the extent possible by the filter characteristics. Since traders are more comfortable with period, which is the reciprocal of frequency, the equations for the Butterworth digital filters are characterized in terms of the cutoff period.
As opposed to the Regularized filter, the order of Butterworth filters can be increased indefinitely to increase the sharpness of the filter rejection. For traders, this quickly reaches the point of diminishing returns because increasing the number of poles in the filter means the lag of the filter is also increased. A three-pole filter gives just about the limit of tolerable lag for a selected cutoff period.
Key Signal
Butter ---> Two Pole Butterworth Filter fast line
Trigger ---> Two Pole Butterworth Filter slow line
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 29th 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.

Ehlers 3 Pole Butterworth Filter V2 [CC]The 3 Pole Butterworth Filter was created by John Ehlers (Cybernetic Analysis For Stocks And Futures pgs 196-197) and this indicator is a moving average that also works well as a trendline. Buy when the indicator line turns green and sell when it turns red.
Let me know if you would like me to publish other indicators or if you want something custom done!

Resampling Filter Pack [DW]This is an experimental study that calculates filter values at user defined sample rates.
This study is aimed to provide users with alternative functions for filtering price at custom sample rates.
First, source data is resampled using the desired rate and cycle offset. The highest possible rate is 1 bar per sample (BPS).
There are three resampling methods to choose from:
-> BPS - Resamples based on the number of bars.
-> Interval - Resamples based on time in multiples of current charting timeframe.
-> PA - Resamples based on changes in price action by a specified size. The PA algorithm in this script is derived from my Range Filter algorithm.
The range for PA method can be sized in points, pips, ticks, % of price, ATR, average change, and absolute quantity.
Then, the data is passed through one of my custom built filter functions designed to calculate filter values upon trigger conditions rather than bars.
In this study, these functions are used to calculate resampled prices based on bar rates, but they can be used and modified for a number of purposes.
The available conditional sampling filters in this study are:
-> Simple Moving Average (SMA)
-> Exponential Moving Average (EMA)
-> Zero Lag Exponential Moving Average (ZLEMA)
-> Double Exponential Moving Average (DEMA)
-> Rolling Moving Average (RMA)
-> Weighted Moving Average (WMA)
-> Hull Moving Average (HMA)
-> Exponentially Weighted Hull Moving Average (EWHMA)
-> Two Pole Butterworth Low Pass Filter (BLP)
-> Two Pole Gaussian Low Pass Filter (GLP)
-> Super Smoother Filter (SSF)
Downsampling is a powerful filtering approach that can be applied in numerous ways. However, it does suffer from a trade off, like most studies do.
Reducing the sample rate will completely eliminate certain levels of noise, at the cost of some spectral distortion. The lower your sample rate is, the more distortion you'll see.
With that being said, for analyzing trends, downsampling may prove to be one of your best friends!

Ehlers 2 Pole Butterworth Filter V2 [CC]The 2 Pole Butterworth Filter was created by John Ehlers (Cycle Analytics For Traders pg 32) and this is an updated version of his original 2 pole Butterworth Filter script that seems to follow the price even closer. Buy when the indicator line turns green and sell when it turns red.
Let me know if there are other scripts you would like to see me publish or if you want something custom done!

Ehlers 2 Pole Butterworth Filter V1 [CC]The 2 Pole Butterworth Filter was created by John Ehlers (Cybernetic Analysis For Stocks And Futures pg 192) and this is one of his many filters that cuts out the noise and follows the price very closely. I recommend combining a 2 pole and 3 pole system of the same type of filter. Buy when the indicator line is green and sell when it is red.
Let me know if there are other indicators you would like to see or if you want something custom done!

Ehlers 3 Pole Butterworth Filter [CC]The 3 Pole Butterworth Filter was created by John Ehlers (Cycle Analytics For Traders pg 32) and this is a nice filter that follows the price very closely. Buy when the indicator is green and sell when it turns red.
This was a custom request so let me know if you would like me to publish any other scripts or if you want something custom done!

Roofing Filter [DW]This is an experimental study built on the concept of using roofing filters on price data proposed by John Ehlers.
Roofing filters are a type of bandpass filter conventionally used in HF radio receivers in the first IF stage to limit the frequency spectrum passed on to later stages in the receiver.
The goal in applying roofing filters to a price signal is to simultaneously attenuate high frequency noise and low frequency distortion to pass an oscillating signal with a nearly zero mean for analysis and/or further calculation.
In this study, there are three filter types to choose from:
-> Ehlers Roofing Filter, which passes data through a 2 pole high pass filter, then through a Super Smoother filter.
-> Gaussian Roofing Filter, which passes data through a 2 pole Gaussian high pass filter, then through a 2 pole Gaussian low pass filter.
-> Butterworth Roofing Filter, which passes data through a 2 pole Butterworth high pass filter, then through a 2 pole Butterworth low pass filter.
Each filter type has different amplitude and delay characteristics, so play around with each type and see which response suits your needs best.
There is an option to normalize the scale of the output as well. The normalization process in this script is computed by comparing positive and negative outputs to the filter's moving RMS value.
The resulting oscillator can be fed through numerous conventional indicators including Stochastic Oscillator, RSI, CCI, etc. to generate smoother, less distorted indicators for a clearer view of turning points.
Alternatively, it can also act as an indicator itself, as implied by the corresponding color scheme included in the script.
Although roofing filters are not conventionally used in the analysis of market data, applying such spectral analysis techniques may prove to be quite useful for the design of more efficient indicators and more reliable predictions.

Butterworth FilterButterworth Filter script.
This indicator was described by John F. Ehlers in his book "Rocket Science for Traders" (2001, Chapter 15: Infinite Impulse Response Filters).

Rate of Change w/ Butterworth FilterIt passes the Rate of Change data through a Butterworth filter which creates a smooth line that can allow for easier detection of slope changes in the data over various periods of times.
The butterworth filter line and the rate of change are plotted together by default. The values for the lengths, for both the butterworth filter and the raw ROC data, can be changed from the format menu (through a toggle).
The shorter the Butterworth length, the closer the line is fitted to the raw ROC data, however you trade of with more frequent slope changes.
The longer the Butterworth length, the smoother the line and less frequent the slope changes, but the Butterworth line is farther of center from the raw ROC data.