Price Density Clouds [EXCAVO]Continuous Kernel-Density Map of Where Price Has Actually Traded
The Price Density Clouds builds a smooth, continuous probability density of
price over a lookback window and paints it as gradient clouds directly behind
the candles. Dense, saturated clouds mark value zones - the equilibrium levels
where the market has spent the most time and where price tends to stall and
revert. Thin, transparent gaps mark inefficiency zones - levels price travels
through quickly. A dashed POC line marks the single highest-probability price,
and the Value Area High / Low bracket the core of the distribution.
This is not a bin-based volume profile. Instead of chopping price into discrete
buckets, KDE sums a smooth gaussian kernel around every price point, producing a
continuous density curve with no bin-edge artefacts. The bandwidth is set
automatically by Silverman's rule, so the smoothing adapts to the instrument's
own volatility.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator. Gradient clouds appear behind the candles
over the lookback window, brightest at the highest-probability
levels and fading out toward thin zones.
Step 2 → Read the clouds. Saturated bands = value / equilibrium where
price tends to stall and mean-revert. Faint gaps = inefficiency
where price moves fast - natural travel targets.
Step 3 → Use the POC. The dashed POC line is the single most-traded
level - a robust magnet and support / resistance anchor. Price
far from POC has a statistical pull back toward it.
Step 4 → Use the Value Area. The dotted Value Area High / Low bracket
the core of the distribution (default 70%). Acceptance inside the
area is balance; rejection outside it is imbalance worth trading.
Step 5 → Check the side profile. The gradient density profile on the
right of the last bar is the same density rotated 90 degrees - a
quick read of the full distribution shape at a glance.
Step 6 → Combine with structure. Clouds are context, not direction.
They pair well with trend, sweep, and breakout tools - a breakout
into a thin zone tends to run; a breakout into a dense zone tends
to stall.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ Gaussian Kernel Density
Every close in the lookback window contributes a gaussian bell curve centred at
its own price. The curves are summed across the price range to produce a single
continuous density function: density(x) = sum over j of exp(-0.5 x ((x - price_j)
/ h)^2). Levels where many bars cluster get tall, overlapping kernels and a high
density; isolated levels get a low density.
◆ Silverman Bandwidth
The kernel width h controls smoothness. It is set automatically by Silverman's
rule of thumb: h = 1.06 x sigma x n^(-1/5), where sigma is the stdev of the
lookback prices and n is the sample size. The Bandwidth Multiplier input scales
this for sharper or smoother clouds. Auto-bandwidth means the same settings
adapt across instruments and timeframes.
◆ Normalisation and POC
The density is evaluated at Resolution levels between the lookback high and low,
then normalised so the peak equals 1.0. That peak level is the POC (Point of
Control) - the single highest-probability price. Cloud opacity and colour are
driven by each level's normalised density.
◆ Value Area
Starting at the POC, the algorithm expands outward, each step absorbing the
denser of the two neighbouring levels, until the enclosed density reaches the
Value Area % of the total (default 70). The price extent reached becomes the
Value Area High and Low.
◆ Gradient Rendering
Each density band of the cloud is drawn as a horizontal box tinted by a
two-colour gradient: the Low Density Color at thin levels through to the High
Density Color at the POC, with opacity ramping in parallel. Adjacent bands tile
continuously, so the cloud reads as a smooth heat-map rather than discrete
blocks. The same gradient drives the right-side density profile, whose width
per level scales with density - at the default resolution the edge reads as a
near-smooth wave while keeping the per-level gradient colour.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ Continuous Density, Not Bins
Standard volume / price profiles split price into discrete bins, so the result
depends heavily on bin size and shows hard edges. KDE produces a smooth
continuous curve - no bin-edge artefacts, no arbitrary bucket count, just the
true shape of where price has traded.
◆ Auto-Adaptive Bandwidth
Silverman's rule sizes the smoothing from the instrument's own volatility and
sample size. The clouds stay meaningful on BTC, EURUSD, gold or an index with
the same default settings.
◆ Value Structure In One View
POC, Value Area High / Low and the full density shape are all on the chart at
once, with a matching side profile - the complete market-profile read without a
separate pane or a session reset.
◆ Premium Gradient Visual
A smooth two-colour density gradient behind the candles with parallel opacity
ramp, a clean dashed POC, dotted value-area lines, and a right-side profile
histogram. The clouds sit behind price as context and never clutter the read.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel (top right) with the current value read:
POC - price of the highest-density level
Value Area High - upper bound of the value area
Value Area Low - lower bound of the value area
Price Zone - whether price is Above Value, In Value, or Below Value
Lookback - bars used to build the distribution
Legend table (bottom left) explains every colour. Both panels toggle in the
Dashboard settings.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
Engine
Lookback Period - 200 (bars used to build the price distribution)
Resolution - 120 (number of horizontal density bands; higher = smoother gradient and profile edge, up to 200)
Bandwidth Multiplier - 1.0 (smoothness; 1.0 = Silverman auto, higher = broader clouds)
Value Area % - 70 (percentage of total density that defines the value area)
Visualization
Low Density Color - blue (thin / inefficiency end of the gradient)
High Density Color - orange (dense / value end of the gradient)
POC Line Color - near-white (high contrast against the dense orange cloud the POC sits in)
Min Cloud Opacity - 8 (opacity of the lowest-density band; keeps empty zones faint)
Max Cloud Opacity - 65 (opacity of the POC band)
Show POC Line - ON
Show Value Area - ON (dotted Value Area High / Low lines)
Value Area Highlight - ON (boosts band opacity inside the value area so the 70% core pops)
Show Side Profile - ON
Profile Outline - ON (thin bright line tracing the right edge of the profile for a crisp silhouette)
Cloud Forward Extend - 10 (bars the clouds extend right of the last bar)
Dashboard
Show Dashboard - ON
Dashboard Position - Top Right
Show Legend - ON
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
Indicator

