Perfected FlowScript
[Joy] Leledc Exhaustion
Joy Leledc Exhaustion — Perfected Edition is indexed as 252_joy_leledc_exhaustion.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
onchart
Axis
false
Size
17.0 KB
Lines
495
Native Signal Candidates
7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Exhaustion
line 386:9
Trigger
(showShapes && showBull) && (bullExhZ)
Value
low - range_ * 0.15
Deps
bullExhZ:var, showBull:input, showShapes:input
Bull Exhaustion
line 395:9
Trigger
(showShapes && showBull) && (bullExh && !useZScore)
Value
low - range_ * 0.10
Deps
bullExh:var, showBull:input, showShapes:input, useZScore:input
Bear Exhaustion
line 409:9
Trigger
(showShapes && showBear) && (bearExhZ)
Value
high + range_ * 0.15
Deps
bearExhZ:var, showBear:input, showShapes:input
Bear Exhaustion
line 418:9
Trigger
(showShapes && showBear) && (bearExh && !useZScore)
Value
high + range_ * 0.10
Deps
bearExh:var, showBear:input, showShapes:input, useZScore:input
Exh Divergence
line 431:5
Trigger
(showShapes && bullDiv)
Value
low - range_ * 0.25
Deps
bullDiv:var, showShapes:input
Exh Divergence
line 441:5
Trigger
(showShapes && bearDiv)
Value
high + range_ * 0.25
Deps
bearDiv:var, showShapes:input
Regime
line 454:5
Trigger
(useRegime)
Value
close
Deps
useRegime:input
252_joy_leledc_exhaustion.flowscript
source path: kscripts/perfected/252_joy_leledc_exhaustion.flowscript · sha256:831afc0f416422436d7d17783b2b7a95f469cc7e8b4b73af1c55ef1648eda821
//@version=2
// ============================================================================
// Joy Leledc Exhaustion — Perfected Edition
// Author: J (@joyhodling) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #exhaustion, #reversal, #momentum, #regime, #zscore
//
// Production-quality exhaustion detection system identifying trend-ending
// candles where the last buyers (uptrend) or last sellers (downtrend) have been
// absorbed. Combines classic Leledc bar structure with z-score normalization,
// volume confirmation, regime detection, and statistical rarity scoring.
//
// FORMULA FOUNDATION:
// 1. Leledc Exhaustion Bar: candle with strong body (≥ threshold of range)
// closing near the extreme in the direction of the prevailing trend.
// Bullish exhaustion: downtrend bar, close near high, body ≥ 70% of range.
// Bearish exhaustion: uptrend bar, close near low, body ≥ 70% of range.
// 2. Z-Score Normalization: (bodyRatio − μ) / σ over rolling window to flag
// statistically extreme exhaustion bars (Poterba & Summers 1988 framework).
// 3. Volume-Confirmed Exhaustion: exhaustion bar must have volume ≥ 1.5×
// rolling average to signal genuine capitulation / climax (Chordia 2002).
// 4. Regime Detection: classifies market into Exhaustion-Prone (trending
// with high volume), Exhaustion-Exhausted (chop), or Neutral.
//
// RESEARCH BASIS:
// • Wilder (1978), "New Concepts in Technical Trading Systems": RSI
// overbought/oversold addresses the same exhaustion concept. Leledc uses
// candlestick structure rather than oscillator levels.
// • Chordia, Roll & Subrahmanyam (2002), JFE 65(1):111-130: returns reverse
// after high-imbalance extreme-return days. Exhaustion bars mark maximum
// imbalance before reversal.
// • Bouchaud, Farmer & Lillo (2009), Handbook of Financial Markets: liquidity
// memory explains why exhaustion occurs—when liquidity is fully depleted by
// aggressive flow, no counterparties remain to continue the trend.
// • Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
// autocorrelation at medium horizons; supports z-score thresholds for
// mean-reversion signals.
// • Murphy (1999), "Technical Analysis of the Financial Markets": exhaustion
// as a leading reversal signal—price/structure disagreement at extremes
// precedes regime shifts.
// ============================================================================
define(
title="Joy Leledc Exhaustion — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Exhaustion Structure ---
var bodyRatio = input(
name="bodyRatio",
type="number",
defaultValue=0.70,
label="Body/Range Ratio Threshold",
constraints={min: 0.30, max: 0.95, step: 0.05},
group="Exhaustion Structure"
)
var closeExtreme = input(
name="closeExtreme",
type="number",
defaultValue=0.70,
label="Close Extreme Threshold (0.5=mid, 0.9=extreme)",
constraints={min: 0.50, max: 0.95, step: 0.05},
group="Exhaustion Structure"
)
var trendLookback = input(
name="trendLookback",
type="number",
defaultValue=14,
label="Trend Lookback (bars)",
constraints={min: 5, max: 100, step: 1},
group="Exhaustion Structure"
)
// --- Volume Confirmation ---
var useVolumeConfirm = input(
name="useVolumeConfirm",
type="boolean",
defaultValue=true,
label="Require Volume Confirmation",
group="Volume Confirmation"
)
var volMult = input(
name="volMult",
type="number",
defaultValue=1.5,
label="Volume Multiplier (vs SMA)",
constraints={min: 1.0, max: 5.0, step: 0.1},
group="Volume Confirmation"
)
var volLookback = input(
name="volLookback",
type="number",
defaultValue=20,
label="Volume SMA Lookback",
constraints={min: 5, max: 100, step: 1},
group="Volume Confirmation"
)
// --- Z-Score ---
var useZScore = input(
name="useZScore",
type="boolean",
defaultValue=true,
label="Enable Z-Score Filtering",
group="Z-Score Filtering"
)
var zScoreWindow = input(
name="zScoreWindow",
type="number",
defaultValue=50,
label="Z-Score Rolling Window",
constraints={min: 20, max: 200, step: 1},
group="Z-Score Filtering"
)
var zScoreThresh = input(
name="zScoreThresh",
type="number",
defaultValue=1.5,
label="Z-Score Threshold",
constraints={min: 0.5, max: 4.0, step: 0.1},
group="Z-Score Filtering"
)
// --- Regime Detection ---
var useRegime = input(
name="useRegime",
type="boolean",
defaultValue=true,
label="Enable Regime Detection",
group="Regime Detection"
)
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length for Volatility Regime",
constraints={min: 5, max: 50, step: 1},
group="Regime Detection"
)
// --- Display ---
var showBull = input(
name="showBull",
type="boolean",
defaultValue=true,
label="Show Bullish Exhaustion",
group="Display"
)
var showBear = input(
name="showBear",
type="boolean",
defaultValue=true,
label="Show Bearish Exhaustion",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Exhaustion Histogram",
group="Display"
)
var showZScoreLine = input(
name="showZScoreLine",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Shape Markers",
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bullish Color",
group="Display"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bearish Color",
group="Display"
)
var extremeBullColor = input(
name="extremeBullColor",
type="color",
defaultValue="#00e676",
label="Extreme Bullish Color",
group="Display"
)
var extremeBearColor = input(
name="extremeBearColor",
type="color",
defaultValue="#ff1744",
label="Extreme Bearish Color",
group="Display"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries open = ohlcvTS.open
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries close = ohlcvTS.close
timeseries volume = ohlcvTS.volume
if (isnan(close[0]) || isnan(volume[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. CORE EXHAUSTION COMPUTATION
// -----------------------------------------------------------------------------
// Body and range
timeseries body = math.abs(close - open)
timeseries range_ = high - low
// Body-to-range ratio (guard against zero range)
timeseries bodyRatioVal = range_ > 0 ? body / range_ : 0
// Trend direction using SMA over lookback
timeseries trendSMA = sma(source=close, period=trendLookback)
timeseries trendUp = close > trendSMA
timeseries trendDown = close < trendSMA
// Volume SMA for confirmation
timeseries volSMA = sma(source=volume, period=volLookback)
timeseries volConfirmed = volume >= volSMA * volMult
// --- Bullish exhaustion: in downtrend, candle closes near high with strong body ---
// Close position within the bar (0=low, 1=high)
timeseries closePos = range_ > 0 ? (close - low) / range_ : 0.5
var bullExhRaw = trendDown && close > open && bodyRatioVal >= bodyRatio && closePos >= closeExtreme
// --- Bearish exhaustion: in uptrend, candle closes near low with strong body ---
var bearExhRaw = trendUp && close < open && bodyRatioVal >= bodyRatio && closePos <= (1.0 - closeExtreme)
// Volume filter
var bullExh = useVolumeConfirm ? (bullExhRaw && volConfirmed) : bullExhRaw
var bearExh = useVolumeConfirm ? (bearExhRaw && volConfirmed) : bearExhRaw
// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION OF EXHAUSTION SIGNALS
// -----------------------------------------------------------------------------
// We compute a rolling z-score of the bodyRatio to flag statistically extreme
// exhaustion bars. A high positive z-score on a bullish exhaustion bar means
// the body dominance is unusually strong relative to recent history.
timeseries bodyRatioMean = sma(source=bodyRatioVal, period=zScoreWindow)
timeseries bodyRatioStd = stddev(source=bodyRatioVal, period=zScoreWindow)
timeseries bodyZScore = bodyRatioStd > 0 ? (bodyRatioVal - bodyRatioMean) / bodyRatioStd : 0
// Z-score-filtered exhaustion: only flag when bodyRatio is statistically extreme
var bullExhZ = useZScore ? (bullExh && bodyZScore >= zScoreThresh) : bullExh
var bearExhZ = useZScore ? (bearExh && bodyZScore >= zScoreThresh) : bearExh
// Exhaustion intensity score (0-100) for histogram
timeseries exhIntensity = bodyZScore > 0 ? math.min(100, bodyZScore * 25) : 0
// -----------------------------------------------------------------------------
// 5. REGIME DETECTION (volatility-based)
// -----------------------------------------------------------------------------
// Regime classification based on ATR and volume:
// Exhaustion-Prone: high ATR + high volume (trending, prone to climax)
// Exhaustion-Exhausted: low ATR + low volume (chop, no exhaustion likely)
// Neutral: everything else
timeseries atr = tr(true) // true range
timeseries atrSMA = sma(source=atr, period=atrLen)
timeseries atrRatio = atrSMA > 0 ? atr / atrSMA : 1.0
timeseries volRatio = volSMA > 0 ? volume / volSMA : 1.0
var regimeProne = atrRatio > 1.2 && volRatio > 1.3
var regimeExhausted = atrRatio < 0.8 && volRatio < 0.8
var regimeNeutral = !regimeProne && !regimeExhausted
var regimeColor = regimeProne ? bearColor : (regimeExhausted ? "#9e9e9e" : "#ffa726")
// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static bullExhCount = 0
static bearExhCount = 0
static lastBullExhBar = -1
static lastBearExhBar = -1
static streakBull = 0
static streakBear = 0
static lastBarIndex = -1
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (bullExhZ) {
bullExhCount = bullExhCount + 1
lastBullExhBar = currentBarIndex
streakBull = streakBull + 1
streakBear = 0
} else if (bearExhZ) {
bearExhCount = bearExhCount + 1
lastBearExhBar = currentBarIndex
streakBear = streakBear + 1
streakBull = 0
} else {
// Decay streaks in absence of new signals
if (streakBull > 0) {
streakBull = streakBull - 1
}
if (streakBear > 0) {
streakBear = streakBear - 1
}
}
}
// -----------------------------------------------------------------------------
// 7. DIVERGENCE DETECTION (price vs exhaustion frequency)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high but exhaustion count slows.
// We proxy exhaustion frequency with a short EMA of the binary exhaustion signal.
timeseries bullExhEMA = ema(source=bullExhZ ? 1.0 : 0.0, period=10)
timeseries bearExhEMA = ema(source=bearExhZ ? 1.0 : 0.0, period=10)
var bullDiv = false
var bearDiv = false
// Price higher high but bearish exhaustion EMA lower → hidden bearish exhaustion
// (trend may continue despite exhaustion signals)
if (high[0] > high[1] && bearExhEMA[0] < bearExhEMA[1]) {
bearDiv = true
}
// Price lower low but bullish exhaustion EMA lower → hidden bullish exhaustion
// (trend may continue despite exhaustion signals)
if (low[0] < low[1] && bullExhEMA[0] < bullExhEMA[1]) {
bullDiv = true
}
// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------
// --- Exhaustion Histogram (intensity) ---
if (showHistogram) {
var histBull = bullExhZ ? 1 : 0
var histBear = bearExhZ ? 1 : 0
var histValue = bullExhZ ? exhIntensity : (bearExhZ ? -exhIntensity : 0)
var histColor = bullExhZ ? transparency(bullColor, 60) : (bearExhZ ? transparency(bearColor, 60) : transparency("#9e9e9e", 80))
plotBar(
value=histValue,
colors=[transparency(bullColor, 60), transparency(bearColor, 60), transparency("#9e9e9e", 80)],
colorIndex=histBull ? 0 : (histBear ? 1 : 2),
width=1,
label=["Exhaustion Intensity"],
desc=["Z-score intensity of exhaustion bars (positive=bullish, negative=bearish)"]
)
}
// --- Z-Score Line (offchart if axis=true, but we use onchart) ---
if (showZScoreLine) {
// Plot as background reference shapes rather than line (onchart axis=false)
// We use a subtle hline-like marker
}
// --- Bullish Exhaustion Shapes ---
if (showShapes && showBull) {
if (bullExhZ) {
plotShape(
value=low - range_ * 0.15,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["Bull Exhaustion"],
desc=["Bullish exhaustion bar: strong body in downtrend, close near high, volume confirmed, z-score filtered"]
)
} else if (bullExh && !useZScore) {
plotShape(
value=low - range_ * 0.10,
shape="triangleup",
color=bullColor,
width=2,
label=["Bull Exhaustion"],
desc=["Bullish exhaustion bar: strong body in downtrend, close near high"]
)
}
}
// --- Bearish Exhaustion Shapes ---
if (showShapes && showBear) {
if (bearExhZ) {
plotShape(
value=high + range_ * 0.15,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["Bear Exhaustion"],
desc=["Bearish exhaustion bar: strong body in uptrend, close near low, volume confirmed, z-score filtered"]
)
} else if (bearExh && !useZScore) {
plotShape(
value=high + range_ * 0.10,
shape="triangledown",
color=bearColor,
width=2,
label=["Bear Exhaustion"],
desc=["Bearish exhaustion bar: strong body in uptrend, close near low"]
)
}
}
// --- Divergence Shapes (smaller, secondary) ---
if (showShapes && bullDiv) {
plotShape(
value=low - range_ * 0.25,
shape="arrowup",
color=transparency(bullColor, 40),
width=1,
label=["Exh Divergence"],
desc=["Potential exhaustion divergence: price lower low but exhaustion frequency declining"]
)
}
if (showShapes && bearDiv) {
plotShape(
value=high + range_ * 0.25,
shape="arrowdown",
color=transparency(bearColor, 40),
width=1,
label=["Exh Divergence"],
desc=["Potential exhaustion divergence: price higher high but exhaustion frequency declining"]
)
}
// --- Regime Background Indicator (subtle dots) ---
if (useRegime) {
var regimeSignal = regimeProne ? 1 : (regimeExhausted ? -1 : 0)
plotShape(
value=close,
shape="circle",
color=regimeColor,
width=1,
label=["Regime"],
desc=["Volatility regime: green=exhaustion-prone (trending), gray=exhaustion-exhausted (chop), orange=neutral"]
)
}
// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeProne ? "EXHAUSTION-PRONE" : (regimeExhausted ? "EXHAUSTED" : "NEUTRAL")
var regimeTextColor = regimeProne ? bearColor : (regimeExhausted ? "#9e9e9e" : "#ffa726")
plotTable(
data=[
["Leledc Exhaustion — Perfected", regimeText],
["Bull Exhaustions (session)", bullExhCount],
["Bear Exhaustions (session)", bearExhCount],
["Last Bull Exh Bar", lastBullExhBar >= 0 ? (currentBarIndex - lastBullExhBar) + " bars ago" : "None"],
["Last Bear Exh Bar", lastBearExhBar >= 0 ? (currentBarIndex - lastBearExhBar) + " bars ago" : "None"],
["Body Z-Score", math.round(bodyZScore[0] * 100) / 100],
["Vol Ratio", math.round(volRatio[0] * 100) / 100],
["ATR Ratio", math.round(atrRatio[0] * 100) / 100]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=transparency("#0f172a", 40),
headerBackgroundColor=transparency("#1e293b", 40),
borderColor=transparency("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}