Perfected FlowScript
euphoria & capitulation
Euphoria & Capitulation — Perfected Edition is indexed as 217_euphoria_capitulation.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
offchart
Axis
true
Size
17.7 KB
Lines
535
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Euphoria
line 442:9
Trigger
(showShapes) && (newEuphoria)
Value
sentimentSmooth
Deps
newEuphoria:var, showShapes:input
Euphoria Exhaust
line 452:9
Trigger
(showShapes) && (euphoriaExhaustion)
Value
sentimentSmooth
Deps
euphoriaExhaustion:var, showShapes:input
Capitulation
line 462:9
Trigger
(showShapes) && (newCapitulation)
Value
sentimentSmooth
Deps
newCapitulation:var, showShapes:input
Capit Exhaust
line 472:9
Trigger
(showShapes) && (capitulationExhaustion)
Value
sentimentSmooth
Deps
capitulationExhaustion:var, showShapes:input
Euphoria Recov
line 482:9
Trigger
(showShapes) && (euphoriaRecovery)
Value
sentimentSmooth
Deps
euphoriaRecovery:var, showShapes:input
Capit Recov
line 492:9
Trigger
(showShapes) && (capitulationRecovery)
Value
sentimentSmooth
Deps
capitulationRecovery:var, showShapes:input
217_euphoria_capitulation.flowscript
source path: kscripts/perfected/217_euphoria_capitulation.flowscript · sha256:0b059f0fb421ac6811f25ef40dc24019188a7464324262ad2c98344d2e7148ee
//@version=2
// ============================================================================
// Euphoria & Capitulation — Perfected Edition
// Author: W | Enhanced by kScript Perfection Engineer
// Tags: CORE, #sentiment, #euphoria, #capitulation, #regime, #z-score, #extremes
//
// Production-grade sentiment-extremes oscillator detecting euphoria (excessive
// bullishness) and capitulation (excessive bearishness) using multi-factor
// composite scoring: RSI momentum, volume amplification, price velocity, and
// rolling z-score normalization. Regime detection classifies each bar into
// Euphoria / Capitulation / Neutral / Recovery states with color-coded
// histograms, shape markers, and a dynamic regime table.
//
// Research papers underpinning this design:
// 1. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
// Stock Returns", Journal of Finance, 61(4), 1645–1680. The canonical
// sentiment index paper: sentiment is a contrarian predictor; extreme
// bullishness forecasts lower subsequent returns, and extreme bearishness
// forecasts higher returns. DOI: 10.1111/j.1540-6261.2006.00885.x
// 2. De Long, Shleifer, Summers & Waldmann (1990), "Positive Feedback Investment
// Strategies and Destabilizing Rational Speculation", Journal of Finance,
// 45(2), 379–395. Noise traders create positive-feedback loops that push
// prices to euphoric extremes before reversal; underpins contrarian
// signalling at sentiment extremes. DOI: 10.1111/j.1540-6261.1990.tb03695.x
// 3. Brown & Cliff (2005), "Investor Sentiment and Asset Valuation",
// Journal of Business, 78(2), 405–440. Directly links high sentiment to
// overvaluation and low sentiment to undervaluation; supports the euphoria/
// capitulation threshold framework. DOI: 10.1086/427636
// 4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", Journal of Financial Economics, 65(1), 111–130.
// Extreme order imbalance (volume-driven) predicts return reversals at
// daily horizons; volume amplification is a critical euphoria/capitulation
// filter. DOI: 10.1016/S0304-405X(02)00136-8
// 5. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
// autocorrelation at medium horizons. Mean-reversion intensity is highest
// after extreme returns; z-score normalization captures this statistically.
// DOI: 10.1016/0022-1996(88)90021-9
// ============================================================================
define(
title="Euphoria & Capitulation — Perfected Edition",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- RSI Momentum ---
var rsiLen = input(
name="rsiLen",
type="number",
defaultValue=14,
label="RSI Length",
constraints={min: 2, max: 50, step: 1},
group="RSI Momentum"
)
var rsiSmooth = input(
name="rsiSmooth",
type="number",
defaultValue=3,
label="RSI EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="RSI Momentum"
)
// --- Volume Amplification ---
var volMaLen = input(
name="volMaLen",
type="number",
defaultValue=20,
label="Volume MA Length",
constraints={min: 5, max: 100, step: 1},
group="Volume Amplification"
)
var volSpikeMult = input(
name="volSpikeMult",
type="number",
defaultValue=1.5,
label="Volume Spike Threshold (× MA)",
constraints={min: 1.0, max: 5.0, step: 0.1},
group="Volume Amplification"
)
var requireVolSpike = input(
name="requireVolSpike",
type="boolean",
defaultValue=true,
label="Require Volume Spike for Extremes",
group="Volume Amplification"
)
// --- Z-Score Normalization ---
var zLookback = input(
name="zLookback",
type="number",
defaultValue=50,
label="Z-Score Lookback (bars)",
constraints={min: 20, max: 200, step: 5},
group="Z-Score Normalization"
)
var zSmooth = input(
name="zSmooth",
type="number",
defaultValue=3,
label="Z-Score EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="Z-Score Normalization"
)
// --- Thresholds ---
var euphoriaThresh = input(
name="euphoriaThresh",
type="number",
defaultValue=80,
label="Euphoria RSI Threshold",
constraints={min: 50, max: 95, step: 1},
group="Thresholds"
)
var capitThresh = input(
name="capitThresh",
type="number",
defaultValue=20,
label="Capitulation RSI Threshold",
constraints={min: 5, max: 50, step: 1},
group="Thresholds"
)
var zEuphoria = input(
name="zEuphoria",
type="number",
defaultValue=2.0,
label="Z-Score Euphoria Threshold",
constraints={min: 1.0, max: 4.0, step: 0.25},
group="Thresholds"
)
var zCapit = input(
name="zCapit",
type="number",
defaultValue=-2.0,
label="Z-Score Capitulation Threshold",
constraints={min: -4.0, max: -1.0, step: 0.25},
group="Thresholds"
)
// --- Display ---
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Sentiment Line",
group="Display"
)
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Regime Histogram",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Extreme Shape Markers",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Regime Table",
group="Display"
)
// --- Colors ---
var euphoriaColor = input(
name="euphoriaColor",
type="color",
defaultValue="#26a69a",
label="Euphoria Color",
group="Colors"
)
var capitColor = input(
name="capitColor",
type="color",
defaultValue="#ef5350",
label="Capitulation Color",
group="Colors"
)
var recoveryColor = input(
name="recoveryColor",
type="color",
defaultValue="#ffd54f",
label="Recovery Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var zLineColor = input(
name="zLineColor",
type="color",
defaultValue="#ffffff",
label="Z-Score Line Color",
group="Colors"
)
var strongColor = input(
name="strongColor",
type="color",
defaultValue="#ffd54f",
label="Strong Signal Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
if (isnan(bars.close[0]) || isnan(bars.volume[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. COMPOSITE SENTIMENT CONSTRUCTION
// -----------------------------------------------------------------------------
// -- 3.1 RSI (Wilder canonical) --
timeseries dChg = bars.close - bars.close[1]
timeseries gains = dChg > 0 ? dChg : 0
timeseries losses = dChg < 0 ? -dChg : 0
timeseries avgGain = rma(source=gains, period=rsiLen)
timeseries avgLoss = rma(source=losses, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - 100 / (1 + rs)
timeseries rsi = ema(source=rsiRaw, period=rsiSmooth)
// -- 3.2 Volume amplification --
timeseries volMA = sma(source=bars.volume, period=volMaLen)
timeseries volRatio = volMA > 0 ? bars.volume / volMA : 1
timeseries volSpike = volRatio > volSpikeMult
// -- 3.3 Price velocity (return magnitude) --
timeseries ret = bars.close > 0 ? (bars.close - bars.close[1]) / bars.close[1] * 100 : 0
timeseries retAbs = math.abs(ret)
// -- 3.4 Composite sentiment score (0-100 scale) --
// Combines: RSI position, volume amplification, and return velocity
// Centered at 50 = neutral; > 50 = bullish bias; < 50 = bearish bias
timeseries sentimentRaw = (rsi - 50) * 2
timeseries volAdj = volRatio > 1 ? math.min(volRatio, 3) : 1
timeseries sentimentAdj = sentimentRaw * volAdj
// Clamp to -100 / +100 then shift to 0-100
timeseries sentimentClamped = math.max(-100, math.min(100, sentimentAdj))
timeseries sentiment = (sentimentClamped + 100) / 2
// -- 3.5 Smoothed sentiment --
timeseries sentimentSmooth = ema(source=sentiment, period=rsiSmooth)
// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Z-score of the smoothed sentiment over a rolling window; this captures
// statistically significant deviations from the local mean.
timeseries sentMean = sma(source=sentimentSmooth, period=zLookback)
timeseries sentStd = stddev(source=sentimentSmooth, period=zLookback)
timeseries zScoreRaw = sentStd > 0 ? (sentimentSmooth - sentMean) / sentStd : 0
timeseries zScore = ema(source=zScoreRaw, period=zSmooth)
// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Four regimes: Euphoria, Capitulation, Recovery, Neutral
// Euphoria: RSI > threshold AND z-score > threshold AND (optionally) volume spike
// Capitulation: RSI < threshold AND z-score < threshold AND (optionally) volume spike
// Recovery: was extreme but now reverting toward neutral
// Neutral: everything else
var euphoriaNow = false
var capitulationNow = false
var recoveryNow = false
var neutralNow = true
var volCondition = !requireVolSpike || volSpike
if (rsi > euphoriaThresh && zScore > zEuphoria && volCondition) {
euphoriaNow = true
capitulationNow = false
recoveryNow = false
neutralNow = false
} else if (rsi < capitThresh && zScore < zCapit && volCondition) {
euphoriaNow = false
capitulationNow = true
recoveryNow = false
neutralNow = false
} else if ((rsi > capitThresh && rsi < euphoriaThresh) || math.abs(zScore) < 1.0) {
// Recovery: returning to neutral territory
euphoriaNow = false
capitulationNow = false
recoveryNow = true
neutralNow = false
} else {
neutralNow = true
}
// Regime color mapping
var regimeColor = euphoriaNow ? euphoriaColor : (
capitulationNow ? capitColor : (recoveryNow ? recoveryColor : neutralColor)
)
// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING — consecutive bars in each regime
// -----------------------------------------------------------------------------
static euphoriaBars = 0
static capitulationBars = 0
static recoveryBars = 0
static lastEuphoriaBar = 0
static lastCapitulationBar = 0
static maxEuphoriaScore = 0.0
static maxCapitulationScore = 0.0
static totalEuphoria = 0
static totalCapitulation = 0
if (!isLiveUpdate) {
if (euphoriaNow) {
euphoriaBars = euphoriaBars + 1
capitulationBars = 0
recoveryBars = 0
lastEuphoriaBar = barCount
totalEuphoria = totalEuphoria + 1
if (zScore > maxEuphoriaScore) {
maxEuphoriaScore = zScore
}
} else if (capitulationNow) {
capitulationBars = capitulationBars + 1
euphoriaBars = 0
recoveryBars = 0
lastCapitulationBar = barCount
totalCapitulation = totalCapitulation + 1
if (math.abs(zScore) > maxCapitulationScore) {
maxCapitulationScore = math.abs(zScore)
}
} else if (recoveryNow) {
recoveryBars = recoveryBars + 1
euphoriaBars = 0
capitulationBars = 0
} else {
euphoriaBars = 0
capitulationBars = 0
recoveryBars = 0
}
}
// -----------------------------------------------------------------------------
// 7. DIVERGENCE / EXTREME ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Euphoria exhaustion: euphoria has lasted N bars and now price falls
// Capitulation exhaustion: capitulation has lasted N bars and now price rises
var euphoriaExhaustion = euphoriaNow && euphoriaBars >= 3 && bars.close < bars.close[1]
var capitulationExhaustion = capitulationNow && capitulationBars >= 3 && bars.close > bars.close[1]
// First extreme bar (new regime entry)
var newEuphoria = euphoriaNow && euphoriaBars == 1
var newCapitulation = capitulationNow && capitulationBars == 1
// Recovery signal (transition from extreme to neutral)
var euphoriaRecovery = !euphoriaNow && euphoriaBars[1] > 0 && bars.close < bars.close[1]
var capitulationRecovery = !capitulationNow && capitulationBars[1] > 0 && bars.close > bars.close[1]
// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------
// -- 8.1 Reference lines --
hline(value=50, color="#ffffff20", width=1)
hline(value=0, color=transparency(capitColor, 70), width=1)
hline(value=100, color=transparency(euphoriaColor, 70), width=1)
// -- 8.2 Z-Score zero line and threshold bands --
if (showZScore) {
hline(value=0, color="#ffffff20", width=1)
hline(value=zEuphoria, color=transparency(euphoriaColor, 60), width=1)
hline(value=zCapit, color=transparency(capitColor, 60), width=1)
hline(value=zEuphoria / 2, color=transparency(euphoriaColor, 80), width=1)
hline(value=zCapit / 2, color=transparency(capitColor, 80), width=1)
}
// -- 8.3 Composite sentiment line (regime-colored) --
if (showComposite) {
plotLine(
value=sentimentSmooth,
width=2,
colors=[regimeColor],
label=["Sentiment"],
desc=["Composite sentiment score (0-100); color = regime"]
)
}
// -- 8.4 Z-Score line --
if (showZScore) {
plotLine(
value=zScore,
width=1,
colors=[zLineColor],
label=["Z-Score"],
desc=["Rolling z-score of sentiment; deviations > " + zEuphoria + " or < " + zCapit + " flag extremes"]
)
}
// -- 8.5 Regime histogram (color-coded by regime) --
if (showHistogram) {
var histColorIdx = euphoriaNow ? 0 : (capitulationNow ? 1 : (recoveryNow ? 2 : 3))
plotLine(
value=[sentimentSmooth, 50],
width=2,
colors=[euphoriaColor, capitColor, recoveryColor, neutralColor],
colorIndex=histColorIdx,
fill=true,
label=["Sentiment", "Neutral"],
desc=["Regime-coded histogram: euphoria=green, capitulation=red, recovery=yellow, neutral=grey"]
)
}
// -- 8.6 Extreme shape markers --
if (showShapes) {
if (newEuphoria) {
plotShape(
value=sentimentSmooth,
shape="triangleup",
colorIndex=euphoriaColor,
width=2,
label=["Euphoria"],
desc=["Euphoria regime detected: RSI=" + rsi + ", Z=" + zScore]
)
}
if (euphoriaExhaustion) {
plotShape(
value=sentimentSmooth,
shape="arrowdown",
colorIndex=strongColor,
width=2,
label=["Euphoria Exhaust"],
desc=["Euphoria exhaustion signal: " + euphoriaBars + " consecutive bars, price falling"]
)
}
if (newCapitulation) {
plotShape(
value=sentimentSmooth,
shape="triangledown",
colorIndex=capitColor,
width=2,
label=["Capitulation"],
desc=["Capitulation regime detected: RSI=" + rsi + ", Z=" + zScore]
)
}
if (capitulationExhaustion) {
plotShape(
value=sentimentSmooth,
shape="arrowup",
colorIndex=recoveryColor,
width=2,
label=["Capit Exhaust"],
desc=["Capitulation exhaustion signal: " + capitulationBars + " consecutive bars, price rising"]
)
}
if (euphoriaRecovery) {
plotShape(
value=sentimentSmooth,
shape="circle",
colorIndex=recoveryColor,
width=1,
label=["Euphoria Recov"],
desc=["Euphoria recovery: sentiment returning from extreme"]
)
}
if (capitulationRecovery) {
plotShape(
value=sentimentSmooth,
shape="circle",
colorIndex=recoveryColor,
width=1,
label=["Capit Recov"],
desc=["Capitulation recovery: sentiment returning from extreme"]
)
}
}
// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = euphoriaNow ? "EUPHORIA" : (capitulationNow ? "CAPITULATION" : (recoveryNow ? "RECOVERY" : "NEUTRAL"))
var regimeTextColor = regimeColor
plotTable(
data=[
["Euphoria & Capitulation", regimeText],
["RSI", math.round(rsi[0], 2)],
["Z-Score", math.round(zScore[0], 2)],
["Sentiment", math.round(sentimentSmooth[0], 1)],
["Vol Ratio", math.round(volRatio[0], 2)],
["Euphoria Count", totalEuphoria],
["Capitulation Count", totalCapitulation],
["Max Z (Euphoria)", math.round(maxEuphoriaScore, 2)],
["Max Z (Capitulation)", math.round(maxCapitulationScore, 2)]
],
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
)
}