KDE Reversals [UAlgo]KDE Reversals is a statistical reversal oscillator that measures where the current price sits inside its recent distribution using a Kernel Density Estimation based cumulative probability model. Instead of relying on fixed momentum formulas or classic overbought and oversold oscillators, the script builds a rolling sample of recent source values, estimates a smoothed empirical distribution, and converts the current value into a percentile style reading from 0 to 100.
The result is a non parametric probability oscillator that answers a simple question: how extreme is the current price relative to the recent sample? Very high readings mean the current value is located near the upper tail of the recent distribution. Very low readings mean it is near the lower tail. The script then uses user defined upper and lower reversal zones to detect potential turning points when the percentile reading exits those extreme regions.
The indicator runs in a separate pane ( overlay=false ) and combines:
A rolling KDE based empirical CDF oscillator
Upper and lower statistical reversal zones
Gradient coloring based on percentile position
Background highlighting in extreme conditions
Optional reversal labels when the percentile exits an extreme zone
This makes the tool especially useful for traders who want a more distribution aware approach to reversal detection rather than a fixed oscillator threshold based only on momentum formulas.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) KDE Based Empirical CDF Oscillator
The core output of the script is a percentile style oscillator built from Kernel Density Estimation. It estimates the cumulative distribution position of the current source value relative to a rolling lookback sample and expresses that result as a percentage from 0 to 100.
This gives a probabilistic location measure rather than a raw momentum reading.
🔸 2) Rolling Lookback Distribution Model
The script stores a rolling window of recent source values in an internal array. As new bars arrive, the oldest values are removed once the array reaches the configured length. This keeps the distribution adaptive to recent market behavior.
Because the model is rolling, the oscillator can adjust as the market shifts from one regime to another.
🔸 3) Non Parametric Reversal Logic
Unlike indicators that assume a fixed normal distribution of prices, this script uses a kernel smoothed empirical distribution. That means the reversal zones are based on the actual recent sample shape, not a rigid assumption about how price should be distributed.
This can make the signal more responsive to skewed, compressed, or uneven recent market structure.
🔸 4) Custom Upper and Lower Reversal Zones
Users can define:
An upper reversal zone in percentile terms
A lower reversal zone in percentile terms
These thresholds determine what counts as statistically stretched relative to the recent sample. This allows the indicator to be tuned for more aggressive or more selective reversal detection.
🔸 5) Reversal Triggers on Exit from Extremes
The script does not trigger simply because the oscillator enters an extreme zone. Instead, it triggers when the percentile reading exits the extreme zone:
A sell trigger occurs when the oscillator crosses back below the upper threshold
A buy trigger occurs when the oscillator crosses back above the lower threshold
This design aims to catch reversal confirmation after an extreme condition begins to unwind.
🔸 6) Dynamic Gradient Coloring
The percentile line is colored with a gradient between bullish and bearish colors based on its position between the lower and upper thresholds. This makes it easy to identify whether the current reading is leaning toward lower tail, neutral, or upper tail conditions.
🔸 7) Upper and Lower Zone Fills
The script includes gradient fills above and below the midline so the oscillator visually emphasizes upper tail and lower tail behavior. This improves readability and helps the user quickly identify whether the current reading is operating in a statistically stretched region.
🔸 8) Extreme Zone Background Highlighting
When the oscillator is above the upper threshold or below the lower threshold, the pane background is lightly highlighted. This creates an immediate visual cue that the current reading is inside a high probability reversal watch zone.
🔸 9) Optional Reversal Labels
When enabled, the script prints:
A downward label after a bearish reversal trigger
An upward label after a bullish reversal trigger
These labels are intentionally simple and keep the pane clean while still marking the event clearly.
🔸 10) Flexible Source Selection
The user can choose which source series to analyze, not only close. This allows the KDE engine to be applied to other price derived series if desired.
🔹 Calculations
1) Rolling Data Queue
The script stores recent source values in a custom KDEData object:
type KDEData
array prices
int length
Each bar, the new value is pushed into the array:
this.prices.push(val)
if this.prices.size() > this.length
this.prices.shift()
This creates a fixed length rolling sample used for the KDE calculation.
2) Interquartile Range (IQR) Calculation
To make the bandwidth estimate more robust, the script computes the interquartile range from a sorted copy of the rolling sample:
int q1_idx = int(math.floor(n * 0.25))
int q3_idx = int(math.floor(n * 0.75))
sorted.get(q3_idx) - sorted.get(q1_idx)
The IQR is later used as part of the spread estimate for kernel bandwidth selection.
3) Robust Spread Estimate
The script combines sample standard deviation and IQR based scaling:
float stdev = this.prices.stdev()
float iqr = this.get_iqr()
float spread = math.min(stdev, iqr / 1.34)
Interpretation:
iqr / 1.34 is a robust estimate of standard deviation under near normal assumptions.
Taking the minimum of stdev and iqr / 1.34 helps reduce the effect of extreme outliers when setting the kernel width.
If the spread collapses to zero, the script falls back to a very small positive value.
4) KDE Bandwidth Selection
The kernel bandwidth is computed using a Silverman style rule:
float h = 1.06 * spread * math.pow(n, -0.2)
This gives the smoothing width used in the Gaussian kernel estimation. Larger sample size reduces the bandwidth, while larger spread increases it.
If the calculated bandwidth is zero, the script forces a small fallback:
if h == 0
h := 0.0001
5) Gaussian Error Function Approximation
The script defines its own approximation of the error function:
erf(float x) =>
...
This function is then used to build the standard normal cumulative distribution function:
norm_cdf(float z) =>
float sqrt2 = math.sqrt(2)
0.5 * (1.0 + erf(z / sqrt2))
This is the mathematical core that converts standardized distances into cumulative probabilities.
6) KDE Based Empirical CDF Calculation
For the current price, the script computes a smoothed empirical CDF by averaging the Gaussian CDF centered on every historical sample point:
for i = 0 to n - 1
float xi = this.prices.get(i)
float z = (current_price - xi) / h
sum_prob += norm_cdf(z)
Then:
(sum_prob / n) * 100.0
Interpretation:
Each historical observation contributes a smooth cumulative probability curve.
Averaging them creates a KDE smoothed empirical percentile estimate for the current price.
This is more stable than a raw rank percentile because it smooths the distribution instead of using hard cutoffs only.
7) Warm Up Condition
The indicator only computes the KDE percentile once the rolling sample is fully populated:
if kde.prices.size() == lengthInput
cdf_percent := kde.get_kde_cdf(srcInput)
Before that, the output remains na , which prevents incomplete early calculations.
8) Oscillator Interpretation
The resulting cdf_percent is a percentile style value:
Near 0 means the current source is near the lower tail of the recent distribution
Near 50 means it is near the middle of the recent distribution
Near 100 means it is near the upper tail of the recent distribution
This is not a momentum ratio. It is a location measure inside the recent smoothed distribution.
9) Threshold Logic
The user defines:
float upperThreshold = input.float(95.0, ...)
float lowerThreshold = input.float(5.0, ...)
These thresholds define statistically extreme regions. For example:
A 95 reading means the source is near the top tail of the recent sample
A 5 reading means the source is near the bottom tail
10) Reversal Trigger Conditions
The script does not trigger on entry into the zone. It triggers when the oscillator exits the zone:
Bearish reversal trigger:
bool sellTrigger = ta.crossunder(cdf_percent, upperThreshold)
Bullish reversal trigger:
bool buyTrigger = ta.crossover(cdf_percent, lowerThreshold)
Interpretation:
A sell trigger means the percentile was above the upper threshold and then moved back below it.
A buy trigger means the percentile was below the lower threshold and then moved back above it.
This acts more like a reversion confirmation than an early warning.
11) Visual Gradient Line
The main oscillator line color is derived from its current percentile position:
color cdfColor = color.from_gradient(cdf_percent, lowerThreshold, upperThreshold, col_bull, col_bear)
This creates a smooth transition from bullish coloring in the lower reversal area toward bearish coloring in the upper reversal area.
12) Gradient Fill Zones
The script fills the area between the percentile line and the hidden midline (50) separately for upper and lower halves:
fill(p_cdf, p_mid, top_value=100, bottom_value=50, ...)
fill(p_cdf, p_mid, top_value=50, bottom_value=0, ...)
This gives the oscillator a cleaner and more informative visual structure than a plain line alone.
13) Background Highlighting
When the oscillator is inside an extreme zone, the pane background is lightly shaded:
bgcolor(cdf_percent >= upperThreshold ? ... : cdf_percent <= lowerThreshold ? ... : na)
This does not trigger a signal by itself. It simply highlights that the reading is currently in a statistically extreme region.
14) Reversal Labels
If labels are enabled, the script marks reversal exits with simple directional arrows:
For bearish reversal:
label.new(bar_index, cdf_percent + 3, "▼", ...)
For bullish reversal:
label.new(bar_index, cdf_percent - 3, "▲", ...)
The labels are plotted near the oscillator value, not on price, which keeps the indicator self contained in its own pane. Indicator

