Indicator · Pine Script v6 · Own pane

Market Memory & Decay Oscillator [WavesUnchained]

by casoon

Calculates a composite carry and decay oscillator fusing impulse-autocorrelation half-life, a Hurst exponent approximation, path efficiency, and range expansion ratios.

View on GitHub

GitHub stars9on the repository
Pine versionv6current
Lines of code218
Settings10inputs
LicenceMIT
Last updateyesterday27 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

218 lines of Pine Script v6 from indicators/trend_strength/market_memory_decay_oscillator/market_memory_decay_oscillator.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

market_memory_decay_oscillator.pine
//@version=6
// ============================================================================
// Market Memory & Decay Oscillator [WavesUnchained]
// Version: 1.2.1
// Author: WavesUnchained
// Build: 2026-10-02 00:00:00
// ============================================================================
// Signed oscillator fusing impulse-autocorrelation half-life, a Hurst-exponent
// approximation, path efficiency and range expansion into a single carry/decay
// read on how long the current impulse is likely to persist before mean-reverting.
//
// Features:
//   ✓ Half-life from the smoothed impulse line's autocorrelation (clamped)
//   ✓ Hurst exponent approximation (persistent vs. mean-reverting regime)
//   ✓ Path efficiency (direct move vs. total travelled distance)
//   ✓ Range expansion / decay via fast-vs-slow ATR ratio
//   ✓ Composite Memory Strength vs. Decay Pressure score
//   ✓ Bullish/Bearish Carry and Decay regime states with background shading
//   ✓ Impulse markers on Z-score threshold breach
//   ✓ Light-theme dashboard (score, state, half-life, impulse age, Hurst, efficiency, range ratio)
//   ✓ Bullish/Bearish Carry and Impulse Decay alerts
//
// ============================================================================

indicator("Market Memory & Decay Oscillator [WavesUnchained]", "MMDO [WU]", format=format.price, precision=2, overlay=false, max_labels_count=100)

//------------------------------------------------------------------------------
// Inputs
//------------------------------------------------------------------------------
src = input.source(close, "Source")

memoryLen   = input.int(64, "Memory Length", minval=20)
fastLen     = input.int(16, "Fast Impulse Length", minval=5)
slowLen     = input.int(96, "Slow Context Length", minval=30)
smoothLen   = input.int(8, "Score Smoothing", minval=1)

impulseZ    = input.float(1.2, "Impulse Z-Threshold", step=0.1)
maxHalfLife = input.float(48.0, "Max Half-Life Clamp", step=1.0)

showZones      = input.bool(true, "Show Zones")
showImpulse    = input.bool(true, "Show Impulse Markers")
showDashboard  = input.bool(true, "Show Dashboard")

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
f_clamp(x, lo, hi) =>
    math.max(lo, math.min(hi, x))

f_safeDiv(a, b, fallback) =>
    b != 0.0 and not na(b) ? a / b : fallback

f_norm(x, scale) =>
    f_clamp(x / scale, -1.0, 1.0)

//------------------------------------------------------------------------------
// Returns / Impulse
//------------------------------------------------------------------------------
ret = math.log(src / src[1])

retMean = ta.sma(ret, memoryLen)
retSd   = ta.stdev(ret, memoryLen)
retZ    = f_safeDiv(ret - retMean, retSd, 0.0)

impulseRaw = ta.ema(retZ, fastLen)
impulseDir = impulseRaw > 0 ? 1.0 : impulseRaw < 0 ? -1.0 : 0.0
impulseStrength = f_clamp(math.abs(impulseRaw) / 2.5, 0.0, 1.0)

newImpulse = math.abs(retZ) > impulseZ
barsFromImpulse = ta.barssince(newImpulse)
age = na(barsFromImpulse) ? 999.0 : barsFromImpulse

//------------------------------------------------------------------------------
// Memory via Autocorrelation / Half-Life
// Measured on the smoothed impulse line, not raw returns: lag-1 autocorrelation
// of raw returns sits near 0, which collapsed the half-life to a fraction of a
// bar. The impulse EMA's own memory sets a floor of about ln(2)·(fastLen+1)/2
// bars; return persistence lengthens it from there.
//------------------------------------------------------------------------------
phi = ta.correlation(impulseRaw, impulseRaw[1], memoryLen)

persistentPhi = f_clamp(nz(phi), 0.0, 0.98)
halfLife = persistentPhi > 0.01 ? -math.log(2.0) / math.log(persistentPhi) : 0.0
halfLife := f_clamp(halfLife, 0.0, maxHalfLife)

decayCurve = halfLife > 0 ? math.exp(-age / halfLife) : 0.0
halfLifeScore = f_clamp(halfLife / maxHalfLife, 0.0, 1.0)

