Quant Reversal Index [AlgoPoint]Overview
The AlgoPoint Quant Reversal Index is a normalized (0-100) oscillator designed to measure mean-reverting tendencies in financial time series. By combining the Hurst Exponent, an Autoregressive AR(1) Half-Life model, and Ornstein-Uhlenbeck (OU) boundaries, this indicator evaluates whether an asset is in a trending or ranging regime and calculates its proportional deviation from a dynamic historical mean.
Mathematical Core & Components
This indicator relies on three primary quantitative concepts:
1. Hurst Exponent ( H ) : Approximated using the log variance ratio of price differences over distinct time lags. It determines the current market regime:
- H < 0.5: Indicates a Mean Reverting (ranging) regime.
- H > 0.5: Indicates a Trending (momentum) regime.
2. AR(1) Half-Life : Calculates the estimated time (in bars) it takes for the price to revert to its mean. This is derived from the linear regression slope (covariance/variance) of price changes against previous prices. This dynamic half-life dictates the lookback length for the oscillator's mean and standard deviation.
3. Ornstein-Uhlenbeck (OU) Conversion : Calculates the mean ($\mu$) and standard deviation ($\sigma$) over the dynamic half-life period to establish upper and lower OU boundaries. The current price is then normalized into a 0 to 100 index based on its position relative to these boundaries.
Visual Elements & Interpretation
- The 0-100 Scale : * A value of 50 represents the dynamic mean ($\mu$).
- A value of 0 represents the Lower OU boundary (Standard Deviation limit).
- A value of 100 represents the Upper OU boundary.
- Values extending beyond 0 or 100 highlight statistical extremes.
- Dynamic Regime Background : When the Hurst Exponent is strictly below the user-defined threshold (default 0.5), the oscillator's background is highlighted. This visually confirms that the asset exhibits stationary, mean-reverting properties. If the background is not highlighted, the asset is considered to be trending, and mean-reversion logic is disabled.
- Signal Generation : The indicator plots "Buy" and "Sell" labels strictly when the market is in a confirmed mean-reverting regime ($H < 0.5$) AND the oscillator crosses back into the 0-100 range from an extreme (e.g., crossing above 0 or crossing below 100). All signals use barstate.isconfirmed to prevent repainting.
- Quant Dashboard : Displays real-time data for the current market regime, exact Hurst Exponent value, and the estimated Half-Life in bars.
How to Use
- Wait for the background to highlight, confirming a mean-reverting regime.
- Monitor the index as it reaches extreme values (< 0 or > 100).
- A statistical reversion is indicated when the index crosses back inside the core 0-100 range.
- Signals should be combined with broader macro analysis and strict risk management protocols.
Alerts
The indicator includes standard alert conditions and dynamic JSON webhook strings for automated trading systems, providing variables such as asset name, price, hurst value, and half-life duration on signal generation. Indicator