KDE Value Clouds [LuxAlgo]The KDE Value Clouds indicator is a quantitative tool that uses Kernel Density Estimation (KDE) to visualize the statistical distribution of price action, identifying high-density "Value Clouds" where the market has spent the most time.
🔶 USAGE
The indicator highlights areas of price " fair value " by calculating the probability density of price across a user-defined lookback period. Traders can use these density clusters to identify significant support and resistance levels that are often invisible to standard trend-following indicators.
🔹 Value Clouds
The " Value Clouds " appear directly on the price chart as gradient boxes. These clouds highlight regions where the density of price action exceeds the 50th percentile of the total distribution.
High Density (Bright Colors): Indicates a "Balance Area" where the market has reached a temporary equilibrium. These often act as magnets for price.
Low Density (Gaps): Indicates "Inefficiency" or fast moves where the market did not spend much time. These areas are often revisited or "filled" later.
🔹 KDE Profile & POC
On the right side of the chart, a smooth horizontal profile represents the continuous density function. The KDE POC (Point of Control) is the single price level with the highest calculated density within the lookback period, serving as the ultimate "anchor" for the current market regime.
🔹 How to use
Traders can look for price to "stall" or range within the bright Value Clouds, as these represent accepted price levels. When price moves into a "Gap" (a low-density area), it often moves quickly until it reaches the next cloud.
The KDE POC can be used as a primary support or resistance level; a breakout above a high-density cloud often signals a shift in market sentiment, while a rejection at the edge of a cloud suggests the market is still in a balanced state.
🔶 DETAILS
🔹 KDE vs. Volume Profile
A standard Volume Profile relies on "bins" (rectangles) to count volume at specific price steps. This can create "jagged" profiles that change drastically depending on the chosen row size.
The KDE Value Clouds approach is different because it uses a continuous probability function. Every price point in the lookback period contributes a small "bell curve" of influence to the total profile. This allows for a much smoother and more mathematically sound representation of where " Value " actually resides, regardless of arbitrary bin sizes.
The core of this indicator relies on two primary mathematical concepts:
Gaussian Kernel Estimation: Instead of simply counting occurrences, the script applies a Gaussian weight to every price point. This results in a "smooth" profile that captures the true shape of the price distribution.
Silverman’s Rule of Thumb: To prevent the clouds from being too noisy or too blurry, the indicator uses Silverman’s rule to calculate an optimal " Bandwidth ." This bandwidth adapts based on the standard deviation of the price data, ensuring the visualization stays relevant across different volatility regimes.
🔶 SETTINGS
🔹 Main Settings
Lookback Period: The number of bars used to calculate the price density. A higher lookback provides a "macro" view of value, while a lower lookback focuses on recent rotations.
Bandwidth Multiplier: Adjusts the "smoothness" of the KDE curve. Increasing this value will make the clouds broader and smoother; decreasing it will make them more granular.
Precision (Steps): Defines the vertical resolution of the density calculation. Higher values result in a more detailed profile.
🔹 Visualization
High/Low Density Colors: Customizes the gradient used for both the side profile and the on-chart clouds.
Profile Width (%): Controls how far the KDE profile extends horizontally across the right side of the chart.
Show Value Cloud on Chart: Toggles the visibility of the background "clouds" that highlight high-density price zones.
Indicator