//------------------------------------------------------------------------------
// Hurst Approximation — single-window rescaled range on returns:
// R = range of cumulative deviations of returns from their mean, S = stdev of returns
//------------------------------------------------------------------------------
float cumDev = 0.0
float cumMax = 0.0
float cumMin = 0.0
for i = 0 to memoryLen - 1
    cumDev += nz(ret[i]) - nz(retMean)
    cumMax := math.max(cumMax, cumDev)
    cumMin := math.min(cumMin, cumDev)
rs = f_safeDiv(cumMax - cumMin, retSd, 1.0)
hurst = f_clamp(math.log(math.max(rs, 1.0)) / math.log(memoryLen), 0.0, 1.0)

hurstMemory = f_clamp((hurst - 0.50) * 2.5, -1.0, 1.0)

//------------------------------------------------------------------------------
// Path Efficiency
//------------------------------------------------------------------------------
direct = math.abs(src - src[memoryLen])
path = ta.sum(math.abs(src - src[1]), memoryLen)
efficiency = f_safeDiv(direct, path, 0.0)
effScore = f_clamp((efficiency - 0.20) * 2.0, 0.0, 1.0)

//------------------------------------------------------------------------------
// Range Expansion / Decay
//------------------------------------------------------------------------------
tr = ta.tr(true)
rangeFast = ta.ema(tr, fastLen)
rangeSlow = ta.ema(tr, slowLen)

rangeRatio = f_safeDiv(rangeFast, rangeSlow, 1.0)
rangeExpansion = f_clamp((rangeRatio - 1.0) / 0.8, 0.0, 1.0)
rangeDecay = f_clamp((1.0 - rangeRatio) / 0.45, 0.0, 1.0)

//------------------------------------------------------------------------------
// Composite Memory / Decay
//------------------------------------------------------------------------------
memoryStrength =
     halfLifeScore * 0.35 +
     math.max(hurstMemory, 0.0) * 0.25 +
     effScore * 0.25 +
     rangeExpansion * 0.15

decayPressure =
     rangeDecay * 0.35 +
     f_clamp(age / maxHalfLife, 0.0, 1.0) * 0.25 +
     math.max(-hurstMemory, 0.0) * 0.25 +
     f_clamp(1.0 - efficiency * 3.0, 0.0, 1.0) * 0.15

carryRaw = impulseDir * impulseStrength * memoryStrength * decayCurve * 100.0
decayRaw = impulseDir * decayPressure * impulseStrength * 100.0

mmdo = ta.ema(carryRaw - decayRaw * 0.55, smoothLen)
decayLine = ta.ema(decayRaw, smoothLen)
memoryLine = ta.ema(impulseDir * memoryStrength * 100.0, smoothLen)

//------------------------------------------------------------------------------
// Regime
//------------------------------------------------------------------------------
carryBull = mmdo > 25
carryBear = mmdo < -25
decaying = math.abs(decayLine) > math.abs(memoryLine) * 0.65 and math.abs(mmdo) < math.abs(memoryLine)

stateText =
     carryBull and not decaying ? "BULLISH CARRY" :
     carryBear and not decaying ? "BEARISH CARRY" :
     decaying                  ? "DECAY" :
                                 "NO EDGE"

scoreColor = color.from_gradient(mmdo, -100, 100, color.rgb(220, 75, 95), color.rgb(40, 180, 120))
decayColor = color.rgb(240, 170, 65)

//------------------------------------------------------------------------------
// Visuals
//------------------------------------------------------------------------------
h100 = hline(100, "Upper Limit", color=color.new(color.gray, 92))
h60  = hline(60, "Strong Carry", color=color.new(color.green, 76))
h25  = hline(25, "Carry Threshold", color=color.new(color.green, 84))
h0   = hline(0, "Zero", color=color.new(color.white, 45))
hm25 = hline(-25, "Bear Carry Threshold", color=color.new(color.red, 84))
hm60 = hline(-60, "Strong Bear Carry", color=color.new(color.red, 76))
hm100 = hline(-100, "Lower Limit", color=color.new(color.gray, 92))

fill(h25, h60, color=showZones ? color.new(color.green, 94) : na)
fill(h60, h100, color=showZones ? color.new(color.green, 90) : na)
fill(hm25, hm60, color=showZones ? color.new(color.red, 94) : na)
fill(hm60, hm100, color=showZones ? color.new(color.red, 90) : na)

plot(mmdo, "Memory & Decay Score", color=scoreColor, linewidth=3)
plot(memoryLine, "Memory Potential", color=color.new(color.aqua, 40), linewidth=1)
plot(decayLine, "Decay Pressure", color=color.new(decayColor, 25), linewidth=2)

plot(showImpulse and newImpulse ? impulseDir * 95 : na, "Impulse Marker", style=plot.style_circles, color=color.new(scoreColor, 0), linewidth=3)

bgcolor(carryBull ? color.new(color.green, 93) : carryBear ? color.new(color.red, 93) : decaying ? color.new(color.orange, 92) : na)