Liquidity Structure & Order Flow [UAlgo]Liquidity Structure & Order Flow is a range based market participation tool that combines a custom volume profile, value area analysis, liquidity void detection, and unusual volume tagging into a single chart overlay. Its goal is to show not only where volume has concentrated across price, but also how that activity was distributed between estimated buying pressure and selling pressure inside the recent market structure.
The script begins by scanning a rolling lookback range, then divides that vertical price space into a configurable number of bins. Each bin becomes a price segment that stores estimated buy volume, sell volume, and total volume. From there, the script builds a profile that highlights the Point of Control, the value area, and the internal order flow balance across the studied range.
What makes this indicator especially useful is that it does more than draw a standard profile. It also identifies areas where participation is abnormally thin relative to both the Point of Control and local neighboring bins. These low participation areas are marked as liquidity voids, helping the user see where the market moved through price with relatively little acceptance.
In addition, the script monitors the current bar for unusually large activity using a volume z score and a directional delta ratio filter. When a bar shows both exceptional size and meaningful directional imbalance, the script prints a bubble style marker above or below price. This gives the user a way to spot unusual participation events as they happen.
The result is a tool that can be used for profile analysis, liquidity mapping, imbalance recognition, and structural context. It helps answer several practical questions at once: where the market accepted price, where it rejected or skipped through price, where the strongest concentration of activity formed, and whether recent candles are showing exceptional directional participation.
🔹 Features
🔸 Custom Range Based Volume Profile
The script constructs a manual volume profile over the selected lookback period. Instead of relying on a built in profile engine, it divides the recent range into user defined price bins and allocates each bar’s volume into those bins. This gives full control over how the profile is built and how the final distribution is interpreted.
🔸 Buy Volume and Sell Volume Estimation
Every candle contributes both buy side and sell side estimates. The script uses the candle’s open, high, low, and close to derive a buy volume ratio, then splits total volume into buy volume and sell volume accordingly. This creates a practical order flow style approximation that is more informative than total volume alone.
🔸 Proportional Price Overlap Allocation
When a candle spans multiple bins, the script distributes its buy volume, sell volume, and total volume proportionally according to how much of the candle overlaps each bin. This produces a more realistic internal structure than simply dropping the full bar volume into one price row.
🔸 Point of Control Detection
The indicator finds the bin with the highest total volume and marks it as the Point of Control. This gives the user an immediate view of the strongest participation price inside the studied range.
🔸 Value Area Calculation
After the Point of Control is found, the script expands upward and downward through neighboring bins until the selected percentage of total profile volume is captured. This defines Value Area High and Value Area Low, allowing the user to distinguish the central acceptance region from the rest of the range.
🔸 Profile Coloring by Participation Side
The profile is drawn as stacked horizontal boxes showing estimated buy side participation and sell side participation inside each row. Bins inside the value area use stronger coloring, while bins outside the value area use softer coloring. This makes the internal structure easy to read visually.
🔸 Liquidity Void Detection
The script scans for bins with unusually weak participation outside the value area. A bin qualifies as a liquidity void candidate only if it is both small relative to the Point of Control and also weaker than its nearby neighbors. Consecutive weak bins are grouped into a larger void zone and labeled directly on the chart.
🔸 Unusual Volume Bubble Markers
Current bar activity is evaluated using a long period volume average and standard deviation. If the bar’s volume is statistically unusual and its estimated delta ratio is large enough, the script prints a directional bubble marker. Positive directional activity is shown below price, and negative directional activity is shown above price.
🔸 Optional Profile and Void Display
The user can independently control whether the volume profile, liquidity voids, and unusual volume markers are shown. This makes the script flexible enough for both full structure analysis and lighter chart layouts.
🔸 Extendable Structural Levels
The Point of Control, Value Area High, and Value Area Low can be drawn as either compact structure references or extended lines, depending on the chosen setting. This allows the user to decide whether the levels should function as local annotations or ongoing chart references.
🔸 Useful for Acceptance and Imbalance Analysis
The combination of profile structure, value area, void zones, and unusual activity markers gives the indicator a broader purpose than a standard profile. It can help identify accepted price, skipped price, directional participation, and possible future reaction areas.
🔹 Calculations
1) Building the Volume Profile Container
type PriceBin
float price
float buyVol = 0.0
float sellVol = 0.0
float totalVol = 0.0
type VolumeProfile
float highPrice = na
float lowPrice = na
float binSize = na
array bins
float pocPrice = na
float pocVol = 0.0
float vah = na
float val = na
float totalVol = 0.0
This is the foundation of the whole script.
Each PriceBin stores one price level area inside the profile. It contains:
the row midpoint price,
estimated buy volume,
estimated sell volume,
and total volume.
The VolumeProfile structure stores the full profile state:
the highest price of the lookback range,
the lowest price of the lookback range,
the bin size,
the array of bins,
and the final analytical values such as Point of Control, Value Area High, Value Area Low, and total profile volume.
So before any analysis happens, the script defines a complete custom data model for price distribution and order flow style estimation.
2) Initializing the Bins Across the Lookback Range
method initBins(VolumeProfile this, float h, float l, int numBins) =>
this.highPrice := h
this.lowPrice := l
this.binSize := (h - l) / numBins
this.pocPrice := na
this.pocVol := 0.0
this.totalVol := 0.0
this.vah := na
this.val := na
this.bins := array.new()
for i = 0 to numBins - 1
this.bins.push(PriceBin.new(price = l + i * this.binSize + (this.binSize / 2)))
This method creates the working profile rows.
First, it stores the high and low of the selected lookback period. Then it calculates binSize , which is the vertical price height of each row. That is simply the full range height divided by the number of bins.
After resetting all major profile outputs, the script creates a fresh bin array. Each new bin is assigned a midpoint price:
l + i * this.binSize + (this.binSize / 2)
That midpoint becomes the visual and analytical center of the row.
In practical terms, this is where the script transforms the raw market range into a structured ladder of price rows that can later receive allocated volume.
3) Locating the Correct Bin for a Price
method getBinIndex(VolumeProfile this, float p) =>
if na(this.lowPrice) or na(this.binSize) or this.binSize == 0
0
else
int idx = math.floor((p - this.lowPrice) / this.binSize)
math.max(0, math.min(idx, this.bins.size() - 1))
This helper method maps any price to its correct row index inside the profile.
It works by measuring how far the price sits above the profile low, then dividing that distance by the bin size. The result is the raw row index. After that, the value is clamped so it always stays inside the valid bin range.
This is important because the script repeatedly needs to know which rows are touched by each candle’s low and high. Without this mapping step, the profile could not distribute volume across price space correctly.
4) Estimating Buy Volume and Sell Volume From Candle Structure
float hlR = high - low
float bVR = hlR == 0 ? 0.5 : (close - low + high - open) / (2 * hlR)
float currentBuyVol = volume * bVR
float currentSellVol = volume * (1 - bVR)
float delta = currentBuyVol - currentSellVol
This snippet explains how the script approximates order flow direction on the current bar.
First, it measures the candle range from high to low. Then it computes a buy volume ratio using the relative location of the open and close inside that range:
(close - low + high - open) / (2 * hlR)
This ratio becomes a practical estimate of how much of the bar’s total volume behaved like buying pressure versus selling pressure. If the candle closes stronger and opens higher inside its range, the ratio leans more bullish. If the candle structure is weaker, the ratio leans more bearish.
That ratio is then used to split total volume into:
currentBuyVol
and
currentSellVol
Finally, the script calculates delta as the difference between estimated buy volume and estimated sell volume.
This is not true transaction tagged exchange delta, but it is a useful chart based directional participation model.
5) Distributing Candle Volume Across Touched Price Rows
method addBarVolume(VolumeProfile this, float h, float l, float c, float o, float v) =>
float hlRange = h - l
float buyVolRatio = hlRange == 0 ? 0.5 : (c - l + h - o) / (2 * hlRange)
float buyV = v * buyVolRatio
float sellV = v * (1 - buyVolRatio)
int startIdx = this.getBinIndex(l)
int endIdx = this.getBinIndex(h)
for i = startIdx to endIdx
if i >= 0 and i < this.bins.size()
PriceBin b = this.bins.get(i)
float binTop = b.price + (this.binSize / 2)
float binBot = b.price - (this.binSize / 2)
float overlapTop = math.min(h, binTop)
float overlapBot = math.max(l, binBot)
float overlap = math.max(0.0, overlapTop - overlapBot)
float weight = hlRange > 0 ? overlap / hlRange : (1.0 / (endIdx - startIdx + 1))
b.buyVol += buyV * weight
b.sellVol += sellV * weight
b.totalVol += v * weight
this.bins.set(i, b)
this.totalVol += v * weight
This is one of the most important calculations in the entire script.
For each candle inside the lookback period, the script first computes estimated buy volume and sell volume. Then it finds which profile rows are touched by the candle’s low and high.
For every touched row, it measures how much of the candle overlaps that specific row. That overlap becomes a weighting factor:
weight = overlap / hlRange
If a candle overlaps a row heavily, that row receives a larger share of the bar’s volume. If the overlap is small, the row receives only a small share.
The script then adds weighted buy volume, weighted sell volume, and weighted total volume into that bin.
This is much more realistic than assigning all volume to a single row because it respects the actual price space the candle traveled through.
6) Determining the Point of Control
method calcValueArea(VolumeProfile this, float pct) =>
float midPrice = (this.highPrice + this.lowPrice) / 2
float maxVol = -1.0
float bestPrice = na
int pocIdx = -1
for i = 0 to this.bins.size() - 1
PriceBin b = this.bins.get(i)
if b.totalVol > maxVol
maxVol := b.totalVol
bestPrice := b.price
pocIdx := i
else if b.totalVol == maxVol and maxVol > 0
if math.abs(b.price - midPrice) < math.abs(bestPrice - midPrice)
bestPrice := b.price
pocIdx := i
this.pocVol := maxVol
this.pocPrice := bestPrice
This is the first phase of the value area calculation.
The script scans all bins and finds the row with the greatest total volume. That row becomes the Point of Control. If two rows have the same maximum volume, the script breaks the tie by choosing the one closer to the middle of the full lookback range.
That tie handling matters because it avoids unstable selection when multiple bins have identical strength.
After the winning row is found, the script stores:
the Point of Control volume in pocVol
and the Point of Control price in pocPrice
So the Point of Control is not simply a visual midpoint. It is the actual strongest participation row in the profile.
7) Expanding Upward and Downward to Build the Value Area
float targetVol = this.totalVol * pct / 100.0
float currentVol = 0.0
if pocIdx >= 0 and pocIdx < this.bins.size()
currentVol := this.bins.get(pocIdx).totalVol
int upIdx = pocIdx + 1
int dnIdx = pocIdx - 1
while currentVol < targetVol and (upIdx < this.bins.size() or dnIdx >= 0)
float upVol = upIdx < this.bins.size() ? this.bins.get(upIdx).totalVol : -1.0
float dnVol = dnIdx >= 0 ? this.bins.get(dnIdx).totalVol : -1.0
After finding the Point of Control, the script calculates the target volume required for the value area. For example, if the input is 70 percent, the target becomes 70 percent of total profile volume.
The expansion begins from the Point of Control row itself. currentVol starts with the Point of Control row’s own total volume. Then the script looks one row up and one row down, repeatedly expanding until the accumulated volume reaches the target.
This is the standard logic of building a value area around the strongest participation center.
8) Deciding Whether to Expand Up or Down
if upVol > dnVol and upVol != -1.0
currentVol += upVol
upIdx += 1
else if dnVol > upVol and dnVol != -1.0
currentVol += dnVol
dnIdx -= 1
else if upVol == dnVol and upVol != -1.0
if currentVol + upVol > targetVol
if math.abs(this.bins.get(upIdx).price - midPrice) < math.abs(this.bins.get(dnIdx).price - midPrice)
currentVol += upVol
upIdx += 1
else
currentVol += dnVol
dnIdx -= 1
else
currentVol += upVol + dnVol
upIdx += 1
dnIdx -= 1
This block decides which side to include next in the value area.
If the row above has more volume than the row below, the script expands upward. If the row below has more volume, it expands downward. If both sides are equal, it uses distance to the overall midpoint as a tie breaker when necessary.
This is important because value area growth should follow participation strength, not arbitrary direction. The final result is a value area that naturally wraps around the highest volume concentration.
9) Final VAH and VAL Assignment
int finalUpIdx = math.max(pocIdx, upIdx - 1)
int finalDnIdx = math.min(pocIdx, dnIdx + 1)
this.vah := finalUpIdx < this.bins.size() ? this.bins.get(finalUpIdx).price : this.highPrice
this.val := finalDnIdx >= 0 ? this.bins.get(finalDnIdx).price : this.lowPrice
Once expansion is complete, the script converts the final included rows into value area boundaries.
The highest included row becomes Value Area High.
The lowest included row becomes Value Area Low.
These values define the central price zone where the chosen percentage of the profile’s total volume was traded.
So VAH and VAL are directly derived from the row by row structure of the profile, not from any fixed percentage of price range.
10) Detecting Unusual Volume Activity
float volSma = ta.sma(volume, 200)
float volStdev = ta.stdev(volume, 200)
float zScore = volStdev == 0 ? 0 : (volume - volSma) / volStdev
float deltaRatio = volume > 0 ? math.abs(delta) / volume : 0
bool isUnusual = zScore > zScoreThreshold and deltaRatio >= deltaRatioThreshold
This block evaluates whether the current bar is unusually active.
First, the script computes a 200 period average volume and standard deviation. Then it transforms the current bar’s volume into a z score, which shows how many standard deviations the bar stands above normal background activity.
Next, it calculates deltaRatio , which measures how large the directional imbalance is relative to total volume.
A bar is marked unusual only if both conditions are true:
the volume is statistically large enough,
and the directional imbalance is meaningful enough.
This double filter helps reduce false signals from large but directionless bars.
11) Printing Unusual Volume Bubbles
if showUnusual and isUnusual
string lblText = (delta > 0 ? "🟢 " : "🔴 ") + str.tostring(math.round(volume))
color lblColor = delta > 0 ? color.new(color.green, 0) : color.new(color.red, 0)
label uLbl = label.new(bar_index, delta > 0 ? low : high, text=lblText, style=label.style_none, textcolor=lblColor, yloc=delta > 0 ? yloc.belowbar : yloc.abovebar, size=size.small)
When an unusual bar is detected, the script prints a directional marker.
If estimated delta is positive, the bubble is shown below price in green.
If estimated delta is negative, the bubble is shown above price in red.
The displayed text also includes the rounded volume value. This allows the user to quickly see both direction and size of the unusual participation event.
So these markers are not random momentum tags. They specifically highlight bars where both participation size and directional imbalance stand out.
12) Rebuilding the Profile on the Last Bar
float highestPrice = ta.highest(high, lookback)
float lowestPrice = ta.lowest(low, lookback)
if barstate.islast and bar_index >= lookback - 1
profile.initBins(highestPrice, lowestPrice, rows)
for i = 0 to lookback - 1
profile.addBarVolume(high , low , close , open , volume )
profile.calcValueArea(vaPct)
This is the main execution block for the profile.
First, the script finds the highest high and lowest low across the chosen lookback window. That defines the total vertical space of the analysis.
Then, on the last visible bar, it:
initializes the bins,
loops through every candle inside the lookback,
adds each candle’s weighted volume into the profile,
and finally calculates the value area.
Running this only on the last bar is efficient because the full profile is a visual structure based on the current lookback window. It does not need to be redrawn historically on every past bar.
13) Scaling and Drawing the Profile Histogram
float maxVol = profile.pocVol
float allVols = array.new_float()
for i = 0 to profile.bins.size() - 1
allVols.push(profile.bins.get(i).totalVol)
float avgVol = allVols.avg()
float stdVol = allVols.stdev()
float clampedMaxVol = math.max(math.min(maxVol, avgVol + (stdVol * 2)), 0.000001)
Before drawing the profile, the script prepares a safer scaling reference.
Instead of using raw Point of Control volume alone without adjustment, it clamps the maximum drawable scale using the average row volume plus two standard deviations. This helps prevent a single extreme row from making the rest of the profile look too compressed.
In practical terms, this means the visual histogram remains readable even when one row is exceptionally dominant.
14) Drawing Buy Side and Sell Side Inside Each Row
int buyLen = math.round((b.buyVol / b.totalVol) * (drawVol / clampedMaxVol) * profileWidth)
int sellLen = math.round((b.sellVol / b.totalVol) * (drawVol / clampedMaxVol) * profileWidth)
bool inVA = b.price <= profile.vah and b.price >= profile.val
bool isPocRow = math.abs(b.price - profile.pocPrice) <= profile.binSize * 0.5
int x1 = profileRight
int x2 = x1 - buyLen
if buyLen > 0
box bB = box.new(x1, topP, x2, botP, border_color=c_border, bgcolor=c_buy)
int x3 = x2
int x4 = x3 - sellLen
if sellLen > 0
box bS = box.new(x3, topP, x4, botP, border_color=c_border, bgcolor=c_sell)
This is the actual profile drawing logic.
For each row, the script determines how much of the row’s total activity came from estimated buy volume and how much came from estimated sell volume. It then converts those fractions into horizontal lengths.
The buy portion is drawn first, then the sell portion continues from the end of the buy section. This creates a stacked horizontal bar that reveals both total participation and internal directional composition.
The row also receives context coloring:
rows inside the value area use stronger color treatment,
and the Point of Control row can receive a distinct border.
So the histogram communicates three layers at once:
how much volume was traded there,
whether that row sits inside the value area,
and how that row’s activity was split between estimated buying and selling pressure.
15) Drawing POC, VAH, and VAL Lines
line pocL = line.new(lineStartX, profile.pocPrice, lineEndX, profile.pocPrice, color=col_poc, width=2, style=line.style_solid)
profileLines.push(pocL)
line vahL = line.new(lineStartX, profile.vah, lineEndX, profile.vah, color=col_vah, width=1, style=line.style_dashed)
profileLines.push(vahL)
line valL = line.new(lineStartX, profile.val, lineEndX, profile.val, color=col_val, width=1, style=line.style_dashed)
profileLines.push(valL)
Once the profile is built, the script draws the three most important structural references:
Point of Control,
Value Area High,
and Value Area Low.
These lines can behave as compact annotations near the profile or as broader structure references if extension is enabled.
This gives the user a quick way to read acceptance and central balance without needing to inspect every row manually.
16) Detecting Liquidity Voids
float voidLimit = profile.pocVol * (voidThreshold / 100.0)
bool inVoid = false
float voidStartPrice = na
for i = 0 to profile.bins.size() - 1
PriceBin b = profile.bins.get(i)
bool isOutsideVA = b.price > profile.vah or b.price < profile.val
This is the beginning of the liquidity void logic.
A row is never treated as a void candidate solely because its volume is small. The script first requires that the row be outside the value area. This matters because low volume inside the main acceptance zone does not carry the same meaning as low volume outside it.
The script also calculates voidLimit as a percentage of Point of Control volume. That creates a relative participation threshold tied to the strongest row in the profile.
17) Comparing Each Row to Its Neighbors
float sumNeighbors = 0.0
int nC = 0
for j = math.max(0, i - 2) to math.min(profile.bins.size() - 1, i + 2)
if j != i
sumNeighbors += profile.bins.get(j).totalVol
nC += 1
float localAvg = nC > 0 ? sumNeighbors / nC : 0.0
bool isGap = b.totalVol < (localAvg * 0.5)
bool isLowVol = b.totalVol < voidLimit
bool isVoid = isLowVol and isGap and isOutsideVA
This is the real filter that defines a liquidity void.
The script looks at nearby bins around the current row and calculates a local neighbor average. Then it applies two separate tests:
the row must be low relative to the Point of Control threshold,
and it must also be weak relative to its nearby neighbors.
Only if both are true, and the row is outside the value area, does the script classify it as a void.
This is important because it prevents the indicator from marking every low volume row as a void. A valid void must look weak both globally and locally.
18) Grouping Consecutive Void Rows Into Zones
if isVoid
if not inVoid
inVoid := true
voidStartPrice := b.price - (profile.binSize / 2)
else
if inVoid
inVoid := false
float voidEndPrice = b.price - (profile.binSize / 2)
float topCoord = math.max(voidStartPrice, voidEndPrice)
float botCoord = math.min(voidStartPrice, voidEndPrice)
box vBox = box.new(bar_index - lookback, topCoord, bar_index, botCoord, border_color=na, bgcolor=col_void)
Once a void row is detected, the script begins tracking a continuous void run. If the next row is also a void, the zone continues. When the run ends, the script closes the zone and draws a box covering the full void area.
This means the indicator does not plot isolated tiny marks for each row. Instead, it groups neighboring weak rows into a cleaner structure that better represents a meaningful liquidity gap.
That box is then labeled as a liquidity void, making the zone easy to identify visually. Indicator

Master Portfolio Lab PRO [The Quant Science]The Master Portfolio Lab PRO is an advanced quantitative analysis terminal designed to transform PulseWire into a powerful multi-asset portfolio management engine. Developed with institutional-grade calculation logic, this tool allows you to simulate, monitor, and analyze the combined performance of 12 customizable assets within a single, dynamic environment.
In a world where trading is often hyper-focused on a single ticker, the Master Lab enables you to level up: stop looking at the tree and start managing the forest.
🧪 USAGE
The script is designed for traders and investors looking to validate asset allocation strategies or monitor their real-market exposure against a specific benchmark.
🧬 How to configure it:
Asset Allocation: Enter your desired tickers (Crypto, Stocks, Forex, or Commodities) and assign a percentage weight to each slot. Ensure the total weight equals 100%.
Capital Configuration: Choose from predefined capital profiles (from $1k to $1M) or set a custom capital amount for precise simulations.
Costs & Fees: Set a "Portfolio Fee" to reflect transaction costs and generate a realistic, non-theoretical equity curve.
Benchmark Comparison: Select a reference index (e.g., S&P 500 or Bitcoin) to measure the Alpha generated by your active management.
🧪 DETAILS
🧬 Multi-Mode Analysis Engine
The script offers four independent visualization modes, instantly switchable via the settings menu:
Cumulative (%): Comparative analysis between the portfolio's percentage return and the benchmark.
Equity ($): Monetary monitoring of net liquidity and cash growth.
SMA Ribbon: Identification of the portfolio's trend regime using moving averages applied directly to the equity curve.
Volatility: Real-time monitoring of portfolio "thermal stress" via smoothed Standard Deviation (WMA).
🧬 Alpha-Glow Logic
The system utilizes a high-fidelity visual architecture based on dynamic gradients. When the portfolio outperforms the benchmark (Positive Alpha), the fill area illuminates, providing immediate psychological feedback on the quality of your management.
🧬 Real-Time Dashboard
An integrated table in the bottom-right corner processes live data to provide:
Net Value: Current portfolio value, including PnL and costs.
Return %: Total return from the selected starting anchor point.
Alpha vs Index: The "holy grail" of trading—exactly how much value you are adding compared to a passive investment.
🧪 SETTINGS
🧬 Capital Configuration
1) Fixed Capital: Toggle quick selectors for standard account sizes.
2) Custom Capital: Manual input for simulating specific real-world accounts.
🧬 Date Period Analysis
Allows you to set a precise start date (Day/Month/Year) to analyze portfolio performance during specific macroeconomic events or historical cycles.
The Master Portfolio Lab PRO was born from the need to overcome PulseWire's native limitations in multi-symbol management. By utilizing normalization techniques and iterative Rate of Change (ROC) calculations, we have created a framework capable of simulating an entire investment fund with surgical precision. 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

Quantum Relative Performance Oscillator [Pineify]Quantum Relative Performance Oscillator
A sophisticated relative strength indicator that normalizes performance metrics to identify true momentum shifts between an asset and its benchmark.
The Quantum Relative Performance Oscillator (RPO) is an advanced technical indicator designed to measure and visualize how a specific asset performs relative to a benchmark index. Unlike traditional relative strength indicators that can drift over time, this indicator normalizes the RS ratio to center around zero, providing traders with a clearer, more accurate picture of momentum shifts.
The Quantum RPO addresses a fundamental limitation in traditional relative strength analysis. While standard RS indicators show whether an asset is outperforming or underperforming a benchmark, they don't easily reveal when that outperformance is accelerating or decelerating. This indicator solves that problem by normalizing the relative strength ratio and applying weighted moving average smoothing to create clear, actionable trading signals.
Key Features
Normalized RS Calculation: Centers the relative strength ratio around zero, eliminating long-term drift and making it easier to identify current momentum trends
Weighted Moving Average (WMA) Processing: Uses WMA instead of simple moving averages for more responsive calculations that give greater weight to recent price action
Dynamic Color Histogram: Visual representation of momentum acceleration and deceleration with intelligent color coding
Crossover Signals: Clear bullish and bearish momentum shift indicators when the RS Ratio crosses above or below the signal line
Customizable Benchmark: Compare any asset against a user-selected benchmark symbol (default: SPY)
Adjustable Parameters: Configurable lookback length and signal smoothing for different timeframes and trading styles
Built-in Alerts: Automated notifications for momentum shift events
How It Works
The indicator fetches closing prices for both the current asset and the user-defined benchmark symbol
It calculates the raw Relative Strength (RS) by dividing the asset's close price by the benchmark's close price
A Weighted Moving Average (WMA) is applied to the RS to establish a baseline equilibrium level
The RS Ratio is calculated as: (RS / WMA) * 100 - 100, which normalizes the value around zero
A Signal Line is created by applying additional WMA smoothing to the RS Ratio
The histogram (Performance Delta) shows the difference between the RS Ratio and Signal Line, indicating momentum strength
Trading Ideas and Insights
Momentum Confirmation: Use the RS Ratio crossing above zero as confirmation that an asset is gaining relative strength against its benchmark
Trend Reversal Signals: Watch for bullish crossovers (RS Ratio crossing above Signal Line) to identify potential trend reversals
Relative Strength Screening: Compare multiple assets using the same benchmark to identify the strongest performers in a sector
Divergence Detection: Look for situations where price makes new highs but the RS Ratio fails to confirm, indicating weakening relative momentum
Sector Rotation: Use different benchmarks (sector ETFs) to identify rotation between sectors
How Multiple Indicators Work Together
This indicator combines three separate but complementary calculations to create a comprehensive relative strength tool:
The raw RS calculation provides the fundamental comparison between asset and benchmark performance
The WMA normalization removes drift and creates a centered oscillator that oscillates around zero
The signal line smoothing filters out noise and provides clear crossover points for trading signals
The histogram visualization combines both elements to show the magnitude and direction of momentum in one clear display
Unique Aspects
Unlike traditional RS indicators that can drift indefinitely higher or lower over time, the Quantum RPO's normalized calculation ensures the oscillator remains centered, making it easier to identify overbought and oversold conditions in relative terms
The dynamic color histogram provides intuitive visual feedback about whether momentum is accelerating or decelerating, helping traders avoid false signals
The use of Weighted Moving Averages rather than simple moving averages provides more responsive calculations that adapt faster to changing market conditions
The built-in alert system allows traders to receive notifications automatically when momentum shifts occur, without needing to constantly monitor the chart
How to Use
Apply the indicator to any asset's chart
Select your preferred benchmark symbol in the settings (SPY for US stocks, BTCUSD for crypto, etc.)
Interpret the RS Ratio: Positive values indicate outperformance, negative values indicate underperformance
Use the Signal Line crossovers for entry signals: Buy when RS Ratio crosses above Signal Line, Sell when it crosses below
Monitor the histogram for momentum confirmation: Green columns rising indicate strengthening bullish momentum, red columns falling indicate strengthening bearish momentum
Set up alerts for bullish and bearish momentum shifts to receive notifications
Customization
Benchmark Symbol: Change the comparison asset (SPY, QQQ, BTCUSD, etc.)
Lookback Length: Adjust the period for WMA calculations (default: 20). Higher values produce smoother results with more lag; lower values are more responsive but may generate more false signals
Signal Length: Modify the smoothing period for the signal line (default: 9)
Color Customization: Customize the bullish (outperforming) and bearish (underperforming) colors to match your preferences
These parameters can be adjusted to suit different trading timeframes, from intraday scalping to long-term position trading
The Quantum Relative Performance Oscillator is a powerful tool for traders who want to understand not just whether an asset is outperforming its benchmark, but whether that outperformance is accelerating or losing steam. By normalizing the relative strength calculation and providing clear visual and alert-based signals, it helps traders make more informed decisions about entries, exits, and asset allocation across different markets and timeframes.
Indicator

Hidden Markov Model: Regime Probability [AlgoPoint]Hidden Markov Model: Regime Probability
Traditional technical indicators are deterministic and lagging; they tell you what the price has already done. The Hidden Markov Model (HMM) Regime Probability system takes a completely different, quantitative approach. It uses probabilistic mathematics to estimate the unobservable "Hidden State" (Market Regime) the price is currently operating in.
Inspired by the mathematical models used by institutional quantitative hedge funds, this script doesn't just look at price direction—it calculates the probability of the market being in a specific regime based on real-time observations of Momentum and Volatility.
1. The Three Hidden States (Regimes)
The market is modeled as existing in one of three hidden states:
↗ Bullish Regime: High positive momentum with low or stable volatility. (Steady, grinding uptrends).
↘ Bearish Regime: High negative momentum with high volatility. (Aggressive sell-offs and panic).
↕ Chop / Chaos Regime: Zero/low momentum with high volatility. (Whipsaw, ranging, and unpredictable noise).
2. How It Works (The Quant Engine)
Since Pine Script does not natively support complex matrix optimization, this script builds a robust Pseudo-HMM using a predefined Transition Matrix and Bayesian Updates.
Observables (Emissions): The script calculates the Z-Scores of Smoothed Momentum (Rate of Change) and Volatility (ATR).
Emission Probabilities (Gaussian PDF): It feeds these Z-Scores into a Gaussian Probability Density Function to see how well the current market matches the expected profile of a Bull, Bear, or Chop regime.
Bayesian Update: Using a predefined Markov Transition Matrix (the statistical inertia of a trend), it updates the prior probabilities to give you a real-time percentage (0-100%) for each regime.
3. Advanced Visual Features & UI
We built a custom UI/UX engine to make digesting complex probabilities instantaneous:
Exponential Color Smoothing (Bar Colors): As the probability of a regime increases, the bar colors smoothly transition. We implemented an exponential color blending algorithm to prevent abrupt, distracting color changes and eliminate "muddy" colors during transitions.
Pro Quant Dashboard: A built-in HUD (Heads-Up Display) provides a quick summary. It features a dominant state readout, an overall "Confidence Score", and ASCII-style mini progress bars (████░░░) for rapid visual processing of probabilities without needing to read the numbers.
Stacked Area Oscillator: The bottom panel displays a 0-100 stacked area chart, showing the exact distribution of probabilities across Bull (Green), Chop (Purple), and Bear (Red) states.
4. How to Use This Tool
This is not a standalone Buy/Sell signal indicator. It is a Strategy Filter and a Risk Manager.
When Bull/Bear Probability is Dominant (>50%): The market is trending. Turn ON your trend-following indicators (like Moving Averages or Breakout systems) and ignore overbought/oversold signals.
When Chop Probability is Dominant (>50%): The market is noisy. Turn OFF your trend-following systems. Either switch to Mean Reversion strategies (like RSI or Bollinger Bands) or stay in cash until a clear regime emerges.
Watch the Confidence Score: If the Dashboard shows "LOW" confidence, it means the probabilities are split (e.g., 34% Bull, 33% Chop, 33% Bear). Wait for the model to gain confidence before committing capital.
5. Alerts
The script includes non-repainting alerts that trigger only when the dominant regime changes:
HMM Regime: BULLISH 🚀 * HMM Regime: BEARISH 🩸 * HMM Regime: CHOP ⚖️
6. Settings
Lookback Period: The window used to calculate the Z-scores for momentum and volatility.
Transition Matrix: Allows advanced users to tweak the statistical likelihood of the market staying in its current state versus transitioning to a new one.
Color Transition Speed: Adjusts the smoothness of the bar coloring. A lower value creates a buttery-smooth fade between regimes, while a value of 1.0 makes it instant. Indicator

Sector Divergence DashboardStatistical arbitrage dashboard for markets and sector ETFs
This Sector Divergence Dashboard is a tool designed to identify mean-reversion opportunities across U.S. equity sectors. I've built it to help me with portfolio management and sector allocation by identifying uncorrelated sectors and divergences between indices and sector ETFs. These divergences are often good investment opportunities.
The indicator also helps you with sector rotation by identifying when sectors have diverged too far from their historical relationships with the broader market. This is a similar methodology used daily in institutional portfolio management and hedge funds.
In this dashboard, you can see:
Z-Score Analysis on log price ratios to detect statistical anomalies
Dual-timeframe correlation tracking to identify relationship breakdowns
Composite scoring that combines divergence magnitude, correlation shifts, and momentum
Correlation heatmap for instant relationship assessment across all pairs
You see exactly which pairs are statistically mispriced and likely to revert to their historical mean.
NOTE: This dashboard is computationally heavy and might take up to one minute to load in your PulseWire.
The Mathematics
1. Price Ratio Z-Score
The indicator calculates the logarithmic price ratio between two assets (e.g., SPY/XLE) and measures how many standard deviations this ratio has moved from its historical average. A z-score of +2.0 means the pair is 2 standard deviations expensive relative to history. This can be a mean-reversion setup.
2. Correlation Breakdown Detection
Short-term correlation (35 bars) is compared against long-term correlation (100 bars). You can change these parameters BTW. When correlations diverge significantly, it signals that the normal relationship has temporarily broken, potentially creating trading opportunities.
3. Relative Performance
Measures the momentum difference between pairs over 300 bars (roughly 60 weeks on daily charts). This captures longer-term structural shifts versus short-term noise.
4. Composite Score
All three metrics are normalized and weighted to create a single ranking score:
50% Z-Score Weight - Primary driver of mean reversion probability
25% Correlation Breakdown - Relationship stability metric
25% Relative Performance - Momentum/trend context
Features
1. Correlation Heatmap
Visualize all pairwise correlations
Color-coded from red (negative correlation) to green (strong positive)
Spot which sectors are moving together or decoupling
2. Divergence Rankings Table
Top 15 SPY-vs-sector pairs ranked by composite opportunity score
Z-scores, correlations, performance differentials, and signals
Color-coded from gray (neutral) to red (extreme divergence)
Scan it daily for setups
3. Deep Dive Chart
Detailed z-score visualization for any selected pair
Visual zones showing normal range, signal threshold, and strong signal areas
Short-term and long-term correlation overlays
Real-time information label with current metrics and signal status
Perfect for analyzing specific opportunities in depth
You can define which symbols you want to deep dive in the parameters
Parameter Guide
Short-Term Correlation - Recent relationship strength
Long-Term Correlation - Historical baseline relationship
Z-Score Length - Mean reversion lookback period
Relative Performance - Longer-term momentum context
Pro Tip : Increase z-score length to 150+ for fewer but stronger signals. Decrease to 50-75 for more frequent opportunities (but more noisy).
Use Cases
Sector Rotation: Identify which sectors are over/undervalued relative to the market
Portfolio Rebalancing: Data-driven signals for tactical asset allocation adjustments
Pairs Trading: Statistical arbitrage between correlated instruments
Risk Management: Monitor correlation stability across your portfolio
Market Regime Detection: Spot when sector relationships are breaking down
Swing Trading: Mean-reversion setups with clear entry/exit rules
Example:
XLK, a key tech ETF, is typically very correlated with the S&P 500 with a 0.88 correlation. Our dashboard detected a divergence between both, which signals a buy/rotation to XLK.
Let me know if you have any requests, improvements suggestions or feedback :) Indicator

Sigmoid Allocation Indicator & DashboardTL;DR This sigmoid-based allocation indicator tells you percentage of your portfolio to invest based on how much the market has dropped.
Market at all-time high? → Stay defensive, invest less (e.g., 30%)
Market crashed hard? → Get aggressive, invest more (e.g., 100%)
The "sigmoid" part just means the transition between these two extremes follows a smooth S-shaped curve.
Description
This indicator is a sigmoid-based allocation system that dynamically adjusts a portfolio exposure based on market drawdown.
It compares multiple steepness curves (K values) to find your optimal risk profile for leveraged ETF strategies, but it can also be used to scale in-out from stocks, crypto and to understand whether to use leverage or not.
The Sigmoid Allocation Dashboard helps you to dynamically adjust a portfolio allocation based on how much a market has dropped from its all-time high.
I've implemented it using a sigmoid (S-curve) function, that dynamically calculates the optimal allocation percentages. Depending on the market conditions, the S curves transition between defensive and aggressive allocations.
The Math Behind It (if you are a geek like me)
This indicator uses the sigmoid function to create smooth S-curve transitions:
α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
Where:
σ(x) = 1 / (1 + e^(-x)) ← Standard sigmoid function
You can also check it here:
// Sigmoid function: σ(x) = 1 / (1 + e^(-x))
sigmoid(float x) =>
1.0 / (1.0 + math.exp(-x))
// Alpha calculation: α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
calcAlpha(float drawdown, float k, float a_min, float a_max, float d_midpoint) =>
sig_input = k * (drawdown - d_midpoint) / 100.0
a_min + (a_max - a_min) * sigmoid(sig_input)
User parameters (you can tweak this):
Allocation Min (%): Your baseline allocation when markets are at ATH (default: 30%)
Allocation Max (%): Your maximum allocation during deep drawdowns (default: 100%)
D_mid (%): The drawdown level where you want to be at the midpoint (default: 25%)
Why do I like sigmoid and not a linear line?
Unlike linear models, the sigmoid creates "floors" and "ceilings" for your allocation. It transitions smoothly, no sudden jumps, and you never exceed your defined min/max bounds.
Understand the K Values (Steepness)
The K parameter controls how quickly your allocation shifts from defensive to aggressive.
Lower K (for example K=5) will give you a gradual transition, but at 0% drawdown you are already at a 46% allocation.
A higher like (like K=40) will give you a sharp transition, but at 0% drawdown you are close to the minimum allocation. On the other hand, a higher K will give close to 100% allocation when the markets are at new lows.
The example below illustrates this well, then the S&P 500 reached new lows in October 2022:
Different K values will affect the sigmoid curves (and you allocations differently). The chart below illustrates well how K affects the sigmoid curves:
Read the Dashboard
The main dashboard shows:
Current drawdown from ATH
Allocation % for each K value
Suggested action (Defensive → MAX LONG)
Use the Reference Chart
The static reference panel shows what your allocation would be at various drawdown levels (0%, 10%, 20%, 30%, 40%, 50%), helping you plan ahead.
Identify Zones
The color-coded chart background shows:
- 🟢 Green Zone: Aggressive positioning - "Buy the Dip"
- 🟡 Yellow Zone: Transition zone - Scaling in/out
- 🔴 Red Zone: Defensive positioning - Protect ya gains
Use Cases
Use case 1: Leveraged ETF Portfolio Management (this is my main use case)
When holding leveraged ETFs like TQQQ or UPRO, volatility makes it important to:
- Reduce exposure near all-time highs (when crashes hurt most)
- Increase exposure during drawdowns (when recovery potential is highest)
Example Strategy:
- At ATH: Hold 30% TQQQ, 70% cash/bonds or other uncorrelated assets
- At 25% drawdown: Hold 65% TQQQ, 35% cash/bonds
- At 40%+ drawdown: Hold 100% TQQQ
Use case 2: Diversified Leveraged Portfolio
Compare different K values for different assets:
- Use K = 10 for broad market (QQQ/SPY exposure via TQQQ/UPRO)
- Use K = 25 for sector bets (TECL, SOXL, TMF) that you want to scale into faster
Use case 3: Systematic Rebalancing Signals
Use the alerts to trigger rebalancing:
- Alert when K3 allocation crosses above 90% (time to add)
- Alert when drawdown exceeds your D_mid threshold
- Alert when market returns to within 5% of ATH
Tips for Best Results
It works best in longer time frames
Adjust the ATR lookback window
Match your risk tolerance level
I use this for index investing and stocks and haven't tried with crypto
Thanks for using the indicator and let me know if you have any feedback :)
- Henrique Centieiro
Indicator

Linear Regression Channel with Multi Sigma and Multi Time FrameThis indicator applies multi-sigma linear regression across multiple institutional time horizons to quantify the line of best fit in equities and index markets. By combining multi-timeframe presets with statistically derived deviation bands, it highlights trend structure, volatility expansion, and regime transitions with clarity.
Features
Auto-Multi-Timeframe presets map directly to institutional trend horizons (daily, weekly, monthly) for accurate regime detection.
Multi-Sigma bands (+/-1, +/-2, +/-3) reveal volatility structure, trend strength, and statistical extremes.
The regression line uses a true least-squares calculation, recalculated each bar for precise trend alignment.
Deviation mode allows switching between standard deviation and max deviation to support different volatility models.
A linked PDF on GitHub provides full documentation, derivations, and institutional use-case examples.
More Information Can Be Found Here:
github.com Indicator

Lorentzian Length Adaptive Moving Average [LLAMA] Adaptation of "Machine Learning: Lorentzian Classification" by
Gradient color by base on work by
LLAMA: A regime-aware adaptive moving average that bends with the market.
Start with a problem traders know:
Traditional moving averages are either too slow (EMA200) or too fast (EMA9)
Adaptive MAs exist, but they often hug price too tightly or smooth too much, failing to balance bias and tactics
LLAMA uses a Lorentzian distance function to adapt its length dynamically. Instead of a fixed smoothing window, it stretches or contracts depending on market conditions. This distortion reduces lag while still providing a clear bias line.
The indicator looks back at recent bars and measures how similar they are using a Lorentzian distance (a log‑scaled absolute difference). It keeps track of the “nearest neighbors” — bars that most resemble the current regime. Each neighbor carries a label (long, short, neutral) based on simple price comparisons. By averaging these labels, LLAMA predicts whether the market is leaning bullish or bearish. That prediction is then mapped into a dynamic length between and .
Bullish bias -> length stretches toward max (smoother, more stable).
Bearish bias -> length contracts toward min (snappier, more reactive).
During breakouts, LLAMA tightens and comes into contact with bars, giving actionable signals. During chop, it stretches to avoid false triggers. It covers both ends of the spectrum (bias and tactics) in one line, something static MA's can't do.
Think of LLAMA as a lens that bends with the market:
Wide lens (max length) for big picture bias.
Narrow lens (min length) for tactical precision.
The "Lorentzian Loop" is the math that decides when to widen or narrow. Indicator

Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
Indicator

Central Limit Theorem Reversion IndicatorDear TV community, let me introduce you to the first-ever Central Limit Theorem indicator on PulseWire.
The Central Limit Theorem is used in statistics and it can be quite useful in quant trading and understanding market behaviors.
In short, the CLT states: "When you take repeated samples from any population and calculate their averages, those averages will form a normal (bell curve) distribution—no matter what the original data looks like."
In this CLT indicator, I use statistical theory to identify high-probability mean reversion opportunities in the markets. It calculates statistical confidence bands and z-scores to identify when price movements deviate significantly from their expected distribution, signaling potential reversion opportunities with quantifiable probability levels.
Mathematical Foundation
The Central Limit Theorem (CLT) says that when you average many data points together, those averages will form a predictable bell-curve pattern, even if the original data is completely random and unpredictable (which often is in the markets). This works no matter what you're measuring, and it gets more reliable as you use more data points.
Why using it for trading?
Individual price movements seem random and chaotic, but when we look at the average of many price movements, we can actually predict how they should behave statistically. This lets us spot when prices have moved "too far" from what's normal—and those extreme moves tend to snap back (mean reversion).
Key Formula:
Z = (X̄ - μ) / (σ / √n)
Where:
- X̄ = Sample mean (average return over n periods)
- μ = Population mean (long-term expected return)
- σ = Population standard deviation (volatility)
- n = Sample size
- σ/√n = Standard error of the mean
How I Apply CLT
Step 1: Calculate Returns
Measures how much price changed from one bar to the next (using logarithms for better statistical properties)
Step 2: Average Recent Returns
Takes the average of the last n returns (e.g., last 100 bars). This is your "sample mean."
Step 3: Find What's "Normal"
Looks at historical data to determine: a) What the typical average return should be (the long-term mean) and b) How volatile the market usually is (standard deviation)
Step 4: Calculate Standard Error
Determines how much sample averages naturally vary. Larger samples = smaller expected variation.
Step 5: Calculate Z-Score
Measures how unusual the current situation is.
Step 6: Draw Confidence Bands
Converts these statistical boundaries into actual price levels on your chart, showing where price is statistically expected to stay 95% and 99% of the time.
Interpretation & Usage
The Z-Score:
The z-score tells you how statistically unusual the current price deviation is:
|Z| < 1.0 → Normal behavior, no action
|Z| = 1.0 to 1.96 → Moderate deviation, watch closely
|Z| = 1.96 to 2.58 → Significant deviation (95%+), consider entry
|Z| > 2.58 → Extreme deviation (99%+), high probability setup
The Confidence Bands
- Upper Red Bands: 95% and 99% overbought zones → Expect mean reversion downward as the price is not likely to cross these lines.
- Center Gray Line: Statistical expectation (fair value)
- Lower Blue Bands: 95% and 99% oversold zones → Expect mean reversion upward
Trading Logic:
- When price exceeds the upper 95% band (z-score > +1.96), there's only a 5% probability this is random noise → Strong sell/short signal
- When price falls below the lower 95% band (z-score < -1.96), there's a 95% statistical expectation of upward reversion → Strong buy/long signal
Background Gradient
The background color provides real-time visual feedback:
- Blue shades: Oversold conditions, expect upward reversion
- Red shades: Overbought conditions, expect downward reversion
- Intensity: Darker colors indicate stronger statistical significance
Trading Strategy Examples
Hypothetically, this is how the indicator could be used:
- Long: Z-score < -1.96 (below 95% confidence band)
- Short: Z-score > +1.96 (above 95% confidence band)
- Take profit when price returns to center line (Z ≈ 0)
Input Parameters
Sample Size (n) - Default: 100
Lookback Period (m) - Default: 100
You can also create alerts based on the indicator.
Final notes:
- The indicator uses logarithmic returns for better statistical properties
- Converts statistical bands back to price space for practical use
- Adaptive volatility: Bands automatically widen in high volatility, narrow in low volatility
- No repainting: yay! All calculations use historical data only
Feedback is more than welcome!
Henri Indicator

Volume Sampled Supertrend [BackQuant]Volume Sampled Supertrend
A Supertrend that runs on a volume sampled price series instead of fixed time. New synthetic bars are only created after sufficient traded activity, which filters out low participation noise and makes the trend much easier to read and model.
Original Script Link
This indicator is built on top of my volume sampling engine. See the base implementation here:
Why Volume Sampling
Traditional charts print a bar every N minutes regardless of how active the tape is. During quiet periods you accumulate many small, low information bars that add noise and whipsaws to downstream signals.
Volume sampling replaces the clock with participation. A new synthetic bar is created only when a pre-set amount of volume accumulates (or, in Dollar Bars mode, when pricevolume reaches a dollar threshold). The result is a non-uniform time series that stretches in busy regimes and compresses in quiet regimes. This naturally:
filters dead time by skipping low volume chop;
standardizes the information content per bar, improving comparability across regimes;
stabilizes volatility estimates used inside banded indicators;
gives trend and breakout logic cleaner state transitions with fewer micro flips.
What this tool does
It builds a synthetic OHLCV stream from volume based buckets and then applies a Supertrend to that synthetic price. You are effectively running Supertrend on a participation clock rather than a wall clock.
Core Features
Sampling Engine - Choose Volume buckets or Dollar Bars . Thresholds can be dynamic from a rolling mean or median, or fixed by the user.
Synthetic Candles - Plots the volume sampled OHLC candles so you can visually compare against regular time candles.
Supertrend on Synthetic Price - ATR bands and direction are computed on the sampled series, not on time bars.
Adaptive Coloring - Candle colors can reflect side, intensity by volume, or a neutral scheme.
Research Panels - Table shows total samples, current bucket fill, threshold, bars-per-sample, and synthetic return stats.
Alerts - Long and Short triggers on Supertrend direction flips for the synthetic series.
How it works
Sampling
Pick Sampling Method = Volume or Dollar Bars.
Set the dynamic threshold via Rolling Lookback and Filter (Mean or Median), or enable Use Fixed and type a constant.
The script accumulates volume (or pricevolume) each time bar. When the bucket reaches the threshold, it finalizes one or more synthetic candles and resets accumulation.
Each synthetic candle stores its own OHLCV and is appended to the synthetic series used for all downstream logic.
Supertrend on the sampled stream
Choose Supertrend Source (Open, High, Low, Close, HLC3, HL2, OHLC4, HLCC4) derived from the synthetic candle.
Compute ATR over the synthetic series with ATR Period , then form upperBand = src + factorATR and lowerBand = src - factorATR .
Apply classic trailing band and direction rules to produce Supertrend and trend state.
Because bars only come when there is sufficient participation, band touches and flips tend to align with meaningful pushes, not idle prints.
Reading the display
Synthetic Volume Bars - The non-uniform candles that represent equal information buckets. Expect more candles during active sessions and fewer during lulls.
Volume Sampled Supertrend - The main line. Green when Trend is 1, red when Trend is -1.
Markers - Small dots appear when a new synthetic sample is created, useful for aligning activity cycles.
Time Bars Overlay (optional) - Plot regular time candles to compare how the synthetic stream compresses quiet chop.
Settings you will use most
Data Settings
Sampling Method - Volume or Dollar Bars.
Rolling Lookback and Filter - Controls the dynamic threshold. Median is robust to outliers, Mean is smoother.
Use Fixed and Fixed Threshold - Force a constant bucket size for consistent sampling across regimes.
Max Stored Samples - Ring buffer limit for performance.
Indicator Settings
SMA over last N samples - A moving average computed on the synthetic close series. Can be hidden for a cleaner layout.
Supertrend Source - Price field from the synthetic candle.
ATR Period and Factor - Standard Supertrend controls applied on the synthetic series.
Visuals and UI
Show Synthetic Bars - Turn synthetic candles on or off.
Candle Color Mode - Green/Red, Volume Intensity, Neutral, or Adaptive.
Mark new samples - Puts a dot when a bucket closes.
Show Time Bars - Overlay regular candles for comparison.
Paint candles according to Trend - Colors chart candles using current synthetic Supertrend direction.
Line Width , Colors , and Stats Table toggles.
Some workflow notes:
Trend Following
Set Sampling Method = Volume, Filter = Median, and a reasonable Rolling Lookback so busy regimes produce more samples.
Trade in the direction of the Volume Sampled Supertrend. Because flips require real participation, you tend to avoid micro whipsaws seen on time bars.
Use the synthetic SMA as a bias rail and trailing reference for partials or re-entries.
Breakout and Continuation
Watch for rapid clustering of new sample markers and a clean flip of the synthetic Supertrend.
The compression of quiet time and expansion in busy bursts often makes breakouts more legible than on uniform time charts.
Mean Reversion
In instruments that oscillate, faded moves against the synthetic Supertrend are easier to time when the bucket cadence slows and Supertrend flattens.
Combine with the synthetic SMA and return statistics in the table for sizing and expectation setting.
Stats table (top right)
Method and Total Samples - Sampling regime and current synthetic history length.
Current Vol or Dollar and Threshold - Live bucket fill versus the trigger.
Bars in Bucket and Avg Bars per Sample - How much time data each synthetic bar tends to compress.
Avg Return and Return StdDev - Simple research metrics over synthetic close-to-close changes.
Why this reduces noise
Time based bars treat a 5 minute print with 1 percent of average participation the same as one with 300 percent. Volume sampling equalizes bar information content. By advancing the bar only when sufficient activity occurs, you skip low quality intervals that add variance but little signal. For banded systems like Supertrend, this often means fewer false flips and cleaner runs.
Notes and tips
Use Dollar Bars on assets where nominal price varies widely over time or across symbols.
Median filter can resist single burst outliers when setting dynamic thresholds.
If you need a stable research baseline, set Use Fixed and keep the threshold constant across tests.
Enable Show Time Bars occasionally to sanity check what the synthetic stream is compressing or stretching.
Link again for reference
Original Volume Based Sampling engine:
Bottom line
When you let participation set the clock, your Supertrend reacts to meaningful flow instead of idle prints. The result is a cleaner state machine, fewer micro whipsaws, and a trend read that respects when the market is actually trading.
Indicator

First Passage Time - Distribution AnalysisThe First Passage Time (FPT) Distribution Analysis indicator is a sophisticated probabilistic tool that answers one of the most critical questions in trading: "How long will it take for price to reach my target, and what are the odds of getting there first?"
Unlike traditional technical indicators that focus on what might happen, this indicator tells you when it's likely to happen.
Mathematical Foundation: First Passage Time Theory
What is First Passage Time?
First Passage Time (FPT) is a concept in stochastic processes that measures the time it takes for a random process to reach a specific threshold for the first time. Originally developed in physics and mathematics, FPT has applications in:
Quantitative Finance: Option pricing, risk management, and algorithmic trading
Neuroscience: Modeling neural firing patterns
Biology: Population dynamics and disease spread
Engineering: Reliability analysis and failure prediction
The Mathematics Behind It
This indicator uses Geometric Brownian Motion (GBM), the same stochastic model used in the Black-Scholes option pricing formula:
dS = μS dt + σS dW
Where:
S = Asset price
μ = Drift (trend component)
σ = Volatility (uncertainty component)
dW = Wiener process (random walk)
Through Monte Carlo simulation, the indicator runs 1,000+ price path simulations to statistically determine:
When each threshold (+X% or -X%) is likely to be hit
Which threshold is hit first (directional bias)
How often each scenario occurs (probability distribution)
🎯 How This Indicator Works
Core Algorithm Workflow:
Calculate Historical Statistics
Measures recent price volatility (standard deviation of log returns)
Calculates drift (average directional movement)
Annualizes these metrics for meaningful comparison
Run Monte Carlo Simulations
Generates 1,000+ random price paths based on historical behavior
Tracks when each path hits the upside (+X%) or downside (-X%) threshold
Records which threshold was hit first in each simulation
Aggregate Statistical Results
Calculates percentile distributions (10th, 25th, 50th, 75th, 90th)
Computes "first hit" probabilities (upside vs downside)
Determines average and median time-to-target
Visual Representation
Displays thresholds as horizontal lines
Shows gradient risk zones (purple-to-blue)
Provides comprehensive statistics table
📈 Use Cases
1. Options Trading
Selling Options: Determine if your strike price is likely to be hit before expiration
Buying Options: Estimate probability of reaching profit targets within your time window
Time Decay Management: Compare expected time-to-target vs theta decay
Example: You're considering selling a 30-day call option 5% out of the money. The indicator shows there's a 72% chance price hits +5% within 12 days. This tells you the trade has high assignment risk.
2. Swing Trading
Entry Timing: Wait for higher probability setups when directional bias is strong
Target Setting: Use median time-to-target to set realistic profit expectations
Stop Loss Placement: Understand probability of hitting your stop before target
Example: The indicator shows 85% upside probability with median time of 3.2 days. You can confidently enter long positions with appropriate position sizing.
3. Risk Management
Position Sizing: Larger positions when probability heavily favors one direction
Portfolio Allocation: Reduce exposure when probabilities are near 50/50 (high uncertainty)
Hedge Timing: Know when to add protective positions based on downside probability
Example: Indicator shows 55% upside vs 45% downside—nearly neutral. This signals high uncertainty, suggesting reduced position size or wait for better setup.
4. Market Regime Detection
Trending Markets: High directional bias (70%+ one direction)
Range-bound Markets: Balanced probabilities (45-55% both directions)
Volatility Regimes: Compare actual vs theoretical minimum time
Example: Consistent 90%+ bullish bias across multiple timeframes confirms strong uptrend—stay long and avoid counter-trend trades.
First Hit Rate (Most Important!)
Shows which threshold is likely to be hit FIRST:
Upside %: Probability of hitting upside target before downside
Downside %: Probability of hitting downside target before upside
These always sum to 100%
⚠️ Warning: If you see "Low Hit Rate" warning, increase this parameter!
Advanced Parameters
Drift Mode
Allows you to explore different scenarios:
Historical: Uses actual recent trend (default—most realistic)
Zero (Neutral): Assumes no trend, only volatility (symmetric probabilities)
50% Reduced: Dampens trend effect (conservative scenario)
Use Case: Switch to "Zero (Neutral)" to see what happens in a pure volatility environment, useful for range-bound markets.
Distribution Type
Percentile: Shows 10%, 25%, 50%, 75%, 90% levels (recommended for most users)
Sigma: Shows standard deviation levels (1σ, 2σ)—useful for statistical analysis
⚠️ Important Limitations & Best Practices
Limitations
Assumes GBM: Real markets have fat tails, jumps, and regime changes not captured by GBM
Historical Parameters: Uses recent volatility/drift—may not predict regime shifts
No Fundamental Events: Cannot predict earnings, news, or macro shocks
Computational: Runs only on last bar—doesn't give historical signals
Remember: Probabilities are not certainties. Use this indicator as part of a comprehensive trading plan with proper risk management.
Created by: Henrique Centieiro. feedback is more than welcome! Indicator

Volume Based Sampling [BackQuant]Volume Based Sampling
What this does
This indicator converts the usual time-based stream of candles into an event-based stream of “synthetic” bars that are created only when enough trading activity has occurred . You choose the activity definition:
Volume bars : create a new synthetic bar whenever the cumulative number of shares/contracts traded reaches a threshold.
Dollar bars : create a new synthetic bar whenever the cumulative traded dollar value (price × volume) reaches a threshold.
The script then keeps an internal ledger of these synthetic opens, highs, lows, closes, and volumes, and can display them as candles, plot a moving average calculated over the synthetic closes, mark each time a new sample is formed, and optionally overlay the native time-bars for comparison.
Why event-based sampling matters
Markets do not release information on a clock: activity clusters during news, opens/closes, and liquidity shocks. Event-based bars normalize for that heteroskedastic arrival of information: during active periods you get more bars (finer resolution); during quiet periods you get fewer bars (coarser resolution). Research shows this can reduce microstructure pathologies and produce series that are closer to i.i.d. and more suitable for statistical modeling and ML. In particular:
Volume and dollar bars are a common event-time alternative to time bars in quantitative research and are discussed extensively in Advances in Financial Machine Learning (AFML). These bars aim to homogenize information flow by sampling on traded size or value rather than elapsed seconds.
The Volume Clock perspective models market activity in “volume time,” showing that many intraday phenomena (volatility, liquidity shocks) are better explained when time is measured by traded volume instead of seconds.
Related market microstructure work on flow toxicity and liquidity highlights that the risk dealers face is tied to information intensity of order flow, again arguing for activity-based clocks.
How the indicator works (plain English)
Choose your bucket type
Volume : accumulate volume until it meets a threshold.
Dollar Bars : accumulate close × volume until it meets a dollar threshold.
Pick the threshold rule
Dynamic threshold : by default, the script computes a rolling statistic (mean or median) of recent activity to set the next bucket size. This adapts bar size to changing conditions (e.g., busier sessions produce more frequent synthetic bars).
Fixed threshold : optionally override with a constant target (e.g., exactly 100,000 contracts per synthetic bar, or $5,000,000 per dollar bar).
Build the synthetic bar
While a bucket fills, the script tracks:
o_s: first price of the bucket (synthetic open)
h_s: running maximum price (synthetic high)
l_s: running minimum price (synthetic low)
c_s: last price seen (synthetic close)
v_s: cumulative native volume inside the bucket
d_samples: number of native bars consumed to complete the bucket (a proxy for “how fast” the threshold filled)
Emit a new sample
Once the bucket meets/exceeds the threshold, a new synthetic bar is finalized and stored. If overflow occurs (e.g., a single native bar pushes you past the threshold by a lot), the code will emit multiple synthetic samples to account for the extra activity.
Maintain a rolling history efficiently
A ring buffer can overwrite the oldest samples when you hit your Max Stored Samples cap, keeping memory usage stable.
Compute synthetic-space statistics
The script computes an SMA over the last N synthetic closes and basic descriptors like average bars per synthetic sample, mean and standard deviation of synthetic returns, and more. These are all in event time , not clock time.
Inputs and options you will actually use
Data Settings
Sampling Method : Volume or Dollar Bars.
Rolling Lookback : window used to estimate the dynamic threshold from recent activity.
Filter : Mean or Median for the dynamic threshold. Median is more robust to spikes.
Use Fixed? / Fixed Threshold : override dynamic sizing with a constant target.
Max Stored Samples : cap on synthetic history to keep performance snappy.
Use Ring Buffer : turn on to recycle storage when at capacity.
Indicator Settings
SMA over last N samples : moving average in synthetic space . Because its index is sample count, not minutes, it adapts naturally: more updates in busy regimes, fewer in quiet regimes.
Visuals
Show Synthetic Bars : plot the synthetic OHLC candles.
Candle Color Mode :
Green/Red: directional close vs open
Volume Intensity: opacity scales with synthetic size
Neutral: single color
Adaptive: graded by how large the bucket was relative to threshold
Mark new samples : drop a small marker whenever a new synthetic bar prints.
Comparison & Research
Show Time Bars : overlay the native time-based candles to visually compare how the two sampling schemes differ.
How to read it, step by step
Turn on “Synthetic Bars” and optionally overlay “Time Bars.” You will see that during high-activity bursts, synthetic bars print much faster than time bars.
Watch the synthetic SMA . Crosses in synthetic space can be more meaningful because each update represents a roughly comparable amount of traded information.
Use the “Avg Bars per Sample” in the info table as a regime signal. Falling average bars per sample means activity is clustering, often coincident with higher realized volatility.
Try Dollar Bars when price varies a lot but share count does not; they normalize by dollar risk taken in each sample. Volume Bars are ideal when share count is a better proxy for information flow in your instrument.
Quant finance background and citations
Event time vs. clock time : Easley, López de Prado, and O’Hara advocate measuring intraday phenomena on a volume clock to better align sampling with information arrival. This framing helps explain volatility bursts and liquidity droughts and motivates volume-based bars.
Flow toxicity and dealer risk : The same authors show how adverse selection risk changes with the intensity and informativeness of order flow, further supporting activity-based clocks for modeling and risk management.
AFML framework : In Advances in Financial Machine Learning , event-driven bars such as volume, dollar, and imbalance bars are presented as superior sampling units for many ML tasks, yielding more stationary features and fewer microstructure distortions than fixed time bars. ( Alpaca )
Practical use cases
1) Regime-aware moving averages
The synthetic SMA in event time is not fooled by quiet periods: if nothing of consequence trades, it barely updates. This can make trend filters less sensitive to calendar drift and more sensitive to true participation.
2) Breakout logic on “equal-information” samples
The script exposes simple alerts such as breakout above/below the synthetic SMA . Because each bar approximates a constant amount of activity, breakouts are conditioned on comparable informational mass, not arbitrary time buckets.
3) Volatility-adaptive backtests
If you use synthetic bars as your base data stream, most signal rules become self-paced : entry and exit opportunities accelerate in fast markets and slow down in quiet regimes, which often improves the realism of slippage and fill modeling in research pipelines (pair this indicator with strategy code downstream).
4) Regime diagnostics
Avg Bars per Sample trending down: activity is dense; expect larger realized ranges.
Return StdDev (synthetic) rising: noise or trend acceleration in event time; re-tune risk.
Interpreting the info panel
Method : your sampling choice and current threshold.
Total Samples : how many synthetic bars have been formed.
Current Vol/Dollar : how much of the next bucket is already filled.
Bars in Bucket : native bars consumed so far in the current bucket.
Avg Bars/Sample : lower means higher trading intensity.
Avg Return / Return StdDev : return stats computed over synthetic closes .
Research directions you can build from here
Imbalance and run bars
Extend beyond pure volume or dollar thresholds to imbalance bars that trigger on directional order flow imbalance (e.g., buy volume minus sell volume), as discussed in the AFML ecosystem. These often further homogenize distributional properties used in ML. alpaca.markets
Volume-time indicators
Re-compute classical indicators (RSI, MACD, Bollinger) on the synthetic stream. The premise is that signals are updated by traded information , not seconds, which may stabilize indicator behavior in heteroskedastic regimes.
Liquidity and toxicity overlays
Combine synthetic bars with proxies of flow toxicity to anticipate spread widening or volatility clustering. For instance, tag synthetic bars that surpass multiples of the threshold and test whether subsequent realized volatility is elevated.
Dollar-risk parity sampling for portfolios
Use dollar bars to align samples across assets by notional risk, enabling cleaner cross-asset features and comparability in multi-asset models (e.g., correlation studies, regime clustering). AFML discusses the benefits of event-driven sampling for cross-sectional ML feature engineering.
Microstructure feature set
Compute duration in native bars per synthetic sample , range per sample , and volume multiple of threshold as inputs to state classifiers or regime HMMs . These features are inherently activity-aware and often predictive of short-horizon volatility and trend persistence per the event-time literature. ( Alpaca )
Tips for clean usage
Start with dynamic thresholds using Median over a sensible lookback to avoid outlier distortion, then move to Fixed thresholds when you know your instrument’s typical activity scale.
Compare time bars vs synthetic bars side by side to develop intuition for how your market “breathes” in activity time.
Keep Max Stored Samples reasonable for performance; the ring buffer avoids memory creep while preserving a rolling window of research-grade data.
Indicator

Expected Value Monte CarloI created this indicator after noticing that there was no Expected Value indicator here on PulseWire.
The EVMC provides statistical Expected Value to what might happen in the future regarding the asset you are analyzing.
It uses 2 quantitative methods:
Historical Backtest to ground your analysis in long-term, factual data.
Monte Carlo Simulation to project a cone of probable future outcomes based on recent market behavior.
This gives you a data-driven edge to quantify risk, and make more informed trading decisions.
The indicator includes:
Dual analysis: Combines historical probability with forward-looking simulation.
Quantified projections: Provides the Expected Value ($ and %), Win Rate, and Sharpe Ratio for both methods.
Asset-aware: Automatically adjusts its calculations for Stocks (252 trading days) and Crypto (365 days) for mathematical accuracy.
The projection cone shows the mean expected path and the +/- 1 standard deviation range of outcomes.
No repainting
Calculation:
1. Historical Expected Value:
This is a systematic backtest over thousands of bars. It calculates the return Rᵢ for N past trades (buy-and-hold). The Historical EV is the simple average of these returns, giving a baseline performance measure.
Historical EV % = (Σ Rᵢ) / N
2. Monte Carlo Projection:
This projection uses the Geometric Brownian Motion (GBM) model to simulate thousands of future price paths based on the market's recent behavior.
It first measures the drift (μ), or recent trend, and volatility (σ), or recent risk, from the Projection Lookback period. It then projects a final return for each simulation using the core GBM formula:
Projected Return = exp( (μ - σ²/2)T + σ√T * Z ) - 1
(Where T is the time horizon and Z is a random variable for the simulation.)
The purple line on the chart is the average of all simulated outcomes (the Monte Carlo EV). The cone represents one standard deviation of those outcomes.
The dashed lines represent one standard deviation (+/- 1σ) from the average, forming a cone of probable outcomes. Roughly 68% of the simulated paths ended within this cone.
This projection answers the question: "If the recent trend and volatility continue, where is the price most likely to go?"
Here's how to read the indicator
Expected Value ($/%): Is my average trade profitable?
Win Rate: How often can I expect to be right?
Sharpe Ratio: Am I being adequately compensated for the risk I'm taking?
User Guide
Max trade duration (bars): This is your analysis timeframe. Are you interested in the probable outcome over the next month (21 bars), quarter (63 bars), or year (252 bars)?
Position size ($): Set this to your typical trade size to see the Expected Value in real dollar terms.
Projection lookback (bars): This is the most important input for the Monte Carlo model. A short lookback (e.g., 50) makes the projection highly sensitive to recent momentum. Use this to identify potential recency bias. A long lookback (e.g., 252) provides a more stable, long-term projection of trend and volatility.
Historical Lookback (bars): For the historical backtest, more data is always better. Use the maximum that your PulseWire plan allows for the most statistically significant results.
Use TP/SL for Historical EV: Check this box to see how the historical performance would have changed if you had used a simple Take Profit and Stop Loss, rather than just holding for the full duration.
I hope you find this indicator useful and please let me know if you have any suggestions. 😊 Indicator

Mutanabby_AI | Ultimate Algo | Remastered+Overview
The Mutanabby_AI Ultimate Algo Remastered+ represents a sophisticated trend-following system that combines Supertrend analysis with multiple moving average confirmations. This comprehensive indicator is designed specifically for identifying high-probability trend continuation and reversal opportunities across various market conditions.
Core Algorithm Components
**Supertrend Foundation**: The primary signal generation relies on a customizable Supertrend indicator with adjustable sensitivity (1-20 range). This adaptive trend-following tool uses Average True Range calculations to establish dynamic support and resistance levels that respond to market volatility.
**SMA Confirmation Matrix**: Multiple Simple Moving Averages (SMA 4, 5, 9, 13) provide layered confirmation for signal strength. The algorithm distinguishes between regular signals and "Strong" signals based on SMA 4 vs SMA 5 relationship, offering traders different conviction levels for position sizing.
**Trend Ribbon Visualization**: SMA 21 and SMA 34 create a visual trend ribbon that changes color based on their relationship. Green ribbon indicates bullish momentum while red signals bearish conditions, providing immediate visual trend context.
**RSI-Based Candle Coloring**: Advanced 61-tier RSI system colors candles with gradient precision from deep red (RSI ≤20) through purple transitions to bright green (RSI ≥79). This visual enhancement helps traders instantly assess momentum strength and overbought/oversold conditions.
Signal Generation Logic
**Buy Signal Criteria**:
- Price crosses above Supertrend line
- Close price must be above SMA 9 (trend confirmation)
- Signal strength determined by SMA 4 vs SMA 5 relationship
- "Strong Buy" when SMA 4 ≥ SMA 5
- Regular "Buy" when SMA 4 < SMA 5
**Sell Signal Criteria**:
- Price crosses below Supertrend line
- Close price must be below SMA 9 (trend confirmation)
- Signal strength based on SMA relationship
- "Strong Sell" when SMA 4 ≤ SMA 5
- Regular "Sell" when SMA 4 > SMA 5
Advanced Risk Management System
**Automated TP/SL Calculation**: The indicator automatically calculates stop loss and take profit levels using ATR-based measurements. Risk percentage and ATR length are fully customizable, allowing traders to adapt to different market conditions and personal risk tolerance.
**Multiple Take Profit Targets**:
- 1:1 Risk-Reward ratio for conservative profit taking
- 2:1 Risk-Reward for balanced trade management
- 3:1 Risk-Reward for maximum profit potential
**Visual Risk Display**: All risk management levels appear as both labels and optional trend lines on the chart. Customizable line styles (solid, dashed, dotted) and positioning ensure clear visualization without chart clutter.
**Dynamic Level Updates**: Risk levels automatically recalculate with each new signal, maintaining current market relevance throughout position lifecycles.
Visual Enhancement Features
**Customizable Display Options**: Toggle trend ribbon, TP/SL levels, and risk lines independently. Decimal precision adjustments (1-8 decimal places) accommodate different instrument price formats and personal preferences.
**Professional Label System**: Clean, informative labels show entry points, stop losses, and take profit targets with precise price levels. Labels automatically position themselves for optimal chart readability.
**Color-Coded Momentum**: The gradient RSI candle coloring system provides instant visual feedback on momentum strength, helping traders assess market energy and potential reversal zones.
Implementation Strategy
**Timeframe Optimization**: The algorithm performs effectively across multiple timeframes, with higher timeframes (4H, Daily) providing more reliable signals for swing trading. Lower timeframes work well for day trading with appropriate risk adjustments.
**Sensitivity Adjustment**: Lower sensitivity values (1-5) generate fewer but higher-quality signals, ideal for conservative approaches. Higher sensitivity (15-20) increases signal frequency for active trading styles.
**Risk Management Integration**: Use the automated risk calculations as baseline parameters, adjusting risk percentage based on account size and market conditions. The 1:1, 2:1, 3:1 targets enable systematic profit-taking strategies.
Market Application
**Trend Following Excellence**: Primary strength lies in capturing significant trend movements through the Supertrend foundation with SMA confirmation. The dual-layer approach reduces false signals common in single-indicator systems.
**Momentum Assessment**: RSI-based candle coloring provides immediate momentum context, helping traders assess signal strength and potential continuation probability.
**Range Detection**: The trend ribbon helps identify ranging conditions when SMA 21 and SMA 34 converge, alerting traders to potential breakout opportunities.
Performance Optimization
**Signal Quality**: The requirement for both Supertrend crossover AND SMA 9 confirmation significantly improves signal reliability compared to basic trend-following approaches.
**Visual Clarity**: The comprehensive visual system enables rapid market assessment without complex calculations, ideal for traders managing multiple instruments.
**Adaptability**: Extensive customization options allow fine-tuning for specific markets, trading styles, and risk preferences while maintaining the core algorithm integrity.
## Non-Repainting Design
**Educational Note**: This indicator uses standard PulseWire functions (Supertrend, SMA, RSI) with normal behavior patterns. Real-time updates on current candles are expected and standard across all technical indicators. Historical signals on closed candles remain fixed and unchanged, ensuring reliable backtesting and analysis.
**Signal Confirmation**: Final signals are confirmed only when candles close, following standard technical analysis principles. The algorithm provides clear distinction between developing signals and confirmed entries.
Technical Specifications
**Supertrend Parameters**: Default sensitivity of 4 with ATR length of 11 provides balanced signal generation. Sensitivity range from 1-20 allows adaptation to different market volatilities and trading preferences.
**Moving Average Configuration**: SMA periods of 8, 9, and 13 create multi-layered trend confirmation, while SMA 21 and 34 form the visual trend ribbon for broader market context.
**Risk Management**: ATR-based calculations with customizable risk percentage ensure dynamic adaptation to market volatility while maintaining consistent risk exposure principles.
Recommended Settings
**Conservative Approach**: Sensitivity 4-5, RSI length 14, higher timeframes (4H, Daily) for swing trading with maximum signal reliability.
**Active Trading**: Sensitivity 6-8, RSI length 8-10, intermediate timeframes (1H) for balanced signal frequency and quality.
**Scalping Setup**: Sensitivity 10-15, RSI length 5-8, lower timeframes (15-30min) with enhanced risk management protocols.
## Conclusion
The Mutanabby_AI Ultimate Algo Remastered+ combines proven trend-following principles with modern visual enhancements and comprehensive risk management. The algorithm's strength lies in its multi-layered confirmation approach and automated risk calculations, providing both novice and experienced traders with clear signals and systematic trade management.
Success with this system requires understanding the relationship between signal strength indicators and adapting sensitivity settings to match current market conditions. The comprehensive visual feedback system enables rapid decision-making while the automated risk management ensures consistent trade parameters.
Practice with different sensitivity settings and timeframes to optimize performance for your specific trading style and risk tolerance. The algorithm's systematic approach provides an excellent framework for disciplined trend-following strategies across various market environments. Indicator

Mutanabby_AI __ OSC+ST+SQZMOMMutanabby_AI OSC+ST+SQZMOM: Multi-Component Trading Analysis Tool
Overview
The Mutanabby_AI OSC+ST+SQZMOM indicator combines three proven technical analysis components into a unified trading system, providing comprehensive market analysis through integrated oscillator signals, trend identification, and volatility assessment.
Core Components
Wave Trend Oscillator (OSC): Identifies overbought and oversold market conditions using exponential moving average calculations. Key threshold levels include overbought zones at 60 and 53, with oversold areas marked at -60 and -53. Crossover signals between the two oscillator lines generate entry opportunities, displayed as colored circles on the chart for easy identification.
Supertrend Indicator (ST): Determines overall market direction using Average True Range calculations with a 2.5 factor and 10-period ATR configuration. Green lines indicate confirmed uptrends while red lines signal downtrend conditions. The indicator automatically adapts to market volatility changes, providing reliable trend identification across different market environments.
Squeeze Momentum (SQZMOM): Compares Bollinger Bands with Keltner Channels to identify consolidation periods and potential breakout scenarios. Black squares indicate squeeze conditions representing low volatility periods, green triangles signal confirmed upward breakouts, and red triangles mark downward breakout confirmations.
Signal Generation Logic
Long Entry Conditions:
Green triangles from Squeeze Momentum component
Supertrend line transitioning to green
Bullish crossovers in Wave Trend Oscillator from oversold territory
Short Entry Conditions:
Red triangles from Squeeze Momentum component
Supertrend line transitioning to red
Bearish crossovers in Wave Trend Oscillator from overbought territory
Automated Risk Management
The indicator incorporates comprehensive risk management through ATR-based calculations. Stop losses are automatically positioned at 3x ATR distance from entry points, while three progressive take profit targets are established at 1x, 2x, and 3x ATR multiples respectively. All risk management levels are clearly displayed on the chart using colored lines and informative labels.
When trend direction changes, the system automatically clears previous risk levels and generates new calculations, ensuring all risk parameters remain current and relevant to existing market conditions.
Alert and Notification System
Comprehensive alert framework includes trend change notifications with complete trade setup details, squeeze release alerts for breakout opportunity identification, and trend weakness warnings for active position management. Alert messages contain specific trading pair information, timeframe specifications, and all relevant entry and exit level data.
Implementation Guidelines
Timeframe Selection: Higher timeframes including 4-hour and daily charts provide the most reliable signals for position trading strategies. One-hour charts demonstrate good performance for day trading applications, while 15-30 minute timeframes enable scalping approaches with enhanced risk management requirements.
Risk Management Integration: Limit individual trade risk to 1-2% of total capital using the automatically calculated stop loss levels for precise position sizing. Implement systematic profit-taking at each target level while adjusting stop loss positions to protect accumulated gains.
Market Volatility Adaptation: The indicator's ATR-based calculations automatically adjust to changing market volatility conditions. During high volatility periods, risk management levels appropriately widen, while low volatility conditions result in tighter risk parameters.
Optimization Techniques
Combine indicator signals with fundamental support and resistance level analysis for enhanced signal validation. Monitor volume patterns to confirm breakout strength, particularly when Squeeze Momentum signals develop. Maintain awareness of scheduled economic events that may influence market behavior independent of technical indicator signals.
The multi-component design provides internal signal confirmation through multiple alignment requirements, significantly reducing false signal occurrence while maintaining reasonable trade frequency for active trading strategies.
Technical Specifications
The Wave Trend Oscillator utilizes customizable channel length (default 10) and average length (default 21) parameters for optimal market sensitivity. Supertrend calculations employ ATR period of 10 with factor multiplier of 2.5 for balanced signal quality. Squeeze Momentum analysis uses Bollinger Band length of 20 periods with 2.0 multiplication factor, combined with Keltner Channel length of 20 periods and 1.5 multiplication factor.
Conclusion
The Mutanabby_AI OSC+ST+SQZMOM indicator provides a systematic approach to technical market analysis through the integration of proven oscillator, trend, and momentum components. Success requires thorough understanding of each element's functionality and disciplined implementation of proper risk management principles.
Practice with demo trading accounts before live implementation to develop familiarity with signal interpretation and trade management procedures. The indicator's systematic approach effectively reduces emotional decision-making while providing clear, objective guidelines for trade entry, management, and exit strategies across various market conditions. Indicator

Momentum Regression [BackQuant]Momentum Regression
The Momentum Regression is an advanced statistical indicator built to empower quants, strategists, and technically inclined traders with a robust visual and quantitative framework for analyzing momentum effects in financial markets. Unlike traditional momentum indicators that rely on raw price movements or moving averages, this tool leverages a volatility-adjusted linear regression model (y ~ x) to uncover and validate momentum behavior over a user-defined lookback window.
Purpose & Design Philosophy
Momentum is a core anomaly in quantitative finance — an effect where assets that have performed well (or poorly) continue to do so over short to medium-term horizons. However, this effect can be noisy, regime-dependent, and sometimes spurious.
The Momentum Regression is designed as a pre-strategy analytical tool to help you filter and verify whether statistically meaningful and tradable momentum exists in a given asset. Its architecture includes:
Volatility normalization to account for differences in scale and distribution.
Regression analysis to model the relationship between past and present standardized returns.
Deviation bands to highlight overbought/oversold zones around the predicted trendline.
Statistical summary tables to assess the reliability of the detected momentum.
Core Concepts and Calculations
The model uses the following:
Independent variable (x): The volatility-adjusted return over the chosen momentum period.
Dependent variable (y): The 1-bar lagged log return, also adjusted for volatility.
A simple linear regression is performed over a large lookback window (default: 1000 bars), which reveals the slope and intercept of the momentum line. These values are then used to construct:
A predicted momentum trendline across time.
Upper and lower deviation bands , representing ±n standard deviations of the regression residuals (errors).
These visual elements help traders judge how far current returns deviate from the modeled momentum trend, similar to Bollinger Bands but derived from a regression model rather than a moving average.
Key Metrics Provided
On each update, the indicator dynamically displays:
Momentum Slope (β₁): Indicates trend direction and strength. A higher absolute value implies a stronger effect.
Intercept (β₀): The predicted return when x = 0.
Pearson’s R: Correlation coefficient between x and y.
R² (Coefficient of Determination): Indicates how well the regression line explains the variance in y.
Standard Error of Residuals: Measures dispersion around the trendline.
t-Statistic of β₁: Used to evaluate statistical significance of the momentum slope.
These statistics are presented in a top-right summary table for immediate interpretation. A bottom-right signal table also summarizes key takeaways with visual indicators.
Features and Inputs
✅ Volatility-Adjusted Momentum : Reduces distortions from noisy price spikes.
✅ Custom Lookback Control : Set the number of bars to analyze regression.
✅ Extendable Trendlines : For continuous visualization into the future.
✅ Deviation Bands : Optional ±σ multipliers to detect abnormal price action.
✅ Contextual Tables : Help determine strength, direction, and significance of momentum.
✅ Separate Pane Design : Cleanly isolates statistical momentum from price chart.
How It Helps Traders
📉 Quantitative Strategy Validation:
Use the regression results to confirm whether a momentum-based strategy is worth pursuing on a specific asset or timeframe.
🔍 Regime Detection:
Track when momentum breaks down or reverses. Slope changes, drops in R², or weak t-stats can signal regime shifts.
📊 Trade Filtering:
Avoid false positives by entering trades only when momentum is both statistically significant and directionally favorable.
📈 Backtest Preparation:
Before running costly simulations, use this tool to pre-screen assets for exploitable return structures.
When to Use It
Before building or deploying a momentum strategy : Test if momentum exists and is statistically reliable.
During market transitions : Detect early signs of fading strength or reversal.
As part of an edge-stacking framework : Combine with other filters such as volatility compression, volume surges, or macro filters.
Conclusion
The Momentum Regression indicator offers a powerful fusion of statistical analysis and visual interpretation. By combining volatility-adjusted returns with real-time linear regression modeling, it helps quantify and qualify one of the most studied and traded anomalies in finance: momentum. Indicator

Rolling Log Returns [BackQuant]Rolling Log Returns
The Rolling Log Returns indicator is a versatile tool designed to help traders, quants, and data-driven analysts evaluate the dynamics of price changes using logarithmic return analysis. Widely adopted in quantitative finance, log returns offer several mathematical and statistical advantages over simple returns, making them ideal for backtesting, portfolio optimization, volatility modeling, and risk management.
What Are Log Returns?
In quantitative finance, logarithmic returns are defined as:
ln(Pₜ / Pₜ₋₁)
or for rolling periods:
ln(Pₜ / Pₜ₋ₙ)
where P represents price and n is the rolling lookback window.
Log returns are preferred because:
They are time additive : returns over multiple periods can be summed.
They allow for easier statistical modeling , especially when assuming normally distributed returns.
They behave symmetrically for gains and losses, unlike arithmetic returns.
They normalize percentage changes, making cross-asset or cross-timeframe comparisons more consistent.
Indicator Overview
The Rolling Log Returns indicator computes log returns either on a standard (1-period) basis or using a rolling lookback period , allowing users to adapt it to short-term trading or long-term trend analysis.
It also supports a comparison series , enabling traders to compare the return structure of the main charted asset to another instrument (e.g., SPY, BTC, etc.).
Core Features
✅ Return Modes :
Normal Log Returns : Measures ln(price / price ), ideal for day-to-day return analysis.
Rolling Log Returns : Measures ln(price / price ), highlighting price drift over longer horizons.
✅ Comparison Support :
Compare log returns of the primary instrument to another symbol (like an index or ETF).
Useful for relative performance and market regime analysis .
✅ Moving Averages of Returns :
Smooth noisy return series with customizable MA types: SMA, EMA, WMA, RMA, and Linear Regression.
Applicable to both primary and comparison series.
✅ Conditional Coloring :
Returns > 0 are colored green ; returns < 0 are red .
Comparison series gets its own unique color scheme.
✅ Extreme Return Detection :
Highlight unusually large price moves using upper/lower thresholds.
Visually flags abnormal volatility events such as earnings surprises or macroeconomic shocks.
Quantitative Use Cases
🔍 Return Distribution Analysis :
Gain insight into the statistical properties of asset returns (e.g., skewness, kurtosis, tail behavior).
📉 Risk Management :
Use historical return outliers to define drawdown expectations, stress tests, or VaR simulations.
🔁 Strategy Backtesting :
Apply rolling log returns to momentum or mean-reversion models where compounding and consistent scaling matter.
📊 Market Regime Detection :
Identify periods of consistent overperformance/underperformance relative to a benchmark asset.
📈 Signal Engineering :
Incorporate return deltas, moving average crossover of returns, or threshold-based triggers into machine learning pipelines or rule-based systems.
Recommended Settings
Use Normal mode for high-frequency trading signals.
Use Rolling mode for swing or trend-following strategies.
Compare vs. a broad market index (e.g., SPY or QQQ ) to extract relative strength insights.
Set upper and lower thresholds around ±5% for spotting major volatility days.
Conclusion
The Rolling Log Returns indicator transforms raw price action into a statistically sound return series—equipping traders with a professional-grade lens into market behavior. Whether you're conducting exploratory data analysis, building factor models, or visually scanning for outliers, this indicator integrates seamlessly into a modern quant's toolbox. Indicator

Cumulative Intraday Volume with Long/Short LabelsThis indicator calculates a running total of volume for each trading day, then shows on the price chart when that total crosses levels you choose. Every day at 6:00 PM Eastern Time, the total goes back to zero so it always reflects only the current day’s activity. From that moment on, each time a new candle appears the indicator looks at whether the candle closed higher than it opened or lower. If it closed higher, the candle’s volume is added to the running total; if it closed lower, the same volume amount is subtracted. As a result, the total becomes positive when buyers have dominated so far today and negative when sellers have dominated.
Because futures markets close at 6 PM ET, the running total resets exactly then, mirroring the way most intraday traders think in terms of a single session. Throughout the day, you will see this running total move up or down according to whether more volume is happening on green or red candles. Once the total goes above a number you specify (for example, one hundred thousand contracts), the indicator will place a small “Long” label at that candle on the main price chart to let you know buying pressure has reached that level. Similarly, once the total goes below a negative number you choose (for example, minus one hundred thousand), a “Short” label will appear at that candle to signal that selling pressure has reached your chosen threshold. You can set these threshold numbers to whatever makes sense for your trading style or the market you follow.
Because raw volume alone never turns negative, this design uses candle direction as a sign. Green candles (where the close is higher than the open) add volume, and red candles (where the close is lower than the open) subtract volume. Summing those signed volume values tells you in a single number whether buying or selling has been stronger so far today. That number resets every evening, so it does not carry over any buying or selling from previous sessions.
Once you have this indicator on your chart, you simply watch the “summed volume” line as it moves throughout the day. If it climbs past your long threshold, you know buyers are firmly in control and a long entry might make sense. If it falls past your short threshold, you know sellers are firmly in control and a short entry might make sense. In quieter markets or times of low volume, you might use a smaller threshold so that even modest buying or selling pressure will trigger a label. During very active periods, a larger threshold will prevent too many signals when volume spikes frequently.
This approach is straightforward but can be surprisingly powerful. It does not rely on complex formulas or hidden statistical measures. Instead, it simply adds and subtracts daily volume based on candle color, then alerts you when that total reaches levels you care about. Over several years of historical testing, this formula has shown an ability to highlight moments when intraday sentiment shifts decisively from buyers to sellers or vice versa. Because the indicator resets every day at 6 PM, it always reflects only today’s sentiment and remains easy to interpret without carrying over past data. You can use it on any intraday timeframe, but it works especially well on five-minute or fifteen-minute charts for futures contracts.
If you want a clear gauge of whether buyers or sellers are dominating in real time, and you prefer a rule-based method rather than a complex model, this indicator gives you exactly that. It shows net buying or selling pressure at a glance, resets each session like most intraday traders do, and marks the moments when that pressure crosses the levels you decide are important. By combining a daily reset with signed volume, you get a single number that tells you precisely what the crowd is doing at any given moment, without any of the guesswork or hidden calculations that more complicated indicators often carry.
Indicator

Indicator

Normalized Price ComparisonNormalized Price Comparison Indicator Description
The "Normalized Price Comparison" indicator is designed to provide traders with a visual tool for comparing the price movements of up to three different financial instruments on a common scale, despite their potentially different price ranges. Here's how it works:
Features:
Normalization: This indicator normalizes the closing prices of each symbol to a scale between 0 and 1 over a user-defined period. This normalization process allows for the comparison of price trends regardless of the absolute price levels, making it easier to spot relative movements and trends.
Crossing Alert: It features an alert functionality that triggers when the normalized price lines of the first two symbols (Symbol 1 and Symbol 2) cross each other. This can be particularly useful for identifying potential trading opportunities when one asset's relative performance changes against another.
Customization: Users can input up to three symbols for analysis. The normalization period can be adjusted, allowing flexibility in how historical data is considered for the scaling process. This period determines how many past bars are used to calculate the minimum and maximum prices for normalization.
Visual Representation: The indicator plots these normalized prices in a separate pane below the main chart. Each symbol's normalized price is represented by a distinct colored line:
Symbol 1: Blue line
Symbol 2: Red line
Symbol 3: Green line
Use Cases:
Relative Performance Analysis: Ideal for investors or traders who want to compare how different assets are performing relative to each other over time, without the distraction of absolute price differences.
Divergence Detection: Useful for spotting divergences where one asset might be outperforming or underperforming compared to others, potentially signaling changes in market trends or investment opportunities.
Crossing Strategy: The alert for when Symbol 1 and Symbol 2's normalized lines cross can be used as a part of a trading strategy, signaling potential entry or exit points based on relative price movements.
Limitations:
Static Alert Messages: Due to Pine Script's constraints, the alert messages cannot dynamically include the names of the symbols being compared. The alert will always mention "Symbol 1" and "Symbol 2" crossing.
Performance: Depending on the timeframe and the number of symbols, performance might be affected, especially on lower timeframes with high data frequency.
This indicator is particularly beneficial for those interested in multi-asset analysis, offering a streamlined way to observe and react to relative price movements in a visually coherent manner. It's a powerful tool for enhancing your trading or investment analysis by focusing on trends and relationships rather than raw price data.
Indicator