Probability-Based Adaptive Detection🙏🏻 PBAD (Probability-Based Adaptive Detection) : adaptive control tool for outliers || novelty detection, made for worst case data & processes, for the highest time complexity O(n^2) compared with the alternatives (would be explained in a sec). Thresholds are completely data driven and axiomatic, no need in provided hyperparameters, are not learned or optimized. The method accepts multiple weights, e.g. both temporal and volatility weights.
Method briefly explained (I can go deeper if any1 asks explicitly):
Performs weighted KDE on initial input data, finds KDE global maximum (mode), creates new “residuals” dataset by centering initial data around this value;
Performs weighted KDE on residuals, uses sigmoid based probability mass targets with increasing probability coverage to construct a set of non-disjoint High Density Intervals (also called HDR, HPD in Bayesian terms);
Uses these intervals to calculate analogs of centralized & standardized moments;
Uses these ^^ moments to construct a set of control thresholds. The scheme used in PBAD is not only based on a central threshold, or on neighboring ones, it utilizes all previous thresholds, gaining more information.
...
The most important part is to understand whether you really need PBAD. Because even tho it seems to be the best one given highest algocomplexity, irl it would work worse in cases when it’s not required by your data.
Here’s the menu (aka taxonomy omg) of methods you can use that would let you make the right choice:
Moment-Based Adaptive Detection (MBAD) :
Norm: L2
Time complexity: original O(n), successfully reduced to O(1) in online version
Use case: default, general purpose
Based on: method of moments (powers of residuals from mean)
Thresholds architecture: centralized
Quantile-Based Adaptive Detection (QBAD):
Norm: L1
Time complexity: O(nlogn)
Use case: either bad data Or process instability
Based on: quantile moments (dyadic percentiles of residuals from median)
Thresholds architecture: chained/recursive/sequential
Probability-Based Adaptive Detection (PBAD):
Norm: L0
Time complexity: O(n^2)
Use case: both bad data And process instability
Based on: probability moments (target probability masses of residuals from KDE mode)
Thresholds architecture: decentralized (for lack of a better name xd, the idea is that these thresholds gain information from the all other threshold and are Not exclusively based on the central or neighboring thresholds)
...
Examples of true use cases:
^^ an appropriate financial instrument to use PBAD
^^ and another one
...
Additional details about how to use it:
Keep the student5 kernel, it’s the best you can do. I added others mostly for comparisons and if you want to use the tool Not for its primary purpose (on a fine data)
“Calculate for N bars” and “Starting at bar N” options allow to reduce calculation period only on the N number of last bars or next bars from a chosen one. It's vital, because calculations here are heavy
Keep plotting offset at 1 (allows to visually compare current bar with the previous threshold values). This is the way it should be done on price data.
HLC3 is the optimal source input, unless you want to use your own better one point estimate of each datapoint (in the best case done by using PBAD itself on OHLC+ values).
In essence it should be used just like MBAD or QBAD, fade/push extensions and limit, fade/push/skip deviations & basis, or other strategies of your. Again, the only reason for 3 methods to exist is to be chosen for according data characteristics.
Btw:
This is the initial version, I don’t consider it perfected tbh, even tho it works as expected, however this method is very situational anyways.
In this script KDE function is modified to ensure the outcoming probabilities Do sum up to 1. I didn’t do this normalization in Weighted KDE Mode script , but there it’s not required since we just need a KDE global max.
see ya
∞
Indicator

SuperTrend + Relative Volume (Kernel Optimized)Introducing our new KDE Optimized Supertrend + Relative Volume Indicator!
This innovative indicator combines the power of the Supertrend indicator along with Relative Volume. It utilizes the Kernel Density Estimation (KDE) to estimate the probability of a candlestick marking a significant trend break or reversal.
❓How to Interpret the KDE %:
The KDE % is a crucial metric that reflects the likelihood that the current candlestick represents a true break in the SuperTrend line, supported by an increase in relative volume. It estimates the probability of a trend shift or continuation based on historical SuperTrend breaks and volume patterns:
Low KDE %: A lower probability that the current break is significant. Price action is less likely to reverse, and the trend may continue.
Moderate KDE - High KDE %: An increased possibility that a trend reversal or consolidation could occur. Traders should start watching for confirmation signals.
📌How Does It Work?
The SuperTrend indicator uses the Average True Range (ATR) to determine the direction of the trend and identifies when the price crosses the SuperTrend line, signaling a potential trend reversal. Here's how the KDE Optimized SuperTrend Indicator works:
SuperTrend Calculation: The SuperTrend indicator is calculated, and when the price breaks above (bullish) or below (bearish) the SuperTrend line, it is logged as a significant event.
Relative Volume: For each break in the SuperTrend line, we calculate the relative volume (current volume vs. the average volume over a defined period). High relative volume can suggest stronger confirmation of the trend break.
KDE Array Calculation: KDE is applied to the break points and relative volume data:
Define the KDE options: Bandwidth, Number of Steps, and Array Range (Array Max - Array Min).
Create a density range array using the defined number of steps, corresponding to potential break points.
Apply a Gaussian kernel function to the break points and volume data to estimate the likelihood of the trend break being significant.
KDE Value and Signal Generation: The KDE array is updated as each break occurs. The KDE % is calculated for the breakout candlestick, representing the likelihood of the trend break being significant. If the KDE value exceeds the defined activation threshold, a darker bullish or bearish arrow is plotted after bar confirmation. If the KDE value falls below the threshold, a more transparent arrow is drawn, indicating a possible but lower probability break.
⚙️Settings:
SuperTrend Settings:
ATR Length: The period over which the Average True Range (ATR) is calculated.
Multiplier: The multiplier applied to the ATR to determine the SuperTrend threshold.
KDE Settings:
Bandwidth: Determines the smoothness of the KDE function and the width of the influence of each break point.
Number of Bins (Steps): Defines the precision of the KDE algorithm, with higher values offering more detailed calculations.
KDE Threshold %: The level at which relative volume is considered significant for confirming a break.
Relative Volume Length: The number of historic candles used in calculating KDE %
Indicator