//------------------------------------------------------------------------------
// Dashboard
//------------------------------------------------------------------------------
var table dash = table.new(position.top_right, 2, 7, border_width=1)

if showDashboard and barstate.islast
    table.cell(dash, 0, 0, "MMDO", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 0, str.tostring(mmdo, "#.0"), text_color=color.white, bgcolor=color.new(scoreColor, 18))

    table.cell(dash, 0, 1, "State", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 1, stateText, text_color=color.white, bgcolor=color.new(scoreColor, 35))

    table.cell(dash, 0, 2, "Half-Life", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 2, str.tostring(halfLife, "#.0") + " bars", text_color=color.white, bgcolor=color.new(color.gray, 75))

    table.cell(dash, 0, 3, "Impulse Age", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 3, str.tostring(age, "#"), text_color=color.white, bgcolor=color.new(color.gray, 75))

    table.cell(dash, 0, 4, "Hurst", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 4, str.tostring(hurst, "#.00"), text_color=color.white, bgcolor=color.new(color.gray, 75))

    table.cell(dash, 0, 5, "Efficiency", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 5, str.tostring(efficiency * 100, "#.0") + "%", text_color=color.white, bgcolor=color.new(color.gray, 75))

    table.cell(dash, 0, 6, "Range Ratio", text_color=color.white, bgcolor=color.new(color.black, 0))
    table.cell(dash, 1, 6, str.tostring(rangeRatio, "#.00"), text_color=color.white, bgcolor=color.new(color.gray, 75))

//------------------------------------------------------------------------------
// Alerts
//------------------------------------------------------------------------------
alertcondition(ta.crossover(mmdo, 25), "Bullish Carry", "MMDO entered bullish carry regime.")
alertcondition(ta.crossunder(mmdo, -25), "Bearish Carry", "MMDO entered bearish carry regime.")
alertcondition(decaying, "Impulse Decay", "MMDO detects impulse decay.")

Overview

Market Memory & Decay Oscillator [WavesUnchained] evaluates whether an impulse is likely to persist or mean-revert, plotting the oscillator in a separate pane alongside background regime zones. Markers appear when return Z-scores breach a user-defined threshold. Inputs adjust memory, impulse, and context lengths, smoothing, threshold sensitivity, and the display of markers and the dashboard.

Details

Published by

casoon on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Oscillators & momentum, Mean reversion, Screeners & dashboards

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

pine-scriptpinescripttechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosesrc
Memory Lengthint64memoryLen
Fast Impulse Lengthint16fastLen
Slow Context Lengthint96slowLen
Score Smoothingint8smoothLen
Impulse Z-Thresholdfloat1.2impulseZ
Max Half-Life Clampfloat48.0maxHalfLife
Show ZonesbooltrueshowZones
Show Impulse MarkersbooltrueshowImpulse
Show DashboardbooltrueshowDashboard
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

KamaFama

by Mastaaa1987
141 stars

KamaFama is an indicator that translates a Freqtrade trading strategy into Pine Script for visualization. It combines Kaufman Adaptive Moving Average (KAMA), MAMA/FAMA calculations derived via Hilbert Transform, Williams %R, and correlation trend filters to ev

Indicator v6 Moving averagesOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of KamaFama
114 stars

Calculates normalized reversal metrics across up to ten Forex currency pairs using user-selected moving average methods, including HarmonicMA, EMA, SMA, or WMA. The indicator identifies overbought, oversold, and mean-crossing conditions using a configurable th

Indicator v4 Screeners & dashboardsMean reversion
Updated 1 year ago · None stated GitHub repository of Multi-Pair Trend Reversal Widget
99 stars

This indicator calculates the statistical autocorrelation coefficient of an input series over a user-defined lookback window at a specified lag. It tracks values using an internal circular buffer, computes sample mean, variance, and autocovariance, and normali

Indicator v6 TrendMean reversion
Updated 4 weeks ago · Apache-2.0 GitHub repository of Autocorrelation Function (ACF)

Manias, Panics and Crashes

by MeridianAlgo
9 stars

Manias, Panics and Crashes is a separate-pane market regime indicator that quantifies market sentiment and systemic risk. It processes technical metrics including RSI, moving averages, and volume alongside optional intermarket data such as VIX volatility and c

Indicator v6 Oscillators & momentumVolatility & bands
Updated 4 months ago · MIT GitHub repository of Manias, Panics and Crashes

Nexural Pressure Pro

by JasonTeixeira
9 stars

Nexural Pressure Pro is a composite pressure indicator that measures directional market momentum using volume-weighted directional movement, order flow delta, aggression, and efficiency ratio metrics. It filters out low-activity bars using configurable volume

Indicator v6 Oscillators & momentumVolume
Updated 12 days ago · Custom licence GitHub repository of Nexural Pressure Pro

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers