Adaptive Kalman filter - Trend Strength Oscillator (Zeiierman)█ Overview
The Adaptive Kalman Filter - Trend Strength Oscillator by Zeiierman is a sophisticated trend-following indicator that uses advanced mathematical techniques, including vector and matrix operations, to decompose price movements into trend and oscillatory components. Unlike standard indicators, this model assumes that price is driven by two latent (unobservable) factors: a long-term trend and localized oscillations around that trend. Through a dynamic "predict and update" process, the Kalman Filter leverages vectors to adaptively separate these components, extracting a clearer view of market direction and strength.
█ How It Works
This indicator operates on a trend + local change Kalman Filter model. It assumes that price movements consist of two underlying components: a core trend and an oscillatory term, representing smaller price fluctuations around that trend. The Kalman Filter adaptively separates these components by observing the price series over time and performing real-time updates as new data arrives.
Predict and Update Procedure: The Kalman Filter uses an adaptive predict-update cycle to estimate both components. This cycle allows the filter to adjust dynamically as the market evolves, providing a smooth yet responsive signal. The trend component extracted from this process is plotted directly, giving a clear view of the prevailing direction. The oscillatory component indicates the tendency or strength of the trend, reflected in the green/red coloration of the oscillator line.
Trend Strength Calculation: Trend strength is calculated by comparing the current oscillatory value against a configurable number of past values.
█ Three Kalman filter Models
This indicator offers three distinct Kalman filter models, each designed to handle different market conditions:
Standard Model: This is a conventional Kalman Filter, balancing responsiveness and smoothness. It works well across general market conditions.
Volume-Adjusted Model: In this model, the filter’s measurement noise automatically adjusts based on trading volume. Higher volumes indicate more informative price movements, which the filter treats with higher confidence. Conversely, low-volume movements are treated as less informative, adding robustness during low-activity periods.
Parkinson-Adjusted Model: This model adjusts measurement noise based on price volatility. It uses the price range (high-low) to determine the filter’s sensitivity, making it ideal for handling markets with frequent gaps or spikes. The model responds with higher confidence in low-volatility periods and adapts to high-volatility scenarios by treating them with more caution.
█ How to Use
Trend Detection: The oscillator oscillates around zero, with positive values indicating a bullish trend and negative values indicating a bearish trend. The further the oscillator moves from zero, the stronger the trend. The Kalman filter trend line on the chart can be used in conjunction with the oscillator to determine the market's trend direction.
Trend Reversals: The blue areas in the oscillator suggest potential trend reversals, helping traders identify emerging market shifts. These areas can also indicate a potential pullback within the prevailing trend.
Overbought/Oversold: The thresholds, such as 70 and -70, help identify extreme conditions. When the oscillator reaches these levels, it suggests that the trend may be overextended, possibly signaling an upcoming reversal.
█ Settings
Process Noise 1: Controls the primary level of uncertainty in the Kalman filter model. Higher values make the filter more responsive to recent price changes, but may also increase susceptibility to random noise.
Process Noise 2: This secondary noise setting works with Process Noise 1 to adjust the model's adaptability. Together, these settings manage the uncertainty in the filter's internal model, allowing for finely-tuned adjustments to smoothness versus responsiveness.
Measurement Noise: Sets the uncertainty in the observed price data. Increasing this value makes the filter rely more on historical data, resulting in smoother but less reactive filtering. Lower values make the filter more responsive but potentially more prone to noise.
O sc Smoothness: Controls the level of smoothing applied to the trend strength oscillator. Higher values result in a smoother oscillator, which may cause slight delays in response. Lower values make the oscillator more reactive to trend changes, useful for capturing quick reversals or volatility within the trend.
Kalman Filter Model: Choose between Standard, Volume-Adjusted, and Parkinson-Adjusted models. Each model adapts the Kalman filter for specific conditions, whether balancing general market data, adjusting based on volume, or refining based on volatility.
Trend Lookback: Defines how far back to look when calculating the trend strength, which impacts the indicator's sensitivity to changes in trend strength. Shorter values make the oscillator more reactive to recent trends, while longer values provide a smoother reading.
Strength Smoothness: Adjusts the level of smoothing applied to the trend strength oscillator. Higher values create a more gradual response, while lower values make the oscillator more sensitive to recent changes.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Indicadores e estratégias
TrigWave Suite [InvestorUnknown]The TrigWave Suite combines Sine-weighted, Cosine-weighted, and Hyperbolic Tangent moving averages (HTMA) with a Directional Movement System (DMS) and a Relative Strength System (RSS).
Hyperbolic Tangent Moving Average (HTMA)
The HTMA smooths the price by applying a hyperbolic tangent transformation to the difference between the price and a simple moving average. It also adjusts this value by multiplying it by a standard deviation to create a more stable signal.
// Function to calculate Hyperbolic Tangent
tanh(x) =>
e_x = math.exp(x)
e_neg_x = math.exp(-x)
(e_x - e_neg_x) / (e_x + e_neg_x)
// Function to calculate Hyperbolic Tangent Moving Average
htma(src, len, mul) =>
tanh_src = tanh((src - ta.sma(src, len)) * mul) * ta.stdev(src, len) + ta.sma(src, len)
htma = ta.sma(tanh_src, len)
Sine-Weighted Moving Average (SWMA)
The SWMA applies sine-based weights to historical prices. This gives more weight to the central data points, making it responsive yet less prone to noise.
// Function to calculate the Sine-Weighted Moving Average
f_Sine_Weighted_MA(series float src, simple int length) =>
var float sine_weights = array.new_float(0)
array.clear(sine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.sin((math.pi * (i + 1)) / length)
array.push(sine_weights, weight)
// Normalize the weights
sum_weights = array.sum(sine_weights)
for i = 0 to length - 1
norm_weight = array.get(sine_weights, i) / sum_weights
array.set(sine_weights, i, norm_weight)
// Calculate Sine-Weighted Moving Average
swma = 0.0
if bar_index >= length
for i = 0 to length - 1
swma := swma + array.get(sine_weights, i) * src
swma
Cosine-Weighted Moving Average (CWMA)
The CWMA uses cosine-based weights for data points, which produces a more stable trend-following behavior, especially in low-volatility markets.
f_Cosine_Weighted_MA(series float src, simple int length) =>
var float cosine_weights = array.new_float(0)
array.clear(cosine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.cos((math.pi * (i + 1)) / length) + 1 // Shift by adding 1
array.push(cosine_weights, weight)
// Normalize the weights
sum_weights = array.sum(cosine_weights)
for i = 0 to length - 1
norm_weight = array.get(cosine_weights, i) / sum_weights
array.set(cosine_weights, i, norm_weight)
// Calculate Cosine-Weighted Moving Average
cwma = 0.0
if bar_index >= length
for i = 0 to length - 1
cwma := cwma + array.get(cosine_weights, i) * src
cwma
Directional Movement System (DMS)
DMS is used to identify trend direction and strength based on directional movement. It uses ADX to gauge trend strength and combines +DI and -DI for directional bias.
// Function to calculate Directional Movement System
f_DMS(simple int dmi_len, simple int adx_len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, dmi_len)
plus = fixnan(100 * ta.rma(plusDM, dmi_len) / trur)
minus = fixnan(100 * ta.rma(minusDM, dmi_len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_len)
dms_up = plus > minus and adx > minus
dms_down = plus < minus and adx > plus
dms_neutral = not (dms_up or dms_down)
signal = dms_up ? 1 : dms_down ? -1 : 0
Relative Strength System (RSS)
RSS employs RSI and an adjustable moving average type (SMA, EMA, or HMA) to evaluate whether the market is in a bullish or bearish state.
// Function to calculate Relative Strength System
f_RSS(rsi_src, rsi_len, ma_type, ma_len) =>
rsi = ta.rsi(rsi_src, rsi_len)
ma = switch ma_type
"SMA" => ta.sma(rsi, ma_len)
"EMA" => ta.ema(rsi, ma_len)
"HMA" => ta.hma(rsi, ma_len)
signal = (rsi > ma and rsi > 50) ? 1 : (rsi < ma and rsi < 50) ? -1 : 0
ATR Adjustments
To minimize false signals, the HTMA, SWMA, and CWMA signals are adjusted with an Average True Range (ATR) filter:
// Calculate ATR adjusted components for HTMA, CWMA and SWMA
float atr = ta.atr(atr_len)
float htma_up = htma + (atr * atr_mult)
float htma_dn = htma - (atr * atr_mult)
float swma_up = swma + (atr * atr_mult)
float swma_dn = swma - (atr * atr_mult)
float cwma_up = cwma + (atr * atr_mult)
float cwma_dn = cwma - (atr * atr_mult)
This adjustment allows for better adaptation to varying market volatility, making the signal more reliable.
Signals and Trend Calculation
The indicator generates a Trend Signal by aggregating the output from each component. Each component provides a directional signal that is combined to form a unified trend reading. The trend value is then converted into a long (1), short (-1), or neutral (0) state.
Backtesting Mode and Performance Metrics
The Backtesting Mode includes a performance metrics table that compares the Buy and Hold strategy with the TrigWave Suite strategy. Key statistics like Sharpe Ratio, Sortino Ratio, and Omega Ratio are displayed to help users assess performance. Note that due to labels and plotchar use, automatic scaling may not function ideally in backtest mode.
Alerts and Visualization
Trend Direction Alerts: Set up alerts for long and short signals
Color Bars and Gradient Option: Bars are colored based on the trend direction, with an optional gradient for smoother visual feedback.
Important Notes
Customization: Default settings are experimental and not intended for trading/investing purposes. Users are encouraged to adjust and calibrate the settings to optimize results according to their trading style.
Backtest Results Disclaimer: Please note that backtest results are not indicative of future performance, and no strategy guarantees success.
MACD+RSI+BBDESCRIPTION
The MACD + RSI + Bollinger Bands Indicator is a comprehensive technical analysis tool designed for traders and investors to identify potential market trends and reversals. This script combines three indicators: the Moving Average Convergence Divergence (MACD), the Relative Strength Index (RSI), and Bollinger Bands. Each of these indicators provides unique insights into market behavior.
FEATURES
MACD (Moving Average Convergence Divergence)
The MACD is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price.
The script calculates the MACD line, the signal line, and the histogram, which visually represents the difference between the MACD line and the signal line.
RSI (Relative Strength Index)
The RSI is a momentum oscillator that measures the speed and change of price movements. It ranges from 0 to 100 and is typically used to identify overbought or oversold conditions.
The script allows users to set custom upper and lower thresholds for the RSI, with default values of 70 and 30, respectively.
Bollinger Bands
Bollinger Bands consist of a middle band (EMA) and two outer bands (standard deviations away from the EMA). They help traders identify volatility and potential price reversals.
The script allows users to customize the length of the Bollinger Bands and the multiplier for the standard deviation.
Color-Coding Logic
The histogram color changes based on the following conditions:
Black: If the RSI is above the upper threshold and the closing price is above the upper Bollinger Band, or if the RSI is below the lower threshold and the closing price is below the lower Bollinger Band.
Green (#4caf50): If the RSI is above the upper threshold but the closing price is not above the upper Bollinger Band.
Light Green (#a5d6a7): If the histogram is positive and the RSI is not above the upper threshold.
Red (#f23645): If the RSI is below the lower threshold but the closing price is not below the lower Bollinger Band.
Light Red (#faa1a4): If the histogram is negative and the RSI is not below the lower threshold.
Inputs
Bollinger Bands Settings
Length: The number of periods for the moving average.
Basis MA Type: The type of moving average (SMA, EMA, SMMA, WMA, VWMA).
Source: The price source for the Bollinger Bands calculation.
StdDev: The multiplier for the standard deviation.
RSI Settings
RSI Length: The number of periods for the RSI calculation.
RSI Upper: The upper threshold for the RSI.
RSI Lower: The lower threshold for the RSI.
Source: The price source for the RSI calculation.
MACD Settings
Fast Length: The length for the fast moving average.
Slow Length: The length for the slow moving average.
Signal Smoothing: The length for the signal line smoothing.
Oscillator MA Type: The type of moving average for the MACD calculation.
Signal Line MA Type: The type of moving average for the signal line.
Usage
This indicator is suitable for various trading strategies, including day trading, swing trading, and long-term investing.
Traders can use the MACD histogram to identify potential buy and sell signals, while the RSI can help confirm overbought or oversold conditions.
The Bollinger Bands provide context for price volatility and potential breakout or reversal points.
Example:
From the example, it can clearly see that the Selling Climax and Buying Climax, marked as orange circle when a black histogram occurs.
Conclusion
The MACD + RSI + Bollinger Bands Indicator is a versatile tool that combines multiple technical analysis methods to provide traders with a comprehensive view of market conditions. By utilizing this script, traders can enhance their analysis and improve their decision-making process.
NASI +The NASI + indicator is an advanced adaptation of the classic McClellan Oscillator, a tool widely used to gauge market breadth. It calculates the McClellan Oscillator by measuring the difference between the 19-day and 39-day EMAs of net advancing issues, which are optionally adjusted to account for the relative strength of advancing vs. declining stocks.
To enhance this analysis, NASI + applies the Relative Strength Index (RSI) to the cumulative McClellan Oscillator values, generating a unique momentum-based view of market breadth. Additionally, two extra EMAs—a 10-day and a 4-day EMA—are applied to the RSI, providing further refinement to signals for overbought and oversold conditions.
With NASI +, users benefit from:
-A deeper analysis of market momentum through cumulative breadth data.
-Enhanced sensitivity to trend shifts with the applied RSI and dual EMAs.
-Clear visual cues for overbought and oversold conditions, aiding in intuitive signal identification.
Direction finderA trend indicator is a tool used in technical analysis to help identify the direction and strength of a price movement in financial markets. It serves as a guide for traders and investors to understand whether an asset's price is likely to continue moving in a particular direction or if it may reverse. Trend indicators are typically based on historical price data, volume, and sometimes volatility, and they often use mathematical calculations or graphical representations to simplify trend analysis.
Common types of trend indicators include:
Moving Averages (MAs): Averages the asset price over a set period, creating a smooth line that helps identify the general direction of the trend. Popular moving averages include the Simple Moving Average (SMA) and Exponential Moving Average (EMA).
Moving Average Convergence Divergence (MACD): Measures the relationship between two moving averages of an asset’s price, often used to signal trend reversals or continuations based on line crossovers and the direction of the MACD line.
Average Directional Index (ADX): Indicates the strength of a trend rather than its direction. A high ADX value suggests a strong trend, while a low value suggests a weak trend or a range-bound market.
Bollinger Bands: This indicator includes a moving average with bands set at standard deviations above and below. It helps identify price volatility and potential trend reversals when prices move toward the outer bands.
Trend indicators can help identify entry and exit points by suggesting whether a trend is continuing or if the price may be about to reverse. However, they are often used in conjunction with other types of indicators, such as momentum or volume-based tools, to provide a fuller picture of market behavior and confirm trading signals.
Trend Trader-RemasteredThe script was originally coded in 2018 with Pine Script version 3, and it was in invite only status. It has been updated and optimised for Pine Script v5 and made completely open source.
Overview
The Trend Trader-Remastered is a refined and highly sophisticated implementation of the Parabolic SAR designed to create strategic buy and sell entry signals, alongside precision take profit and re-entry signals based on marked Bill Williams (BW) fractals. Built with a deep emphasis on clarity and accuracy, this indicator ensures that only relevant and meaningful signals are generated, eliminating any unnecessary entries or exits.
Key Features
1) Parabolic SAR-Based Entry Signals:
This indicator leverages an advanced implementation of the Parabolic SAR to create clear buy and sell position entry signals.
The Parabolic SAR detects potential trend shifts, helping traders make timely entries in trending markets.
These entries are strategically aligned to maximise trend-following opportunities and minimise whipsaw trades, providing an effective approach for trend traders.
2) Take Profit and Re-Entry Signals with BW Fractals:
The indicator goes beyond simple entry and exit signals by integrating BW Fractal-based take profit and re-entry signals.
Relevant Signal Generation: The indicator maintains strict criteria for signal relevance, ensuring that a re-entry signal is only generated if there has been a preceding take profit signal in the respective position. This prevents any misleading or premature re-entry signals.
Progressive Take Profit Signals: The script generates multiple take profit signals sequentially in alignment with prior take profit levels. For instance, in a buy position initiated at a price of 100, the first take profit might occur at 110. Any subsequent take profit signals will then occur at prices greater than 110, ensuring they are "in favour" of the original position's trajectory and previous take profits.
3) Consistent Trend-Following Structure:
This design allows the Trend Trader-Remastered to continue signaling take profit opportunities as the trend advances. The indicator only generates take profit signals in alignment with previous ones, supporting a systematic and profit-maximising strategy.
This structure helps traders maintain positions effectively, securing incremental profits as the trend progresses.
4) Customisability and Usability:
Adjustable Parameters: Users can configure key settings, including sensitivity to the Parabolic SAR and fractal identification. This allows flexibility to fine-tune the indicator according to different market conditions or trading styles.
User-Friendly Alerts: The indicator provides clear visual signals on the chart, along with optional alerts to notify traders of new buy, sell, take profit, or re-entry opportunities in real-time.
Rikki's DikFat Bull/Bear OscillatorRikki's DikFat Bull/Bear Oscillator - Trend Identification & Candle Colorization
Rikki's DikFat Bull/Bear Oscillator is a powerful visual tool designed to help traders easily identify bullish and bearish trends on the chart. By analyzing market momentum using specific elements of the Commodity Channel Index (CCI) , this indicator highlights key trend reversals and continuations with color-coded candles, allowing you to quickly spot areas of opportunity.
How It Works
At the heart of this indicator is the Commodity Channel Index (CCI) , a popular momentum-based oscillator. The CCI measures the deviation of price from its average over a specified period (default is 30 bars). This helps identify whether the market is overbought, oversold, or trending.
Here's how the indicator interprets the CCI:
Bullish Trend (Green Candles) : When the market is showing signs of continued upward momentum, the candles turn green. This happens when the current CCI is less than 200 and moves from a value greater than 100 with velocity, signaling that the upward trend is still strong, and the market is likely to continue rising. Green candles indicate bullish price action , suggesting it might be a good time to look for buying opportunities or hold your current long position.
Bearish Trend (Red Candles) : Conversely, when the CCI shows signs of downward momentum (both the current and previous CCI readings are negative), the candles turn red. This signals that the market is likely in a bearish trend , with downward price action expected to continue. Red candles are a visual cue to consider selling opportunities or to stay out of the market if you're risk-averse.
How to Use It
Bullish Market : When you see green candles, the market is in a bullish phase. This suggests that prices are moving upward, and you may want to focus on buying signals . Green candles are your visual confirmation of a strong upward trend.
Bearish Market : When red candles appear, the market is in a bearish phase. This indicates that prices are moving downward, and you may want to consider selling or staying out of long positions. Red candles signal that downward pressure is likely to continue.
Why It Works
This indicator uses momentum to identify shifts in trend. By tracking the movement of the CCI , the oscillator detects whether the market is trending strongly or simply moving in a sideways range. The color changes in the candles help you quickly visualize where the market momentum is headed, giving you an edge in determining potential buy or sell opportunities.
Clear Visual Signals : The green and red candles make it easy to follow market trends, even for beginners.
Identifying Trend Continuations : The oscillator helps spot ongoing trends, whether bullish or bearish, so you can align your trades with the prevailing market direction.
Quick Decision-Making : By using color-coded candles, you can instantly know whether to consider entering a long (buy) or short (sell) position without needing to dive into complex indicators.
NOTES This indicator draws and colors it's own candles bodies, wicks and borders. In order to have the completed visualization of red and green trends, you may need to adjust your TradingView chart settings to turn off or otherwise modify chart candles.
Conclusion
With Rikki's DikFat Bull/Bear Oscillator , you have an intuitive and easy-to-read tool that helps identify bullish and bearish trends based on proven momentum indicators. Whether you’re a novice or an experienced trader, this oscillator allows you to stay in tune with the market’s direction and make more informed, confident trading decisions.
Make sure to use this indicator in conjunction with your own trading strategy and risk management plan to maximize your trading potential and limit your risks.
Kalman Based VWAP [EdgeTerminal]Kalman VWAP is a different take on volume-weighted average price (VWAP) indicator where we enhance the results with Kalman filtering and dynamic wave visualization for a more smooth and improved trend identification and volatility analysis.
A little bit about Kalman Filter:
Kalman filtering (also known as linear quadratic estimation) is an algorithm that uses a series of measurements observed over time, including statistical noise and other inaccuracies, to produce estimates of unknown variables that tend to be more accurate than those based on a single measurement, by estimating a joint probability distribution over the variables for each time-step. The filter is constructed as a mean squared error minimiser, but an alternative derivation of the filter is also provided showing how the filter relates to maximum likelihood statistics
This indicator combines:
Volume-Weighted Average Price (VWAP) for institutional price levels
Kalman filtering for noise reduction and trend smoothing
Dynamic wave visualization for volatility zones
This creates a robust indicator that helps traders identify trends, support/resistance zones, and potential reversal points with high precision.
What makes this even more special is the fact that we use open price as a data source instead of usual close price. This allows you to tune the indicator more accurately when back testing it and generally get results that are closer to real time market data.
The math:
In case if you're interested in the math of this indicator, the indicator employs a state-space Kalman filter model:
State Equation: x_t = x_{t-1} + w_t
Measurement Equation: z_t = x_t + v_t
x_t is the filtered VWAP state
w_t is process noise ~ N(0, Q)
v_t is measurement noise ~ N(0, R)
z_t is the traditional VWAP measurement
The Kalman filter recursively updates through:
Prediction: x̂_t|t-1 = x̂_{t-1}
Update: x̂_t = x̂_t|t-1 + K_t(z_t - x̂_t|t-1)
Where K_t is the Kalman gain, optimally balancing between prediction and measurement.
Input Parameters
Measurement Noise: Controls signal smoothing (0.0001 to 1.0)
Process Noise: Adjusts trend responsiveness (0.0001 to 1.0)
Wave Size: Multiplier for volatility bands (0.1 to 5.0)
Trend Lookback: Period for trend determination (1 to 100)
Bull/Bear Colors: Customizable color schemes
Application:
I recommend using this along other indicators. This is best used for assets that don't have a close time, such as BTC but can be used with anything as long as the data is there.
With default settings, this works better for swing trades but you can adjust it for day trading as well, by adjusting the lookback and also process noise.
Stock Booster 3.0
//@version=5
const bool DEBUG = false
const int maxDistanceToLastBar = 5000
const int labelCooldown = 8
const int KDELimit = 300
indicator("Stock Booster", overlay = true, max_labels_count = 500)
rsiLengthInput = input.int(14, minval = 1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
highPivotLen = input.int(21, "High Pivot Length", minval = 1, group = "Pivots", display = display.none)
lowPivotLen = input.int(21, "Low Pivot Length", minval = 1, group = "Pivots", display = display.none)
realPivotLabels = DEBUG ? input.bool(false, " Real Pivot Labels", group = "Pivots") : false
kdePivotLabels = DEBUG ? input.bool(false, " KDE Pivot Labels", group = "Pivots") : false
activationThresholdStr = input.string("Medium", "Activation Threshold", options = , group = "KDE", tooltip = "Determines the amount of arrows shown. Higher options will result in more arrows being rendered.")
string KDEKernel = input.string("Gaussian", "Kernel", options= , group = "KDE", tooltip = "The kernel function for KDE calculation. Gaussian is a commonly used kernel and is based on normal distribution.")
float KDEBandwidth = input.float(2.71828, "Bandwidth", group = "KDE", tooltip = "This setting sets the smoothness of the KDE function output.")
int KDEStep = input.int(100, "Nº Bins", minval = 1, group = "KDE", tooltip = "The number of elements the KDE Probability array will have. Higher settings will result in greater precision.")
activationThreshold = DEBUG ? input.float(0.25, " Activation Threshold", group = "KDE") : 0.25
if not DEBUG
activationThreshold := (activationThresholdStr == "High" ? 0.4 : activationThresholdStr == "Medium" ? 0.25 : 0.15)
probMode = DEBUG ? input.string("Sum", ' Probability Mode', options = , group = "KDE") : "Sum"
minPadding = DEBUG ? input.bool(false, ' KDE Min Padding', group = "KDE") : false
tableEnabled = input.bool(true, "Dashboard", group = "Dashboard", display = display.none)
tableLocation = input.string("Top Right", "Position", options = , group = "Dashboard", display = display.none)
screenerColor = input.color(#1B1F2B, 'Background', group = 'Dashboard', display = display.none)
frameColor = input.color(color.rgb(255, 255, 255), 'Frame', group = 'Dashboard', display = display.none)
borderColor = input.color(color.rgb(255, 255, 255), 'Border', group = 'Dashboard', display = display.none)
textColorDB = input.color(color.white, 'Text', group = 'Dashboard', display = display.none)
fillBackgrounds = input.bool(true, "Fill Backgrounds", group = "Dashboard", display = display.none)
bearishColor = input.color(#f23646, "High Pivots", group = "Style", inline = "col", display = display.none)
neutralColor = input.color(color.gray, "Neutral", group = "Style", inline = "col", display = display.none)
bullishColor = input.color(#089981, "Low Pivots", group = "Style", inline = "col", display = display.none)
textColor = input.color(color.white, 'Text', group = 'Style', inline = "col", display = display.none)
RSILabelsEnabled = input.bool(true, "RSI Labels", group = "Style")
KDELabelsEnabled = input.bool(true, "KDE Labels", group = "Style")
rsi = ta.rsi(rsiSourceInput, rsiLengthInput)
getPosition (positionText) =>
if positionText == "Top Right"
position.top_right
else if positionText == "Top Center"
position.top_center
else if positionText == "Right Center"
position.middle_right
else if positionText == "Left Center"
position.middle_left
else if positionText == "Bottom Center"
position.bottom_center
else if positionText == "Middle Center"
position.middle_center
//#region KDE
gaussian (float distance, float bandwidth = 1.0) => 1.0 / math.sqrt(2.0 * math.pi) * math.pow(math.e, -0.5 * math.pow(distance / bandwidth, 2.0))
uniform (float distance, float bandwidth = 1.0) => (math.abs(distance) > bandwidth) ? 0.0 : 0.5
sigmoid (float distance, float bandwidth = 1.0) => 2.0 / math.pi * (1.0 / (math.pow(math.e, (distance / bandwidth)) + math.pow(math.e, -(distance / bandwidth))))
kde (array arr, string kernel, float bandwidth, int steps) =>
arrSize = arr.size()
arrRange = arr.range()
arrMin = arr.min() - (minPadding ? (arrRange / 2.0) : 0)
stepCount = arrRange / steps
densityRange = array.new(steps * 2)
for i = 0 to (steps * 2) - 1
densityRange.set(i, arrMin + i * stepCount)
xArr = array.new()
yArr = array.new()
for i = 0 to densityRange.size() - 1
float temp = 0
for j = 0 to arr.size() - 1
switch KDEKernel
"Gaussian" => temp += gaussian(densityRange.get(i) - arr.get(j), 1.0 / bandwidth)
"Uniform" => temp += uniform(densityRange.get(i) - arr.get(j), 1.0 / bandwidth)
"Sigmoid" => temp += sigmoid(densityRange.get(i) - arr.get(j), 1.0 / bandwidth)
xArr.push(densityRange.get(i))
yArr.push(1.0 / arrSize * temp)
//#endregion
//#region Pivots
prefixSum (array arr, int l, int r) =>
arr.get(r) - (l == 0 ? 0 : arr.get(l - 1))
float MidKDEHigh = na
float MidKDELow = na
var array KDEHighX = na
var array KDEHighY = na
var array KDEHighYSum = array.new()
var array KDELowX = na
var array KDELowY = na
var array KDELowYSum = array.new()
highPivot = ta.pivothigh(highPivotLen, highPivotLen)
lowPivot = ta.pivotlow(lowPivotLen, lowPivotLen)
var highPivotRSIs = array.new()
var lowPivotRSIs = array.new()
if not na(highPivot)
if highPivotRSIs.size() > KDELimit
highPivotRSIs.remove(0)
highPivotRSIs.push(rsi )
= kde(highPivotRSIs, KDEKernel, KDEBandwidth, KDEStep)
KDEHighX := KDEHighX1
KDEHighY := KDEHighY1
KDEHighYSum.clear()
temp = 0.0
for i = 0 to KDEHighY.size() - 1
temp += KDEHighY.get(i)
KDEHighYSum.push(temp)
MidKDEHigh := array.get(KDEHighX, array.indexof(KDEHighY, array.max(KDEHighY)))
if not na(lowPivot)
if lowPivotRSIs.size() > KDELimit
lowPivotRSIs.remove(0)
lowPivotRSIs.push(rsi )
= kde(lowPivotRSIs, KDEKernel, KDEBandwidth, KDEStep)
KDELowX := KDELowX1
KDELowY := KDELowY1
KDELowYSum.clear()
temp = 0.0
for i = 0 to KDELowY.size() - 1
temp += KDELowY.get(i)
KDELowYSum.push(temp)
MidKDELow := array.get(KDELowX, array.indexof(KDELowY, array.max(KDELowY)))
//#endregion
//#region KDE Optimization
f_lin_interpolate(float x0, float x1, float y0, float y1, float x) =>
y0 + (x - x0) * (y1 - y0) / (x1 - x0)
float lowProb = na
float maxLowProb = na
float highProb = na
float maxHighProb = na
if last_bar_index - maxDistanceToLastBar < bar_index
if highPivotRSIs.size() > 0
highXIndexL = array.binary_search_leftmost(KDEHighX, rsi)
highXIndexR = math.min(array.binary_search_rightmost(KDEHighX, rsi), KDEHighX.size() - 1)
nearestIndex = (math.abs(rsi - KDEHighX.get(highXIndexL)) < math.abs(rsi - KDEHighX.get(highXIndexR))) ? highXIndexL : highXIndexR
if probMode == "Nearest"
highProb := KDEHighY.get(nearestIndex)
maxHighProb := array.max(KDEHighY)
else if probMode == "Sum"
highProb := prefixSum(KDEHighYSum, 0, nearestIndex)
if lowPivotRSIs.size() > 0
lowXIndexL = array.binary_search_leftmost(KDELowX, rsi)
lowXIndexR = math.min(array.binary_search_rightmost(KDELowX, rsi), KDELowX.size() - 1)
nearestIndex = (math.abs(rsi - KDELowX.get(lowXIndexL)) < math.abs(rsi - KDELowX.get(lowXIndexR))) ? lowXIndexL : lowXIndexR
if probMode == "Nearest"
lowProb := KDELowY.get(nearestIndex)
maxLowProb := array.max(KDELowY)
else if probMode == "Sum"
lowProb := prefixSum(KDELowYSum, nearestIndex, KDELowYSum.size() - 1)
if DEBUG and barstate.islastconfirmedhistory
for i = 0 to KDELowX.size() - 1
curX = KDELowX.get(i)
curY = KDELowY.get(i)
log.info(str.tostring(curX) + " = " + str.tostring(curY))
log.info("High Y Sum " + str.tostring(KDEHighY.sum()))
diffToHighKDE = math.abs(rsi - MidKDEHigh)
diffToLowKDE = math.abs(rsi - MidKDELow)
//#endregion
//#region Draw Pivots
color curColor = na
if (not na(KDELowY)) and (not na(KDEHighY))
if probMode == "Nearest"
if math.abs(lowProb - maxLowProb) < activationThreshold / 50.0
curColor := bullishColor
if math.abs(highProb - maxHighProb) < activationThreshold / 50.0
curColor := bearishColor
else if probMode == "Sum"
if lowProb > KDELowY.sum() * (1.0 - activationThreshold)
curColor := bullishColor
else if highProb > KDEHighY.sum() * (1.0 - activationThreshold)
curColor := bearishColor
//barcolor(curColor)
atr = ta.atr(50)
plotarrow(curColor == bullishColor and barstate.isconfirmed ? 1 : na, "Bullish Arrows", color.new(bullishColor, 70), color.new(bullishColor, 70), minheight = 20, maxheight = 20)
plotarrow(curColor == bearishColor and barstate.isconfirmed ? -1 : na, "Bearish Arrows", color.new(bearishColor, 70), color.new(bearishColor, 70), minheight = 20, maxheight = 20)
plotarrow((na(curColor) and curColor == bullishColor and barstate.isconfirmed) ? 1 : na, "Possible Bullish Pivot", bullishColor, bullishColor, minheight = 20, maxheight = 20)
plotarrow((na(curColor) and curColor == bearishColor and barstate.isconfirmed) ? -1 : na, "Possible Bearish Pivot", bearishColor, bearishColor, minheight = 20, maxheight = 20)
alertcondition(na(curColor) and curColor == bullishColor and barstate.isconfirmed, "Possible Bullish Pivot")
alertcondition(na(curColor) and curColor == bearishColor and barstate.isconfirmed, "Possible Bearish Pivot")
if KDELabelsEnabled or RSILabelsEnabled
var lastBullishLabel = 0
if (na(curColor) and curColor == bullishColor and barstate.isconfirmed) and (bar_index - lastBullishLabel) > labelCooldown
lastBullishLabel := bar_index
txt = ""
if RSILabelsEnabled and KDELabelsEnabled
txt := "RSI | " + str.tostring(rsi, "#") + " | " + str.tostring(lowProb * 100, "#.##") + "%"
else if RSILabelsEnabled
txt := "RSI | " + str.tostring(rsi, "#")
else
txt := str.tostring(rsi, "#") + "%"
label.new(bar_index, low, txt, yloc = yloc.belowbar, color = na, style = label.style_label_up, textcolor = textColor, force_overlay = true)
var lastBearishLabel = 0
if (na(curColor) and curColor == bearishColor and barstate.isconfirmed) and (bar_index - lastBearishLabel) > labelCooldown
lastBearishLabel := bar_index
txt = ""
if RSILabelsEnabled and KDELabelsEnabled
txt := "RSI | " + str.tostring(rsi, "#") + " | " + str.tostring(highProb * 100, "#.##") + "%"
else if RSILabelsEnabled
txt := "RSI | " + str.tostring(rsi, "#")
else
txt := str.tostring(rsi, "#") + "%"
label.new(bar_index, low, txt, yloc = yloc.abovebar, color = na, style = label.style_label_down, textcolor = textColor, force_overlay = true)
if kdePivotLabels
txt = str.tostring(rsi, "#.##") + " HP -> " + str.tostring(highProb, "#.##") + " LP -> " + str.tostring(lowProb, "#.##") + " MHP -> " + str.tostring(maxHighProb, "#.##") + " MLP -> " + str.tostring(maxLowProb, "#.##")
if math.abs(lowProb - maxLowProb) < activationThreshold
label.new(bar_index, high, txt, yloc = yloc.belowbar, color = textColor, style = label.style_label_up, textcolor = color.black, force_overlay = true)
if math.abs(highProb - maxHighProb) < activationThreshold
label.new(bar_index, high, txt, yloc = yloc.abovebar, color = textColor, style = label.style_label_down, textcolor = color.black, force_overlay = true)
if realPivotLabels
if not na(highPivot)
txt = str.tostring(rsi , "#.##") + " HP -> " + str.tostring(highProb , "#.##") + " LP -> " + str.tostring(lowProb , "#.##") + " MHP -> " + str.tostring(maxHighProb , "#.##") + " MLP -> " + str.tostring(maxLowProb , "#.##")
label.new(bar_index - highPivotLen, high, txt, yloc = yloc.abovebar, color = textColor, style = label.style_label_down, textcolor = color.black, force_overlay = true)
if not na(lowPivot)
txt = str.tostring(rsi , "#.##") + " HP -> " + str.tostring(highProb , "#.##") + " LP -> " + str.tostring(lowProb , "#.##") + " MHP -> " + str.tostring(maxHighProb , "#.##") + " MLP -> " + str.tostring(maxLowProb , "#.##")
label.new(bar_index - lowPivotLen, high, txt, yloc = yloc.belowbar, color = textColor, style = label.style_label_up, textcolor = color.black, force_overlay = true)
//#endregion
if tableEnabled
var table realtimeTable = table.new(getPosition(tableLocation), 2, 10, bgcolor = screenerColor, frame_width = 2, frame_color = frameColor, border_width = 1, border_color = borderColor)
// Header
table.merge_cells(realtimeTable, 0, 0, 1, 0)
table.cell(realtimeTable, 0, 0, "KDE Optimized RSI", text_color = textColorDB, bgcolor = screenerColor)
// RSI
table.cell(realtimeTable, 0, 1, "RSI", text_color = textColorDB, bgcolor = screenerColor)
table.cell(realtimeTable, 1, 1, str.tostring(rsi, "#"), text_color = textColorDB, bgcolor = screenerColor)
// KDE
table.cell(realtimeTable, 0, 2, (lowProb > highProb) ? "Bullish KDE" : "Bearish KDE", text_color = (lowProb > highProb) ? bullishColor : bearishColor, bgcolor = screenerColor)
table.cell(realtimeTable, 1, 2, str.tostring(nz(math.max(highProb, lowProb), 0) * 100, "#.##") + "%", text_color = textColorDB, bgcolor = screenerColor)
MERCURY by DrAbhiramSivprasad"MERCURY by DrAbhiramSivprasad"
Developed from over 10 years of personal trading experience, the Mercury Indicator is a strategic tool designed to enhance accuracy in trading decisions. Think of it as a guiding light—a supportive tool that helps traders refine and build more robust strategies by integrating multiple powerful elements into a single indicator. I’ll be sharing some examples to illustrate how I use this indicator in my own trading journey, highlighting its potential to improve strategy accuracy.
Reason behind the combination of emas , cpr and vwap is it provides very good support and resistance in my trading carrier so now i brought them together in one plate
How It Works:
Mercury combines three essential elements—EMA, VWAP, and CPR—each of which plays a vital role in detecting support and resistance:
Exponential Moving Averages (EMAs): Known for their strength in providing dynamic support and resistance levels, EMAs help in identifying trends and shifts in momentum. This indicator includes a dashboard with up to nine customizable EMAs, showing whether each is acting as support or resistance based on real-time price movement.
Volume Weighted Average Price (VWAP): VWAP also provides valuable support and resistance, often regarded as a fair price level by institutional traders. Paired with EMAs, it forms a dual-layered support/resistance system, adding an additional level of confirmation.
Central Pivot Range (CPR): By combining CPR with EMAs and VWAP, Mercury highlights “traffic blocks” in your target journey. This means it identifies zones where price is likely to stall or reverse, providing additional guidance for navigating entries and exits.
Why This Combination Matters:
Using these three tools together gives you a more complete view of the market. VWAP and EMAs offer dynamic trend direction and support/resistance, while CPR pinpoints critical price zones. This combination helps you find high-probability trades, adding clarity to complex market situations and enabling stronger confirmation on trend or reversal decisions.
How to Use:
Trend Confirmation: Check if all EMAs are aligned (green for uptrend, red for downtrend), which is visible in the EMA dashboard. An alignment across VWAP, CPR, and EMAs signifies high confidence in trend direction.
Breakouts & Breakdowns: Mercury has an alert system to signal when a price breakout or breakdown occurs across VWAP, EMA1, and EMA2. This can help in spotting strong directional moves.
Example Application: In my trading, I use Mercury to identify support/resistance zones, confirming trends with EMA/VWAP alignment and using CPR as a checkpoint. I find this especially useful for day trading and swing setups.
Recommended Timeframes:
Day Trading: 5 to 15-minute charts for swift, actionable insights.
Swing Trading: 1-hour or 4-hour charts for broader trend analysis.
Note:
The Mercury Indicator should be used as a supportive tool rather than a standalone strategy, guiding you toward informed decisions in line with your trading style and goals.
EXAMPLE OF TRADE
you can see the cart of XAUUSD on 11th nov 2024
1.SHORT POSITION - TIME FRAME 15 MIN
So here for a short position you need to wait for a breakdown candle which will print in orange post the candle you need to check ema dashboard is completly red that indicates no traffic blocks in your journey to destiny target from ema's and you can take the target from nearest cpr support line
TAKEN IN XAUUSD you can see in chart of XAUUSD on 7th nov
2.LONG POSITION - TIME FRAME 15 MIN -
So here for long position you need to wait for a breakout candle from indicator thats here is blue and check all ema boxes are green and candle body should close above all the 3 lines here it is the both ema 1 and 2 and the vwap line then you can take and entry and your target will be the nearest resistance from the daily cpr
3. STOP LOSS CRITERIA
After the entry any candle close below any of the last line from entry for example we have 3 lines vwap and ema 1 and 2 lines and u have made an entry and the last line before the entry is vwap then if any candle closes below vwap can be considered as stoploss like wise in any lines
The MERCURY indicator is a comprehensive trading tool designed to enhance traders' ability to identify trends, breakouts, and reversals effectively. Created by Dr. Abhiram Sivprasad, this indicator integrates several technical elements, including Central Pivot Range (CPR), EMA crossovers, VWAP levels, and a table-based EMA dashboard, to offer a holistic trading view.
Core Components and Functionality:
Central Pivot Range (CPR):
The CPR in MERCURY provides a central pivot level along with Below Central (BC) and Top Central (TC) pivots. These levels act as potential support and resistance, useful for identifying reversal points and zones where price may consolidate.
Exponential Moving Averages (EMAs):
MERCURY includes up to nine EMAs, with a customizable EMA crossover alert system. This feature enables traders to see shifts in trend direction, especially when shorter EMAs cross longer ones.
VWAP (Volume-Weighted Average Price):
VWAP is incorporated as a dynamic support/resistance level and, combined with EMA crossovers, helps refine entry and exit points for higher probability trades.
Breakout and Breakdown Alerts:
MERCURY monitors conditions for upside and downside breakouts. For an upside breakout, all EMAs turn green and a candle closes above VWAP, EMA1, and EMA2. Similarly, all EMAs turning red, combined with a close below VWAP and EMA1/EMA2, signals a downside breakdown. Continuous alerts are available until the trend shifts.
Real-Time EMA Dashboard:
A table displays each EMA’s relative position (Above or Below), helping traders quickly gauge trend direction. Colors in the table adjust to long/short conditions based on EMA alignment.
Usage Recommendations:
Trend Confirmation:
Use the CPR, EMA alignments, and VWAP to confirm uptrends and downtrends. The table highlights trends, making it easy to spot long or short setups at a glance.
Breakout and Breakdown Alerts:
The alert system is customizable for continuous notifications on critical price levels. When all EMAs align in one direction (green for long, red for short) and the close is above or below VWAP and key EMAs, the indicator confirms a breakout/breakdown.
Adaptable for Different Styles:
Day Trading: Traders can set shorter EMAs for quick insights.
Swing Trading: Longer EMAs combined with CPR offer insights into sustained trends.
Recommended Settings:
Timeframes: MERCURY is suitable for timeframes as low as 5 minutes for intraday traders, up to daily charts for trend analysis.
Symbols: Works across forex, stocks, and crypto. Adjust EMA lengths for asset volatility.
Example Strategy:
Long Entry: When the price crosses above CPR and closes above both EMA1 and EMA2.
Short Entry: When the price falls below CPR with a close below both EMA1 and EMA2.
Dynamic Time Period CandlesThis indicator gives the dynamic history of the current price over various time frames as a series of candles on the right of the display, with optional lines on the chart, so that you can assess the current trend more easily.
In the library I found lots of indicators that looked at the previous xx time period candle, but they then immediately switched to the new xx time candle when it started to be formed. This indicator looks back at the rolling previous time period. With this indicator, you can clearly see how price has been behaving over time.
IMPORTANT SETUP INFO:
Initially, you must go into the settings and select the timeframe (in minutes) that your chart is displaying. If you don't do this then the indicator will look back the wrong number of candles and give you totally wrong results.
You can then setup how high you want the candle labels to be on the chart.
Then you can select settings for each candle that you want displayed. Anywhere between 1 and 5 different timeframes can be displayed on the chart at once.
I initially published an indicator called 'Dynamic 4-Hour Candle (Accurate Highs and Lows)', but this new indicator is so different that it needs to be forked and published as a separate indicator. The reasons for this are below:
The original indicator only looked at the previous 4 hour time period. This indicator allows the user to select any time period that they choose.
The original indicator only looked at one time period. This indicator allows to select between one and five time periods on the chart at once.
The original indicator did not put lines on the chart to show the lookback period and the highs and lows of that time period. This indicator does both those things.
The name of the original indicator in no way now describes what this new indicator is capable of, and would be very misleading to anyone who came across it. This new indicator has a name that much more accurately reflects what its' purpose and functionality is.
Soorfin on LiqsRefined liquidation indicator
- Last highs (given on a period)
- Last lows (same)
- Custom price
- Live price
This is a refined liquidation indicator more customizable and better.
Credits goes to @mabonyi for the original idea.
Daily CRTDaily CRT Indicator
The Daily CRT Indicator is a custom technical analysis tool designed to help traders identify and visualize key price patterns on the daily timeframe. Specifically, it detects and marks the "Sweep and Close Inside" pattern, which is a price action pattern that can signal potential trading opportunities.
Key Features:
Pattern Detection:
The indicator detects two specific price action patterns:
Sweep and Close Above: When the current price sweeps above the previous day’s high and closes inside the range, indicating a potential bullish breakout or continuation.
Sweep and Close Below: When the current price sweeps below the previous day’s low and closes inside the range, signaling a potential bearish move.
Horizontal Lines:
The indicator automatically draws horizontal lines at the previous day’s high and low levels whenever a pattern is detected, providing a visual reference for key support and resistance zones.
These lines are displayed in real-time on the chart and adjust dynamically as new patterns form.
Customizable Line Appearance:
Choose the color, thickness, and style (solid, dashed, or dotted) of the lines to fit your preferred chart aesthetic.
Alert System:
The indicator comes with built-in alerts. Set an alert to notify you when the Sweep and Close Inside pattern is detected, helping you stay on top of potential trade setups.
History Management:
Show History: Optionally display the detected patterns on previous bars (past patterns).
Customizable History Duration: Control how far back you want to view the patterns, allowing you to adjust for a cleaner chart and focus on the most recent setups.
Visual Labels:
When the pattern is detected, the indicator can display a label under the bar (customizable) to highlight the occurrence of the pattern, making it easier for traders to spot potential trade signals.
Built for the Daily Timeframe:
This indicator is specifically designed to work on the daily timeframe and is ideal for swing traders and longer-term traders who are focused on the daily price action and want to capture patterns that indicate potential market reversals or breakouts.
How It Works:
The indicator monitors the previous day's price action and looks for situations where the current price action either sweeps the previous day's high or low and then closes inside the range of the previous day's bar. This type of price movement can often signal that a reversal or continuation is about to occur. The indicator marks these setups by drawing horizontal lines and optionally displays labels for quick identification.
Settings & Customization:
Line Color: Customize the color of the lines marking the previous day’s high and low.
Line Thickness: Choose from different thickness levels for better visibility.
Line Style: Pick from solid, dashed, or dotted styles.
Show History: Toggle the display of historical patterns, with the option to control how many days back to show.
Show Labels: Option to toggle the display of labels when the pattern is detected.
Alert Condition: Receive alerts when a pattern is detected, ensuring you never miss a trade opportunity.
Ideal For:
Swing Traders: This indicator is perfect for traders looking to capture swings in the market based on daily price action.
Pattern Traders: Those who trade based on specific chart patterns will benefit from this tool, as it identifies important reversal and breakout signals.
Technical Analysts: Anyone who incorporates price action patterns into their strategy can use this tool as a supplemental analysis tool to improve their trading decisions.
By using the Daily CRT Indicator, you’ll have a powerful tool to help you spot important price action patterns that may indicate key market moves. Whether you're looking to catch breakouts, reversals, or simply track significant support and resistance levels, this indicator is a versatile addition to your trading toolkit.
This description provides a clear understanding of how the Daily CRT Indicator works and what value it offers, making it easy for traders to know if it fits their trading style. Feel free to tweak the description further depending on the details you’d like to emphasize.
W.ARITAS™ Quantum RSI + BollingerW.ARITAS™ Quantum RSI + Bollinger - Script Overview
The W.ARITAS™ Quantum RSI + Bollinger indicator provides a highly adaptable RSI tool with Bollinger Band cloud overlay. It leverages volatility-based adjustments, quantum-inspired volatility correction, wave-function transformations, and gradient color displays to create a dynamic, visually informative trading tool.
Key Components and Functionalities:
Input Parameters and Visual Controls:
This section allows users to adjust the key variables of the RSI and Bollinger calculations, including base lengths, source data, Bollinger Band width, volatility adjustment factors, and quantum scaling. Visual customization includes color gradient boundaries for RSI values.
Gradient Color Generation:
c_any_size and c_make_gradient functions generate a dynamic color gradient for the RSI visualization. These gradients reflect overbought and oversold zones, and the gradient adapts based on fibonacci values, enhancing visual insights.
Shared Smoothing and Centering Functions:
Key functions like f_rma (custom RMA), f_CenterAroundZero , and f_EnhancedJMA (Jurik Moving Average with wavelet filtering) provide essential smoothing and normalization for the RSI values, making the indicator reactive while reducing rsi signal noise.
Core RSI and Bollinger Calculations:
The custom RSI calculation, f_VRSI , dynamically adjusts based on volatility, leveraging a custom RMA to modify the RSI length according to current market conditions. Similarly, the Bollinger Band calculation, f_EnhancedBollinger , adapts to volatility fluctuations by widening or narrowing the bands, signaling potential trend reversals or breakout points. These bands form the basis of the Bollinger cloud, and when the RSI curve intersects with this cloud, it highlights potential market reversal points.
Quantum Effects and Wave Function Modulation:
Quantum Volatility Correction f_QuantumVolatilityCorrection : Applies quantum-inspired oscillations to correct the volatility measurement, stabilizing and balancing the RSI/Bollinger responsiveness during high or low volatility periods.
Wave Functions f_WaveFunction : Integrates Fibonacci and phase modulation, introducing cyclical patterns that align with observed market rhythms. This function reshapes the RSI/Bollinger values into a sine-like wave, creating oscillatory behavior that enhances trend identification.
Enhanced Plotting and Boundary Visualization:
Smart Gradient Colors: Using smart_gradient_normalized , the color gradient adapts to RSI values, visualizing shifts in market momentum and potential reversal zones.
Boundary Lines and Fills: Filled boundary lines demarcate overbought, oversold, and mid-range zones. These lines help users identify extremes, which can signify potential entry or exit points.
Educational and Community Value:
Each function is purpose-built and original, developed solely for this script except for the JMA function, which is a modified version of Jurik’s algorithm, acknowledged accordingly in the comments.
The script, provides a rich educational resource for the TradingView community. It offers a complete, well-documented example of a quantum-inspired technical indicator with advanced volatility adjustment, suitable for both educational purposes and practical trading.
Highs and Lows [Scarface Trades]This indicator visualizes a strategy described by Scarface Trades on Youtube. There are three kinds of support/resistance areas based on:
- the previous day's high and low
- the overnight session's high and low
- the high and low of the first five minutes of the day (09:30 - 09:35 Eastern)
The primary goal of the strategy is to trade breaks of these resistance lines after confirmation in form of a pullback into resistance gone support.
Volume Flow ConfluenceVolume Flow Confluence (CMF-KVO Integration)
Core Function:
The Volume Flow Confluence Indicator combines two volume-analysis methods: Chaikin Money Flow (CMF) and the Klinger Volume Oscillator (KVO). It displays a histogram only when both indicators align in their respective signals.
Signal States:
• Green Bars: CMF is positive (> 0) and KVO is above its signal line
• Red Bars: CMF is negative (< 0) and KVO is below its signal line
• No Bars: When indicators disagree
Technical Components:
Chaikin Money Flow (CMF):
Measures the relationship between volume and price location within the trading range:
• Calculates money flow volume using close position relative to high/low range
• Aggregates and normalizes over specified period
• Default period: 20
Klinger Volume Oscillator (KVO):
Evaluates volume in relation to price movement:
• Tracks trend changes using HLC3
• Applies volume force calculation
• Uses two EMAs (34/55) with a signal line (13)
Practical Applications:
1. Signal Identification
- New colored bars after blank periods show new agreement between indicators
- Color intensity differentiates new signals from continuations
- Blank spaces indicate lack of agreement
2. Trend Analysis
- Consecutive colored bars show continued indicator agreement
- Transitions between colors or to blank spaces show changing conditions
- Can be used alongside other technical analysis tools
3. Risk Considerations
- Signals are not predictive of future price movement
- Should be used as one of multiple analysis tools
- Effectiveness may vary across different markets and timeframes
Technical Specifications:
Core Algorithm
CMF = Σ(((C - L) - (H - C))/(H - L) × V)n / Σ(V)n
KVO = EMA(VF, 34) - EMA(VF, 55)
Where VF = V × |2(dm/cm) - 1| × sign(Δhlc3)
Signal Line = EMA(KVO, 13)
Signal Logic
Long: CMF > 0 AND KVO > Signal
Short: CMF < 0 AND KVO < Signal
Neutral: All other conditions
Parameters
CMF Length = 20
KVO Fast = 34
KVO Slow = 55
KVO Signal = 13
Volume = Regular/Actual Volume
Data Requirements
Price Data: OHLC
Volume Data: Required
Minimum History: 55 bars
Recommended Timeframe: ≥ 1H
Credits:
• Marc Chaikin - Original CMF development
• Stephen Klinger - Original KVO development
• Alex Orekhov (everget) - CMF script implementation
• nj_guy72 - KVO script implementation
Buy&Sell Hollow CandlesThe Hollow Candles Script is a type of candlestick analysis script designed to highlight the following:
Purpose of the Script: This script provides the user with buy and sell signals based on candlesticks that show an upward or downward reversal.
Mechanism of the Script: When a hollow (unfilled) red candle appears, it signals a potential entry, provided that this candle is at a low point, following a series of red candles with higher volume than previous days. Similarly, it gives a sell signal when a green candle appears at a peak with high sell volume surpassing that of prior days. However, the appearance of these candles alone should not prompt an immediate buy or sell; you should wait for a confirming candle to validate the signal.
Sideways Movement Caution: If these signals appear during a sideways or flat trend, it is not advisable to proceed with buying or selling.
Chart Insights: The chart demonstrates certain buy and sell operations along with some non-ideal signals where decision-making should be based on fundamental analytical experience.
3 CANDLE SUPPLY/DEMANDExplanation of the Code:
Demand Zone Logic: The script checks if the second candle closes below the low of the first candle and the third candle closes above both the highs of the first and second candles.
Zone Plotting: Once the pattern is identified, a demand zone is plotted from the low of the first candle to the high of the third candle, using a dashed green line for clarity.
Markers: A small triangle marker is added below the bars where a demand zone is detected for easy visualization.
Efficient Logic: The script checks the conditions for demand zone formation for every three consecutive candles on the chart.
This approach should be both accurate and efficient in plotting demand zones, making it easier to spot potential support levels on the chart.
Nasan Hull-smoothed envelope The Nasan Hull-Smoothed Envelope indicator is a sophisticated overlay designed to track price movement within an adaptive "envelope." It dynamically adjusts to market volatility and trend strength, using a series of smoothing and volatility-correction techniques. Here's a detailed breakdown of its components, from the input settings to the calculated visual elements:
Inputs
look_back_length (500):
Defines the lookback period for calculating intraday volatility (IDV), smoothing it over time. A higher value means the indicator considers a longer historical range for volatility calculations.
sl (50):
Sets the smoothing length for the Hull Moving Average (HMA). The HMA smooths various lines, creating a balance between sensitivity and stability in trend signals.
mp (1.5):
Multiplier for IDV, scaling the volatility impact on the envelope. A higher multiplier widens the envelope to accommodate higher volatility, while a lower one tightens it.
p (0.625):
Weight factor that determines the balance between extremes (highest high and lowest low) and averages (sma of high and sma of low) in the high/low calculations. A higher p gives more weight to extremes, making the envelope more responsive to abrupt market changes.
Volatility Calculation (IDV)
The Intraday Volatility (IDV) metric represents the average volatility per bar as an exponentially smoothed ratio of the high-low range to the close price. This is calculated over the look_back_length period, providing a base volatility value which is then scaled by mp. The IDV enables the envelope to dynamically widen or narrow with market volatility, making it sensitive to current market conditions.
Composite High and Low Bands
The high and low bands define the upper and lower bounds of the envelope.
High Calculation
a_high:
Uses a multi-period approach to capture the highest highs over several intervals (5, 8, 13, 21, and 34 bars). Averaging these highs provides a more stable reference for the high end of the envelope, capturing both immediate and recent peak values.
b_high:
Computes the average of shorter simple moving averages (5, 8, and 13 bars) of the high prices, smoothing out fluctuations in the recent highs. This generates a balanced view of high price trends.
high_c:
Combines a_high and b_high using the weight p. This blend creates a composite high that balances between recent peaks and smoothed averages, making the upper envelope boundary adaptive to short-term price shifts.
Low Calculation
a_low and b_low:
Similar to the high calculation, these capture extreme lows and smooth low values over the same intervals. This approach creates a stable and adaptive lower bound for the envelope.
low_c:
Combines a_low and b_low using the weight p, resulting in a composite low that adjusts to price fluctuations while maintaining a stable trend line.
Volatility-Adjusted Bands
The final composite high (c_high) and composite low (c_low) bands are adjusted using IDV, which accounts for intraday volatility. When volatility is high, the bands expand; when it’s low, they contract, providing a visual representation of volatility-adjusted price bounds.
Basis Line
The basis line is a Hull Moving Average (HMA) of the average of c_high and c_low. The HMA is known for its smoothness and responsiveness, making the basis line a central trend indicator. The color of the basis line changes:
Green when the basis line is increasing.
Red when the basis line is decreasing.
This color-coded basis line serves as a quick visual reference for trend direction.
Short-Term Trend Strength Block
This component analyzes recent price action to assess short-term bullish and bearish momentum.
Conditions (green, red, green1, red1):
These are binary conditions that categorize price movements as bullish or bearish based on the close compared to the open and the close’s relationship with the exponential moving average (EMA). This separation helps capture different types of strength (above/below EMA) and different bullish or bearish patterns.
Composite Trend Strength Values:
Each of the bullish and bearish counts (above and below the EMA) is normalized, resulting in the following values:
green_EMAup_a and red_EMAup_a for bullish and bearish strength above the EMA.
green_EMAdown_a and red_EMAdown_a for bullish and bearish strength below the EMA.
Trend Strength (t_s):
This calculated metric combines the normalized trend strengths with extra weight to conditions above the EMA, giving more relevance to trends that have momentum behind them.
Enhanced Trend Strength
avg_movement:
Calculates the average absolute price movement over the short_term_length, providing a measurement of recent price activity that scales with volatility.
enhanced_t_s:
Multiplies t_s by avg_movement, creating an enhanced trend strength value that reflects both directional strength and the magnitude of recent price movement.
min and max:
Minimum and maximum percentile thresholds, respectively, based on enhanced_t_s for controlling the color gradient in the fill area.
Fill Area
The fill area between plot_c_high and plot_c_low is color-coded based on the enhanced trend strength (enhanced_t_s):
Gradient color transitions from blue to green based on the strength level, with blue representing weaker trends and green indicating stronger trends.
This visual fill provides an at-a-glance assessment of trend strength across the envelope, with color shifts highlighting momentum shifts.
Summary
The indicator’s purpose is to offer an adaptive price envelope that reflects real-time market volatility and trend strength. Here’s what each component contributes:
Basis Line: A trend-following line in the center that adjusts color based on trend direction.
Envelope (c_high, c_low): Adapts to volatility by expanding and contracting based on IDV, giving traders a responsive view of expected price bounds.
Fill Area: A color-gradient region representing trend strength within the envelope, helping traders easily identify momentum changes.
Overall, this tool helps to identify trend direction, market volatility, and strength of price movements, allowing for more informed decisions based on visual cues around price boundaries and trend momentum.
Combined Indicator for Analysing TrendThis Indicator would be able to analyse the current Trend of the market. However it is advisable to study further parametrs and have own study before following the Trend
Multi-Timeframe Market Structure [LuxAlgo Modified]Tells you if market structure in H1, H4, D1 or W1 is bullish or bearish.
Market structureHi all!
This script shows you the market structure. You can choose to show internal market structure (with pivots of a default length of 5) and swing market structure (with pivots of a default length of 50). For these two trends it will show you:
• Break of structure (BOS)
• Change of character (CHoCH) (mandatory)
• Equal high/low (EQH/EQL)
It's inspired by "Smart Money Concepts (SMC) " by LuxAlgo that will also show you the market structure.
It will create the two market structures depending on the pivots found. Both of these market structures can be enabled/disabled. The pivots length can be configured separately. The pivots found will be the 'base' of this indicator and will show you when price breaks it. When that happens a break of structure or a change of character will be created. The latest 5 pivots found within the current trends will be kept to take action on. The internal market structure is shown with dashed lines and swing market structure is shown with solid lines.
A break of structure is removed if an earlier pivots within the same trend is broken. Like in the images below, the first pivot (in the first image) is removed when an earlier pivot's higher price within the same trend is broken (the second image):
Equal high/lows have a pink zone (by default but can be changed by the user). These zones can be configured to be extended to the right (off by default). Equal high/lows are only possible if it's not been broken by price and if a later bar has a high/low within the limit it's added to the zone (without it being more 'extreme' (high or low) then the previous price). A factor (percentage of width) of the Average True Length (of length 14) that the pivot must be within to to be considered an Equal high/low. This is configurable and sets this 'limit' and is 10 by default.
You are able to show the pivots that are used. "HH" (higher high), "HL" (higher low), "LH" (lower high), "LL" (lower low) and "H"/"L" (for pivots (high/low) when the trend has changed) are the labels used.
This script has proven itself useful for me to quickly see how the current market is. You can see the pivots (price and bar) where break of structure or change of character happens to see the current trends. I hope that you will find this useful for you.
When programming I focused on simplicity and ease of read. I did not focus on performance, I will do so if it's a problem (haven't noticed it is one yet).
You can set alerts for when a change of character happens. You can configure it to fire on when it happens (all or once per bar) but it defaults to 'once_per_bar_close' to avoid repainting. This has the drawback to alert you when the bar closes.
TLDR: this is an indicator showing you the market structure (break of structures and change of characters) using swing points/pivots. Two trends can be shown, internal (with pivots of length of 5) and swing (with pivots of the length of 50).
Best of trading luck!
Economic Seasons [Daveatt]Ever wondered what season your economy is in?
Just like Mother Nature has her four seasons, the economy cycles through its own seasons! This indicator helps you visualize where we are in the economic cycle by tracking two key metrics:
📊 What We're Tracking:
1. Interest Rates (USIRYY) - The yearly change in interest rates
2. Inflation Rate (USINTR) - The rate at which prices are rising
The magic happens when we normalize these values (fancy math that makes the numbers play nice together) and compare them to their recent averages. We use a lookback period to calculate the standard deviation and determine if we're seeing higher or lower than normal readings.
🔄 The Four Economic Seasons & Investment Strategy:
1. 🌸 Goldilocks (↑Growth, ↓Inflation)
"Not too hot, not too cold" - The economy is growing steadily without overheating.
BEST TIME TO: Buy growth stocks, technology, consumer discretionary
WHY: Companies can grow earnings in this ideal environment of low rates and stable prices
2. 🌞 Reflation (↑Growth, ↑Inflation)
"Party time... but watch your wallet!" - The economy is heating up.
BEST TIME TO: Buy commodities, banking stocks, real estate
WHY: These sectors thrive when inflation rises alongside growth
3. 🌡️ Inflation (↓Growth, ↑Inflation)
"Ouch, my purchasing power!" - Growth slows while prices keep rising.
BEST TIME TO: Rotate into value stocks, consumer staples, healthcare
WHY: These defensive sectors maintain pricing power during inflationary periods
4. ❄️ Deflation (↓Growth, ↓Inflation)
"Winter is here" - Both growth and inflation are falling.
BEST TIME TO: Focus on quality bonds, cash positions, and dividend aristocrats
WHY: Capital preservation becomes key; high-quality fixed income provides safety
🎯 Strategic Trading Points:
- BUY AGGRESSIVELY: During late Deflation/early Goldilocks (the spring thaw)
- HOLD & ACCUMULATE: Throughout Goldilocks and early Reflation
- START TAKING PROFITS: During late Reflation/early Inflation
- DEFENSIVE POSITIONING: Throughout Inflation and Deflation
⚠️ Warning Signs to Watch:
- Goldilocks → Reflation: Time to reduce growth stock exposure
- Reflation → Inflation: Begin rotating into defensive sectors
- Inflation → Deflation: Quality becomes crucial
- Deflation → Goldilocks: Start building new positions
The blue dot shows you where we are right now in this cycle.
The red arrows in the middle remind us that this is a continuous cycle - one season flows into the next, just like in nature!
💡 Pro Tip: The transitions between seasons often provide the best opportunities - but also the highest risks. Use additional indicators and fundamental analysis to confirm these shifts.
Remember: Just like you wouldn't wear a winter coat in summer, you shouldn't use a Goldilocks strategy during Inflation! Time your trades with the seasons. 🎯
Happy Trading! 📈