RSI (Kernel Optimized) | Flux Charts💎 GENERAL OVERVIEW
Introducing our new KDE Optimized RSI Indicator! This indicator adds a new aspect to the well-known RSI indicator, with the help of the KDE (Kernel Density Estimation) algorithm, estimates the probability of a candlestick will be a pivot or not. For more information about the process, please check the "HOW DOES IT WORK ?" section.
Features of the new KDE Optimized RSI Indicator :
A New Approach To Pivot Detection
Customizable KDE Algorithm
Realtime RSI & KDE Dashboard
Alerts For Possible Pivots
Customizable Visuals
❓ HOW TO INTERPRET THE KDE %
The KDE % is a critical metric that reflects how closely the current RSI aligns with the KDE (Kernel Density Estimation) array. In simple terms, it represents the likelihood that the current candlestick is forming a pivot point based on historical data patterns. a low percentage suggests a lower probability of the current candlestick being a pivot point. In these cases, price action is less likely to reverse, and existing trends may continue. At moderate levels, the possibility of a pivot increases, indicating potential trend shifts or consolidations.Traders should start monitoring closely for confirmation signals. An even higher KDE % suggests a strong likelihood that the current candlestick could form a pivot point, which could lead to a reversal or significant price movement. These points often align with overbought or oversold conditions in traditional RSI analysis, making them key moments for potential trade entry or exit.
📌 HOW DOES IT WORK ?
The RSI (Relative Strength Index) is a widely used oscillator among traders. It outputs a value between 0 - 100 and gives a glimpse about the current momentum of the price action. This indicator then calculates the RSI for each candlesticks, and saves them into an array if the candlestick is a pivot. The low & high pivot RSIs' are inserted into two different arrays. Then the a KDE array is calculated for both of the low & high pivot RSI arrays. Explaining the KDE might be too much for this write-up, but for a brief explanation, here are the steps :
1. Define the necessary options for the KDE function. These are : Bandwidth & Nº Steps, Array Range (Array Max - Array Min)
2. After that, create a density range array. The array has (steps * 2 - 1) elements and they are calculated by (arrMin + i * stepCount), i being the index.
3. Then, define a kernel function. This indicator has 3 different kernel distribution modes : Uniform, Gaussian and Sigmoid
4. Then, define a temporary value for the current element of KDE array.
5. For each element E in the pivot RSI array, add "kernel(densityRange.get(i) - E, 1.0 / bandwidth)" to the temporary value.
6. Add 1.0 / arrSize * to the KDE array.
Then the prefix sum array of the KDE array is calculated. For each candlestick, the index closest to it's RSI value in the KDE array is found using binary search. Then for the low pivot KDE calculation, the sum of KDE values from found index to max index is calculated. For the high pivot KDE, the sum of 0 to found index is used. Then if high or low KDE value is greater than the activation threshold determined in the settings, a bearish or bullish arrow is plotted after bar confirmation respectively. The arrows are drawn as long as the KDE value of current candlestick is greater than the threshold. When the KDE value is out of the threshold, a less transparent arrow is drawn, indicating a possible pivot point.
🚩 UNIQUENESS
This indicator combines RSI & KDE Algorithm to get a foresight of possible pivot points. Pivot points are important entry, confirmation and exit points for traders. But to their nature, they can be only detected after more candlesticks are rendered after them. The purpose of this indicator is to alert the traders of possible pivot points using KDE algorithm right away when they are confirmed. The indicator also has a dashboard for realtime view of the current RSI & Bullish or Bearish KDE value. You can fully customize the KDE algorithm and set up alerts for pivot detection.
⚙️ SETTINGS
1. RSI Settings
RSI Length -> The amount of bars taken into account for RSI calculation.
Source -> The source value for RSI calculation.
2. Pivots
Pivot Lengths -> Pivot lengths for both high & low pivots. For example, if this value is set to 21; 21 bars before AND 21 bars after a candlestick must be higher for a candlestick to be a low pivot.
3. KDE
Activation Threshold -> This setting determines the amount of arrows shown. Higher options will result in more arrows being rendered.
Kernel -> The kernel function as explained in the upper section.
Bandwidth -> The bandwidth variable as explained in the upper section. The smoothness of the KDE function is tied to this setting.
Nº Bins -> The Nº Steps variable as explained in the upper section. It determines the precision of the KDE algorithm. Indicator

