General Filter Estimator-An Experiment on Estimating EverythingIntroduction
The last indicators i posted where about estimating the least squares moving average, the task of estimating a filter is a funny one because its always a challenge and it require to be really creative. After the last publication of the 1LC-LSMA , who estimate the lsma with 1 line of code and only 3 functions i felt like i could maybe make something more flexible and less complex with the ability to approximate any filter output. Its possible, but the methods to do so are not something that pinescript can do, we have to use another base for our estimation using coefficients, so i inspired myself from the alpha-beta filter and i started writing the code.
Calculation and The Estimation Coefficients
Simplicity is the key word, its also my signature style, if i want something good it should be simple enough, so my code look like that :
p = length/beta
a = close - nz(b ,close)
b = nz(b ,close) + a/p*gamma
3 line, 2 function, its a good start, we could put everything in one line of code but its easier to see it this way. length control the smoothing amount of the filter, for any filter f(Period) Period should be equal to length and f(Period) = p , it would be inconvenient to have to use a different length period than the one used in the filter we want to estimate (imagine our estimation with length = 50 estimating an ema with period = 100) , this is where the first coefficients beta will be useful, it will allow us to leave length as it is. In general beta will be greater than 1, the greater it will be the less lag the filter will have, this coefficient will be useful to estimate low lagging filters, gamma however is the coefficient who will estimate lagging filters, in general it will range around .
We can get loose easily with those coefficients estimation but i will leave a coefficients table in the code for estimating popular filters, and some comparison below.
Estimating a Simple Moving Average
Of course, the boxcar filter, the running mean, the simple moving average, its an easy filter to use and calculate.
For an SMA use the following coefficients :
beta = 2
gamma = 0.5
Our filter is in red and the moving average in white with both length at 50 (This goes for every comparison we will do)
Its a bit imprecise but its a simple moving average, not the most interesting thing to estimate.
Estimating an Exponential Moving Average
The ema is a great filter because its length times more computing efficient than a simple moving average. For the EMA use the following coefficients :
beta = 3
gamma = 0.4
N.B : The EMA is rougher than the SMA, so it filter less, this is why its faster and closer to the price
Estimating The Hull Moving Average
Its a good filter for technical analysis with tons of use, lets try to estimate it ! For the HMA use the following coefficients :
beta = 4
gamma = 0.85
Looks ok, of course if you find better coefficients i will test them and actualize the coefficient table, i will also put a thank message.
Estimating a LSMA
Of course i was gonna estimate it, but this time this estimation does not have anything a lsma have, no moving average, no standard deviation, no correlation coefficient, lets do it.
For the LSMA use the following coefficients :
beta = 3.5
gamma = 0.9
Its far from being the best estimation, but its more efficient than any other i previously made.
Estimating the Quadratic Least Square Moving Average
I doubted about this one but it can be approximated as well. For the QLSMA use the following coefficients :
beta = 5.25
gamma = 1
Another ok estimate, the estimate filter a bit more than needed but its ok.
Jurik Moving Average
Its far from being a filter that i like and its a bit old. For the comparison i will use the JMA provided by @everget described in this article : c.mql5.com
For the JMA use the following coefficients :
for phase = 0
beta = pow*2 (pow is a parameter in the Jma)
gamma = 0.5
Here length = 50, phase = 0, pow = 5 so beta = 10
Looks pretty good considering the fact that the Jma use an adaptive architecture.
Discussion
I let you the task to judge if the estimation is good or not, my motivation was to estimate such filters using the less amount of calculations as possible, in itself i think that the code is quite elegant like all the codes of IIR filters (IIR Filters = Infinite Impulse Response : Filters using recursion) .
It could be possible to have a better estimate of the coefficients using optimization methods like the gradient descent. This is not feasible in pinescript but i could think about it using python or R.
Coefficients should be dependant of length but this would lead to a massive work, the variation of the estimation using fixed coefficients when using different length periods is just ok if we can allow some errors of precision.
I dont think it should be possible to estimate adaptive filter relying a lot on their adaptive parameter/smoothing constant except by making our coefficients adaptive (gamma could be)
So at the end ? What make a filter truly unique ? From my point of sight the architecture of a filter and the problem he is trying to solve is what make him unique rather than its output result. If you become a signal, hide yourself into noise, then look at the filters trying to find you, what a challenging game, this is why we need filters.
Conclusion
I wanted to give a simple filter estimator relying on two coefficients in order to estimate both lagging and low-lagging filters. I will try to give more precise estimate and update the indicator with new coefficients.
Thanks for reading !
Komut dosyalarını "富时中国50三倍做空" için ara
BTC Volume Index [v2018-11-21] @ LekkerCryptisch.nlIndicates the volume trend:
~50 = short term volume is the same as long term volume
> 50 = short term volume is higher than long term volume (i.e. trend is rising volume)
< 50 = short term volume is lower than long term volume (i.e. trend is declining volume)
Reverse Engineered RSI - Key Levels + MTFThis indicator overlays 5 Reverse Engineered RSI (RERSI) levels on your main chart window.
The RERSI was first developed by Giorgos Siligardos in the June 2003 issue of Stocks and Commodities Magazine. HPotter provided the initial implementation - from which this script is derived - so all credit to them (see: ).
In simple terms, RERSI plots lines on the price chart that reflect levels of the RSI . E.g. if you set up a RERSI line at a level of 50, then price will touch that line when the standard RSI indicator reads 50. Hopefully that makes sense, but compare the two if it doesn't.
Why is the RERSI useful if it's just plotting RSI values? Well, it simplifies things, and enables you to get a clearer picture of trend direction, RSI support and resistance levels, RSI trading signals, and it keeps your chart window uncluttered.
I've set up 5 RERSI lines to be plotted: Overbought and Oversold Levels, a Middle Level (generally leave this at 50), and then Down/Up Trend Lines. The latter two are loosely based on the work of Constance Brown (and they in turn were influenced by Andrew Brown), who posited that RSI doesn't breach certain levels during trends (e.g. 40-50 is often a support level during an uptrend).
Play around with the levels, and the RSI Length, to see how your particular market reacts, and where key levels may lie. Remember, this isn't meant as a stand-alone system (although I think there's potential to use it as such, especially with price action trading - which I guess wouldn't make it stand-alone then!!), and works best with confirmation from other sources.
Oh, and there's MTF capability, because I think that's useful for all indicators.
Any queries, please let me know.
Cheers,
RJR
Better RSI with bullish / bearish market cycle indicator This script improves the default RSI. First. it identifies regions of the RSI which are oversold and overbought by changing the color of RSI from white to red. Second, it adds additional reference lines at 20,40,50,60, and 80 to better gauge the RSI value. Finally, the coolest feature, the middle 50 line is used to indicate which cycle the price is currently at. A green color at the 50 line indicates a bullish cycle, a red color indicators a bearish cycle, and a white color indicates a neutral cycle.
The cycles are determined using the RSI as follows:
if RSI is overbought, cycle switches to bullish until RSI falls below 40, at which point it becomes neutral
if RSI is oversold, cycle switches bearish until RSI rises above 60, at which point it becomes neutral
a neutral cycle is exited at either overbought or oversold conditions
Very useful, please give it a try and let me know what you think
ACM22 not repaintedДелал данный скрипт для FORTS.Идеально подойдет тем,кто использует трейлинг стопы.В основе стратегии лежит RSI.Как по мне,хорошая вещь для проверки стратегии и ее оптимизиации.На скрине 50 контрактов,так что не сильно радуйтесь,а просто делите на 50 и получите показатели на 1 контракт.
Script make for futures on MICEX.U can change paramets of RSI,traling stop and stop loss .On a ps 50 futures USDollar-russian ruble.Use for testing and optimisation.
Inertia Indicator The inertia indicator measures the market, stock or currency pair momentum and
trend by measuring the security smoothed RVI (Relative Volatility Index).
The RVI is a technical indicator that estimates the general direction of the
volatility of an asset.
The inertia indicator returns a value that is comprised between 0 and 100.
Positive inertia occurs when the indicator value is higher than 50. As long as
the inertia value is above 50, the long-term trend of the security is up. The inertia
is negative when its value is lower than 50, in this case the long-term trend is
down and should stay down if the inertia stays below 50
GC RSI Columns V2016This is a basic RSI indicator but in column format.I had been using this for a while and it gives a nice visual representation of trend change by changing color of the column.
Base line is 50 level. Anything above 50 is buy opportunity and below 50 is sell opportunity . Try it on higher time frames and see the results.
Example on chart above.
Note: i published it on demand. many folks were asking me for this ,since it(column rsi) was not available in public indicators
Golden Cross, SMA 200 Moving Average Strategy (by ChartArt)This famous moving average strategy is very easy to follow to decide when to buy (go long) and when to take profit.
The strategy goes long when the faster SMA 50 (the simple moving average of the last 50 bars) crosses above the slower SMA 200. Orders are closed when the SMA 50 crosses below the SMA 200. This simple strategy does not have any other stop loss or take profit money management logic. The strategy does not short and goes long only!
Here is an article explaining the "golden cross" strategy in more detail:
www.stockopedia.com
On the S&P 500 index (symbol "SPX") this strategy worked on the daily chart 81% since price data is available since 1982. And on the DOW Jones Industrial Average (symbol "DOWI") this strategy worked on the daily chart 55% since price data is available since 1916. The low number of trades is in both cases not statistically significant though.
All trading involves high risk; past performance is not necessarily indicative of future results. Hypothetical or simulated performance results have certain inherent limitations. Unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not actually been executed, the results may have under- or over-compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown.
Forex Master v4.0 (EUR/USD Mean-Reversion Algorithm)DESCRIPTION
Forex Master v4.0 is a mean-reversion algorithm currently optimized for trading the EUR/USD pair on the 5M chart interval. All indicator inputs use the period's closing price and all trades are executed at the open of the period following the period where the trade signal was generated.
There are 3 main components that make up Forex Master v4.0:
I. Trend Filter
The algorithm uses a version of the ADX indicator as a trend filter to trade only in certain time periods where price is more likely to be range-bound (i.e., mean-reverting). This indicator is composed of a Fast ADX and a Slow ADX, both using the same look-back period of 50. However, the Fast ADX is smoothed with a 6-period EMA and the Slow ADX is smoothed with a 12-period EMA. When the Fast ADX is above the Slow ADX, the algorithm does not trade because this indicates that price is likelier to trend, which is bad for a mean-reversion system. Conversely, when the Fast ADX is below the Slow ADX, price is likelier to be ranging so this is the only time when the algorithm is allowed to trade.
II. Bollinger Bands
When allowed to trade by the Trend Filter, the algorithm uses the Bollinger Bands indicator to enter long and short positions. The Bolliger Bands indicator has a look-back period of 20 and a standard deviation of 1.5 for both upper and lower bands. When price crosses over the lower band, a Long Signal is generated and a long position is entered. When price crosses under the upper band, a Short Signal is generated and a short position is entered.
III. Money Management
Rule 1 - Each trade will use a limit order for a fixed quantity of 50,000 contracts (0.50 lot). The only exception is Rule
Rule 2 - Order pyramiding is enabled and up to 10 consecutive orders of the same signal can be executed (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts).
Rule 3 - Every order will include a bracket with both TP and SL set at 50 pips (note: the algorithm only closes the current open position and does not enter the opposite trade once a TP or SL has been hit).
Rule 4 - When a new opposite trade signal is generated, the algorithm sends in a larger order to close the current open position as well as open a new one (for example: 14 consecutive Long Signals are generated over 8 hours and the algorithm sends in 10 different buy orders at various prices for a total of 350,000 contracts. A Short Signal is generated shortly after the 14th Long Signal. The algorithm then sends in a sell order for 400,000 contracts to close the 350,000 contracts long position and open a new short position of 50,000 contracts).
RSI-EMA IndicatorThis indicator calculates and plots 2 separate EMAs of the RSI. The default settings below work great on SPX/SPY daily chart. General rule is if an EMA is above 50, the stock's near term outlook is bullish. If an EMA is below 50, the near term outlook is bearish. Personally, I like to use a fast EMA as a buy signal and a slow EMA as a sell signal.
Default settings:
RSI = 50
EMA1 = 100
EMA2 = 200
High-Low Index [LazyBear]-- Fixed ---
Source: pastebin.com
Fixes an issue with "Combined" mode, using wrong symbols.
--- Original ---
The High-Low Index is a breadth indicator based on Record High Percent, which is based on new 52-week highs and new 52-week lows.
Readings below 50 indicate that there were more new lows than new highs. Readings above 50 indicate that there were more new highs than new lows. 0 indicates there were zero new highs (0% new highs). 100 indicates there was at least 1 new high and no new lows (100% new highs). 50 indicates that new highs and new lows were equal (50% new highs).
Readings consistently above 70 usually coincide with a strong uptrend. Readings consistently below 30 usually coincide with a strong downtrend.
More info:
stockcharts.com
List of my public indicators: bit.ly
List of my app-store indicators: blog.tradingview.com
Just noticed @Greeny has already published this -> Linking it here.
TimWest Long Short FiltersTimWest Long Short Filters
Indicator Has 3 Separate Filters that Create Green(Bullish) or Red(Bearish) BackGround Highlights
If Price is Above or Below a certain LookBack Period - Tim Defaults to 63 on Daily Chart to Quickly View if Price is Above or Below it’s Price 1 Quarter Ago.
A Simple Moving Average Filter - Tim Defaults to 50 SMA and 200 SMA also known as the “Golden Cross”.
A Exponential Moving Average Filter - For Those Who Want To View Shorter Term Market Swings. Defaults to 50 EMA and 100 EMA used By Chuck Hughes, 7 Time World Trading Champion. Chuck Claims the 50/100 EMA's Show the Earliest Change in Market Direction the Equal - Sustainable Moves
Inputs Tab has Checkboxes to Turn On/Off any of the 3 Filters Above.
Reference Chart Post www.tradingview.com
3 projection Indicators - PBands, PO & PBAll these indicators are by Mel Widner.
Projection Bands :
-------------------------------------------------------
These project market data along the trend with the maxima and minima of the projections defining the band. The method provides a way to signal potential direction changes relative to the trend. Usage is like any other trading band.
Projection Oscillator :
-------------------------------------------------------
This indicates the relative position of price with in the bands. It fluctuates between the values 0 to 100. You can configure the "basis" to make it oscillate around a specific value (for ex., basis=50 will make it oscillate between +50 and -50). EMA of PO (length configurable, default is 5) is plotted as a signal line. There is also an option to plot the difference (oscillator - signal), just like MACD histogram. When you see a divergence in this oscillator, remember that it just indicates a potential movement with in the band (for ex., a bullish divergence shown may cause the price to cross the median and move up to the top band).
Projection Bandwidth :
-------------------------------------------------------
This shows the % width of the projection bands. A trend reversal is signaled by a high value. Low value may indicate the start of a new trend. This is also a trend strength indicator.
More info: drive.google.com
Borrowed the color theme for this chart from @liw0. Thanks :)
Frank-Setup EMA, RS & RSI ✅It is a clean and simple indicator designed to identify weakness in stocks using two proven methods: RSI and Relative Strength (RS) vs. a benchmark (e.g., NIFTY).
🔹 Features
RSI Weakness Signals
Plots when RSI crosses below 50 (weakness begins).
Plots when RSI moves back above 50 (weakness ends).
Relative Strength (RS) vs Benchmark
Compares stock performance to a chosen benchmark.
Signals when RS drops below 1 (stock underperforming).
Signals when RS recovers above 1 (strength resumes).
Clear Visual Markers
Circles for RSI signals.
Triangles for RS signals.
Optional RSI labels for clarity.
Built-in Alerts
Get notified instantly when RSI or RS weakness starts or ends.
No need to constantly watch charts.
🎯 Use Case
This tool is built for traders who want to:
Spot shorting opportunities when a stock shows weakness.
Track underperformance vs. the index.
Manage risk by exiting longs when weakness appears.
Frank-Setup ✅ (RSI + RS only)Frank-Shorting Setup ✅ is an indicator designed to help traders spot weakness in a stock by combining RSI and Relative Strength (RS) analysis.
🔹 Key Features
RSI Weakness Signals
Marks when RSI falls below 50 (downside pressure begins).
Marks when RSI moves back above 50 (weakness ends).
Relative Strength (RS) vs Benchmark
Compares stock performance to a benchmark (e.g., NIFTY).
Signals when RS drops below 1 (stock underperforming).
Signals when RS moves back above 1 (strength resumes).
Clear Chart Markings
Circles for RSI signals.
Triangles for RS signals.
Optional labels for extra clarity.
Alerts Built-In
Get notified when RSI or RS weakness starts/ends.
No need to monitor charts all the time
Frank-Shorting Setup ✅ (RSI + RS only)An indicator designed to help traders spot weakness in a stock by combining RSI and Relative Strength (RS) analysis.
🔹 Key Features
RSI Weakness Signals
Marks when RSI falls below 50 (downside pressure begins).
Marks when RSI moves back above 50 (weakness ends).
Relative Strength (RS) vs Benchmark
Compares stock performance to a benchmark (e.g., NIFTY).
Signals when RS drops below 1 (stock underperforming).
Signals when RS moves back above 1 (strength resumes).
Clear Chart Markings
Circles for RSI signals.
Triangles for RS signals.
Optional labels for extra clarity.
Alerts Built-In
Get notified when RSI or RS weakness starts/ends.
No need to monitor charts all the time
Swing Z | Zillennial Technologies Inc.Swing Z by Zillennial Technologies Inc. is an advanced algorithmic framework built specifically for cryptocurrency markets. It integrates multiple layers of technical analysis into a single decision-support tool, generating buy and sell signals only when several independent confirmations align.
Core Concept
Swing Z fuses trend structure, momentum oscillators, volatility signals, and price action tools to capture high-probability trading opportunities in volatile crypto environments.
Trend Structure (EMA 9, 21, 50, 200)
Short-term EMAs (9 & 21) detect immediate momentum shifts.
Longer-term EMAs (50 & 200) define the broader trend and dynamic support/resistance.
Momentum & Confirmation Layer
RSI measures relative strength and market conditions.
MACD crossovers confirm momentum shifts and trend continuations.
Volatility & Market Pressure
TTM Squeeze highlights compression zones likely to precede breakouts.
Volume analysis confirms conviction behind directional moves.
VWAP (Volume Weighted Average Price) establishes intraday value zones and institutional benchmarks.
Price Action Filters
Fibonacci retracements are integrated to identify key reversal and continuation levels.
Signals are produced only when multiple conditions agree, reducing noise and improving reliability in fast-moving crypto markets.
Features
Tailored for cryptocurrency trading across major pairs (BTC, ETH, and altcoins).
Works effectively on swing and trend-based timeframes (1H–1D).
Combines trend, momentum, volatility, and price action into a single framework.
Generates clear Buy/Sell markers and integrates with TradingView alerts.
How to Use
Apply to a clean chart for the clearest visualization.
Use Swing Z as a swing trading tool, aligning entries with both trend structure and momentum confirmation.
Combine with your own stop-loss, take-profit, and position sizing rules.
Avoid application on non-standard chart types such as Renko, Heikin Ashi, or Point & Figure, which may distort results.
Disclaimer
Swing Z is designed as a decision-support tool, not financial advice.
All backtesting should use realistic risk, commission, and slippage assumptions.
Past results do not guarantee future performance.
Signals do not repaint but may adjust as new data develops in real-time.
Why Swing Z is original & useful:
Swing Z unifies EMA trend structure, RSI, MACD, TTM Squeeze, VWAP, Fibonacci retracements, and volume analysis into a single algorithmic framework. This multi-confirmation approach improves accuracy by requiring consensus across trend, momentum, volatility, and price action — a design made specifically for the challenges and volatility of cryptocurrency markets.
Swing Z – Crypto Trading Algorithm | Zillennial Technologies IncSwing Z by Zillennial Technologies Inc. is an advanced algorithmic framework built specifically for cryptocurrency markets. It integrates multiple layers of technical analysis into a single decision-support tool, generating buy and sell signals only when several independent confirmations align.
Core Concept
Swing Z fuses trend structure, momentum oscillators, volatility signals, and price action tools to capture high-probability trading opportunities in volatile crypto environments.
Trend Structure (EMA 9, 21, 50, 200)
Short-term EMAs (9 & 21) detect immediate momentum shifts.
Longer-term EMAs (50 & 200) define the broader trend and dynamic support/resistance.
Momentum & Confirmation Layer
RSI measures relative strength and market conditions.
MACD crossovers confirm momentum shifts and trend continuations.
Volatility & Market Pressure
TTM Squeeze highlights compression zones likely to precede breakouts.
Volume analysis confirms conviction behind directional moves.
VWAP (Volume Weighted Average Price) establishes intraday value zones and institutional benchmarks.
Price Action Filters
Fibonacci retracements are integrated to identify key reversal and continuation levels.
Signals are produced only when multiple conditions agree, reducing noise and improving reliability in fast-moving crypto markets.
Features
Tailored for cryptocurrency trading across major pairs (BTC, ETH, and altcoins).
Works effectively on swing and trend-based timeframes (1H–1D).
Combines trend, momentum, volatility, and price action into a single framework.
Generates clear Buy/Sell markers and integrates with TradingView alerts.
How to Use
Apply to a clean chart for the clearest visualization.
Use Swing Z as a swing trading tool, aligning entries with both trend structure and momentum confirmation.
Combine with your own stop-loss, take-profit, and position sizing rules.
Avoid application on non-standard chart types such as Renko, Heikin Ashi, or Point & Figure, which may distort results.
Disclaimer
Swing Z is designed as a decision-support tool, not financial advice.
All backtesting should use realistic risk, commission, and slippage assumptions.
Past results do not guarantee future performance.
Signals do not repaint but may adjust as new data develops in real-time.
Why Swing Z is original & useful:
Swing Z unifies EMA trend structure, RSI, MACD, TTM Squeeze, VWAP, Fibonacci retracements, and volume analysis into a single algorithmic framework. This multi-confirmation approach improves accuracy by requiring consensus across trend, momentum, volatility, and price action — a design made specifically for the challenges and volatility of cryptocurrency markets.
Radial Basis Kernel RSI for LoopRadial Basis Kernel RSI for Loop
What it is
An RSI-style oscillator that uses a radial basis function (RBF) kernel to compute a similarity-weighted average of gains and losses across many lookback lengths and kernel widths (γ). By averaging dozens of RSI estimates—each built with different parameters—it aims to deliver a smoother, more robust momentum signal that adapts to changing market conditions.
How it works
The script measures up/down price changes from your chosen Source (default: close).
For each combination of RSI length and Gamma (γ) in your ranges, it builds an RSI where recent bars that look most similar (by price behavior) get more weight via an RBF kernel.
It averages all those RSIs into a single value, then smooths it with your selected Moving Average type (SMA, EMA, WMA, HMA, DEMA) and a light regression-based filter for stability.
Inputs you can tune
Min/Max RSI Kernel Length & Step: Range of RSI lookbacks to include in the ensemble (e.g., 20→40 by 1) or (e.g., 30→50 by 1).
Min/Max Gamma & Step: Controls the RBF “width.” Lower γ = broader similarity (smoother); higher γ = more selective (snappier).
Source: Price series to analyze.
Overbought / Oversold levels: Defaults 70 / 30, with a midline at 50. Shaded regions help visualize extremes.
MA Type & Period (Confluence): Final smoothing on the averaged RSI line (e.g., DEMA(44) by default).
Red “OB” labels when the line crosses down from extreme highs (~80) → potential overbought fade/exit areas.
Green “OS” labels when the line crosses up from extreme lows (~20) → potential oversold bounce/entry areas.
How to use it
Treat it like RSI, but expect fewer whipsaws thanks to the ensemble and kernel weighting.
Common approaches:
Look for crosses back inside the bands (e.g., down from >70 or up from <30).
Use the 50 midline for directional bias (above = bullish momentum tilt; below = bearish).
Combine with trend filters (e.g., your chart MA) for higher-probability signals.
Performance note: This is really heavy and depending on how much time your subscription allows you could experience this timing out. Increasing the step size is the easiest way to reduce the load time.
Works on any symbol or timeframe. Like any oscillator, best used alongside price action and risk management rather than in isolation.
Pump/Dump Detector [Modular]//@version=5
indicator("Pump/Dump Detector ", overlay=true)
// ————— Inputs —————
risk_pct = input.float(1.0, "Risk %", minval=0.1)
capital = input.float(100000, "Capital")
stop_multiplier = input.float(1.5, "Stop Multiplier")
target_multiplier = input.float(2.0, "Target Multiplier")
volume_mult = input.float(2.0, "Volume Spike Multiplier")
rsi_low_thresh = input.int(15, "RSI Oversold Threshold")
rsi_high_thresh = input.int(85, "RSI Overbought Threshold")
rsi_len = input.int(2, "RSI Length")
bb_len = input.int(20, "BB Length")
bb_mult = input.float(2.0, "BB Multiplier")
atr_len = input.int(14, "ATR Length")
show_signals = input.bool(true, "Show Entry Signals")
use_orderflow = input.bool(true, "Use Order Flow Proxy")
use_ml_flag = input.bool(false, "Use ML Risk Flag")
use_session_filter = input.bool(true, "Use Volatility Sessions")
// ————— Symbol Filter (Optional) —————
symbol_nq = input.bool(true, "Enable NQ")
symbol_es = input.bool(true, "Enable ES")
symbol_gold = input.bool(true, "Enable Gold")
is_nq = str.contains(syminfo.ticker, "NQ")
is_es = str.contains(syminfo.ticker, "ES")
is_gold = str.contains(syminfo.ticker, "GC")
symbol_filter = (symbol_nq and is_nq) or (symbol_es and is_es) or (symbol_gold and is_gold)
// ————— Calculations —————
rsi = ta.rsi(close, rsi_len)
atr = ta.atr(atr_len)
basis = ta.sma(close, bb_len)
dev = bb_mult * ta.stdev(close, bb_len)
bb_upper = basis + dev
bb_lower = basis - dev
rolling_vol = ta.sma(volume, 20)
vol_spike = volume > volume_mult * rolling_vol
// ————— Session Filter (EST) —————
est_offset = -5
est_hour = (hour + est_offset + 24) % 24
session_filter = (est_hour >= 18 or est_hour < 6) or (est_hour >= 14 and est_hour < 17)
session_ok = not use_session_filter or session_filter
// ————— Order Flow Proxy —————
mfi = ta.mfi(close, 14)
buy_imbalance = ta.crossover(mfi, 50)
sell_imbalance = ta.crossunder(mfi, 50)
reversal_candle = close > open and close > ta.highest(close , 3)
// ————— ML Risk Flag (Placeholder) —————
ml_risk_flag = use_ml_flag and (ta.sma(close, 5) > ta.sma(close, 20))
// ————— Entry Conditions —————
long_cond = symbol_filter and session_ok and vol_spike and rsi < rsi_low_thresh and close < bb_lower and (not use_orderflow or (buy_imbalance and reversal_candle)) and (not use_ml_flag or ml_risk_flag)
short_cond = symbol_filter and session_ok and vol_spike and rsi > rsi_high_thresh and (not use_orderflow or sell_imbalance) and (not use_ml_flag or ml_risk_flag)
// ————— Position Sizing —————
risk_amt = capital * (risk_pct / 100)
position_size = risk_amt / atr
// ————— Plot Signals —————
plotshape(show_signals and long_cond, title="Long Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(show_signals and short_cond, title="Short Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
// ————— Alerts —————
alertcondition(long_cond, title="Long Entry Alert", message="Pump fade detected: Long setup triggered")
alertcondition(short_cond, title="Short Entry Alert", message="Dump detected: Short setup triggered")
KAMA Trend Flip with Snap & Follow - SightLing Labs🔭 OVERVIEW
KAMA Snap Follow is a customized adaptation of the Kaufman Adaptive Moving Average (KAMA) that overlays a trend-tracking line on the chart. It computes an adaptive smoothing constant from the efficiency ratio, then incorporates conditional enhancements: a "snap" mechanism to boost responsiveness on significant counter-trend bars surpassing an ATR-based threshold, and a temporary "follow" mode after trend flips to intensify adaptation for a user-defined number of bars. This allows the line to hug price more closely during early reversal phases before returning to standard smoothing for noise filtration. The line colors green for upward trends (rising KAMA), red for downward (falling KAMA), and gray for neutral, with optional alerts on trend changes. If the structure invalidates (e.g., via excessive lag or unconfirmed flips), no automatic cleanup occurs—users manage via settings tweaks and backtesting.
🔭 CONCEPTS
* Adaptive smoothing core: Builds on KAMA's efficiency ratio to dynamically adjust between fast and slow constants, gliding over minor volatility while aiming to react to directional shifts.
* Snap trigger: Detects potential reversals via large bar changes opposing the prior trend, exceeding a multiplier of ATR; this temporarily amplifies the smoothing constant (capped at 1.0) to pull KAMA toward price.
* Follow mode activation: Post-flip, engages a boosted adaptation phase for a fixed bar count, forcing tighter shadowing in the new direction to reduce lag on true turns, then reverts to absorber mode.
* Trend detection: Simple comparison of current vs. prior KAMA values defines up/down/neutral, with no embedded signals—purely for visual trend context.
* Risk-aware design: No guarantees; focuses on lag reduction in simulations (e.g., 38-54% trough lag cuts on synthetic volatile series), but real-market performance varies—backtest thoroughly.
🔭 FEATURES
* Custom KAMA calculation with manual efficiency ratio and smoothing powers for baseline adaptation.
* ATR-integrated snap for reversal sensitivity, with adjustable multiplier and boost.
* Post-flip follow mode with configurable period and boost to enhance new-trend hugging.
* Trend coloring and flip alerts: Green/red/gray line with conditions for up/down/neutral; alerts on changes.
* User controls:
Source (e.g., close).
Efficiency Ratio Length (pivot-like sensitivity).
Fast/Slow Powers (adaptation speed).
ATR Length (volatility measure).
Snap Multiplier/Boost (reversal threshold/amplification).
Follow Period/Boost (post-flip duration/intensity).
* Efficient execution: Lightweight, no heavy buffers—suitable for intraday charts via backtested tweaks.
🔭 HOW TO USE
* Tune sensitivity: Shorten Efficiency Ratio Length on lower timeframes for quicker reactions; lengthen on higher for smoother trends. Test ATR Length against asset volatility.
* Monitor flips: Use green/red shifts as trend context—combine with your strategy (e.g., crossovers, support/resistance) for potential entries; alerts notify changes.
* Leverage modes: Snap helps catch sharp turns; follow mode tightens tracking post-reversal—observe on historical data to gauge lag reduction (e.g., 30-57% miss cuts on 0.20 moves in tests).
* Apply MTF: Spot broader trends on 5m; refine on 30s/1m near flips. Backtest configurations to avoid over-optimization.
* Integrate confluence: Pair with volume, RSI, or your filters; never rely solely—markets evolve, so validate via simulations and live observation.
🔭 CONCLUSION
KAMA Snap Follow evolves standard KAMA by adding snap and follow mechanics to combat reversal lag while filtering bumps, offering a visual tool for trend analysis in volatile intraday setups. Developed to address traditional adaptive averages' delays without introducing excessive whipsaw (e.g., zero added in noisy flats per tests), it provides adjustable parameters for customization. No performance promises—results hinge on backtesting and market fit; use as a framework for scenario evaluation, not automated trading.
Example Configurations (derived from synthetic tests on SOFI-like intraday volatility; backtest and adjust):
- For 30s charts (high noise, rapid shifts): Efficiency Ratio Length=20, Fast Power=1, Slow Power=15, ATR Length=10, Snap Multiplier=1.2, Snap Boost=2.0, Follow Period=5, Follow Boost=2.5—yields ~40% lag reduction on turns, filtering 85% of <0.01 fluctuations.
- For 1m charts (moderate volatility): Efficiency Ratio Length=30, Fast Power=2, Slow Power=20, ATR Length=14, Snap Multiplier=1.5, Snap Boost=2.5, Follow Period=8, Follow Boost=3.0—achieves ~30% lower reversal misses (e.g., 0.08 vs. 0.12 on 0.20 swings), stable in 50-bar chops.
- For 5m charts (trendier flows): Efficiency Ratio Length=50, Fast Power=3, Slow Power=40, ATR Length=20, Snap Multiplier=1.8, Snap Boost=3.0, Follow Period=12, Follow Boost=3.5—boosts post-flip hug by 25%, ignoring 90% of ±0.05 noise across 100 bars.
Persistence# Persistence
## What it does
Measures **price change persistence**, defined as the percentage of bars within a lookback window that closed higher than the prior close. A high value means the instrument has been closing up frequently, which can indicate durable momentum. This mirrors Stockbee’s idea: *select stocks with high price change persistence*, and then combine **momentum plus persistence**.
## Can be used for scanning in PineScreener
## Calculation
* `isUp` is true when `close > close `.
* `countUp` counts true instances over the last `len` bars.
* `pctUp = 100 * countUp / len`, bounded between 0 and 100.
* A 50% level is a natural baseline. Above 50% suggests more up closes than down closes in the window.
## Inputs
* **Lookback bars (`len`)**: default 252 for roughly one trading year on a daily chart. On weekly charts use something like 52, on monthly charts use 12.
## How to use
1. **Screen for persistence**
Sort a watchlist by the plotted value, higher is better. Many momentum traders start looking above 58 to 65 percent, then layer a trend filter.
2. **Combine with momentum**
Examples, pick tickers with:
* `pctUp > 60`, and price above a rising EMA50 or EMA100.
* `pctUp rising` and weekly ROC positive.
3. **Switch timeframe to change the horizon**
* Daily chart with `len = 252` approximates one year.
* Weekly chart with `len = 52` approximates one year.
* Monthly chart with `len = 12` approximates one year.
## TC2000 equivalence
Stockbee’s TC2000 expression:
```
CountTrue(c > c1, 252)
```
## Interpretation guide
* **70 to 90**: very strong persistence; often trend leaders, check for extensions and risk controls.
* **60 to 70**: constructive persistence; good hunting ground for swing setups that also pass momentum filters.
* **50**: neutral baseline; around random up vs down frequency.
* **Below 50**: persistent weakness; consider only for mean reversion or short strategies.
## Practical tips
* **Event effects**: ex-dividend gaps can reduce persistence on high yield names. Earnings gaps can swing the value sharply.
* **Survivorship bias**: when backtesting on curated lists, persistence can look cleaner than in live scans.
* **Liquidity**: thin names may show noisy persistence due to erratic prints.
## Reference to Stockbee
* “One way to select stocks for swing trading is to find those with high price change persistence.”
* “Persistence can be calculated on a daily, monthly, or weekly timeframe.”
* TC2000 function: `CountTrue(c > c1, 252)`
* Example noted in the tweet: CVNA had very high one-year price persistence at the time of that post.
* Takeaway: **look for momentum plus persistence**, not persistence alone.
EMA–VWAP Strategy (Confirmed crosses, 1 trade/cross)Wait for 10 and 20 ema to cross
Buy between 10 and 20
wait for 20 and 50 to cross
buy at vwap
10/20/50 ema and vwap is plotted