MathStatisticsKernelDensityEstimationLibrary "MathStatisticsKernelDensityEstimation"
(KDE) Method for Kernel Density Estimation
kde(observations, kernel, bandwidth, nsteps)
Parameters:
observations : float array, sample data.
kernel : string, the kernel to use, default='gaussian', options='uniform', 'triangle', 'epanechnikov', 'quartic', 'triweight', 'gaussian', 'cosine', 'logistic', 'sigmoid'.
bandwidth : float, bandwidth to use in kernel, default=0.5, range=(0, +inf), less will smooth the data.
nsteps : int, number of steps in range of distribution, default=20, this value is connected to how many line objects you can display per script.
Returns: tuple with signature: (float array, float array)
draw_horizontal(distribution_x, distribution_y, distribution_lines, graph_lines, graph_labels) Draw a horizontal distribution at current location on chart.
Parameters:
distribution_x : float array, distribution points x value.
distribution_y : float array, distribution points y value.
distribution_lines : line array, array to append the distribution curve lines.
graph_lines : line array, array to append the graph lines.
graph_labels : label array, array to append the graph labels.
Returns: void, updates arrays: distribution_lines, graph_lines, graph_labels.
draw_vertical(distribution_x, distribution_y, distribution_lines, graph_lines, graph_labels) Draw a vertical distribution at current location on chart.
Parameters:
distribution_x : float array, distribution points x value.
distribution_y : float array, distribution points y value.
distribution_lines : line array, array to append the distribution curve lines.
graph_lines : line array, array to append the graph lines.
graph_labels : label array, array to append the graph labels.
Returns: void, updates arrays: distribution_lines, graph_lines, graph_labels.
style_distribution(lines, horizontal, to_histogram, line_color, line_style, linewidth) Style the distribution lines.
Parameters:
lines : line array, distribution lines to style.
horizontal : bool, default=true, if the display is horizontal(true) or vertical(false).
to_histogram : bool, default=false, if graph style should be switched to histogram.
line_color : color, default=na, if defined will change the color of the lines.
line_style : string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both)
linewidth : int, default=na, if defined will change the line width.
Returns: void.
style_graph(lines, lines, horizontal, line_color, line_style, linewidth) Style the graph lines and labels
Parameters:
lines : line array, graph lines to style.
lines : labels array, graph labels to style.
horizontal : bool, default=true, if the display is horizontal(true) or vertical(false).
line_color : color, default=na, if defined will change the color of the lines.
line_style : string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both)
linewidth : int, default=na, if defined will change the line width.
Returns: void. Library

Indicator

Indicator

Indicator
