MM Flow
FlowScripts

Perfected FlowScript

Euphoria & Capitulation - Tradingriot

Euphoria & Capitulation [Tradingriot] Perfected is indexed as 007_euphoria_capitulation_tradingriot.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

9.1 KB

Lines

218

Native Signal Candidates

3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

3/3 guarded

Euphoria

line 155:5

Trigger

(showShapes && euphoriaEvent)

Value

sentimentScore

Deps

euphoriaEvent:var, showShapes:input

Capitulation

line 167:5

Trigger

(showShapes && capitulationEvent)

Value

sentimentScore

Deps

capitulationEvent:var, showShapes:input

Vol Spike

line 179:5

Trigger

(showShapes && volSpike && !euphoriaEvent && !capitulationEvent)

Value

sentimentScore

Deps

capitulationEvent:var, euphoriaEvent:var, showShapes:input, volSpike:var

007_euphoria_capitulation_tradingriot.flowscript

source path: kscripts/perfected/007_euphoria_capitulation_tradingriot.flowscript · sha256:8d2ca6486abc1a1308b7a8accb6807dded08fbb25d71f9259cd369a7644c0b00

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Euphoria & Capitulation [Tradingriot Perfected]
// Author: abetrade (@abetrade) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #euphoria, #capitulation, #volume, #pivots, #regime, #sentiment
//
// Production-quality sentiment/extremes oscillator detecting new price highs
// and lows on significant volume spikes. Implements anchored regime
// detection with static state tracking, volume-significance histogram, and
// comprehensive shape markers for euphoria and capitulation events.
//
// Research papers underpinning this design:
//  - Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns": extreme imbalances predict return reversals; new
//    highs/lows on volume are extreme imbalance conditions.
//  - Poterba & Summers (1988), "Mean Reversion in Stock Prices": empirical
//    evidence of mean reversion at medium-term horizons; euphoria/capitulation
//    extremes precede reversals.
//  - Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//    Losers": momentum anomaly validates trend-continuation when new highs/lows
//    occur on volume.
//  - Daniel & Moskowitz (2013), "Momentum Crashes": momentum crashes follow
//    extreme sentiment; euphoria regimes forecast momentum drawdowns.
//  - Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules":
//    breakout signals (new highs/lows) generate significant excess returns.
// ============================================================================

define(
    title="Euphoria & Capitulation [Tradingriot] Perfected",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------

// --- Detection Group ---
var lookback = input(name="lookback", type="number", defaultValue=20, label="Pivot Lookback (bars)", constraints={min: 5, max: 100, step: 1}, group="Detection")
var volLen = input(name="volLen", type="number", defaultValue=20, label="Volume Average Length", constraints={min: 5, max: 100, step: 1}, group="Detection")
var volMult = input(name="volMult", type="number", defaultValue=1.5, label="Volume Spike Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Detection")
var regimeDecay = input(name="regimeDecay", type="number", defaultValue=5, label="Regime Decay (bars)", constraints={min: 1, max: 50, step: 1}, group="Detection")

// --- Display Group ---
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Shape Markers", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Volume Histogram", group="Display")
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Euphoria/Capitulation Zones", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Regime Table", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors Group ---
var euphoriaColor = input(name="euphoriaColor", type="color", defaultValue="#d50000", label="Euphoria Color", group="Colors")
var capitulationColor = input(name="capitulationColor", type="color", defaultValue="#26a69a", label="Capitulation Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var volSpikeColor = input(name="volSpikeColor", type="color", defaultValue="#ffab00", label="Volume Spike Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources & NaN Guard
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// Pivot Detection
// ---------------------------------------------------------------------------
timeseries priorHigh = highest(hi, lookback)
timeseries priorLow = lowest(lo, lookback)
timeseries avgVol = sma(vol, volLen)

// New high/low detection: current bar exceeds prior lookback extreme
var newHigh = hi[0] > priorHigh[1]
var newLow = lo[0] < priorLow[1]
var volSpike = vol[0] >= avgVol[0] * volMult

// Euphoria = new high + volume spike
// Capitulation = new low + volume spike
var euphoriaEvent = newHigh && volSpike
var capitulationEvent = newLow && volSpike

// ---------------------------------------------------------------------------
// Regime Detection (static variables for stateful tracking)
// ---------------------------------------------------------------------------
static sentimentScoreRaw = 50.0

if (euphoriaEvent) {
    sentimentScoreRaw = 100.0
} else if (capitulationEvent) {
    sentimentScoreRaw = 0.0
} else {
    // Decay toward neutral (50)
    sentimentScoreRaw = sentimentScoreRaw + (50.0 - sentimentScoreRaw) / regimeDecay
}

timeseries sentimentScore = sentimentScoreRaw

var regimeEuphoria = sentimentScoreRaw >= 80.0
var regimeCapitulation = sentimentScoreRaw <= 20.0
var regimeNeutral = !regimeEuphoria && !regimeCapitulation

var regimeColor = regimeEuphoria ? euphoriaColor : (regimeCapitulation ? capitulationColor : neutralColor)

// ---------------------------------------------------------------------------
// Volume Histogram (relative volume scaled to 0-50 range)
// ---------------------------------------------------------------------------
timeseries relVol = vol / math.max(1, avgVol)
timeseries volHist = (relVol - 1.0) * 25

// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------

// --- Midline ---
hline(value=50, color="#ffffff20", width=1)

// --- Euphoria / Capitulation Zones ---
if (showZones) {
    hline(value=80, color=transparency(euphoriaColor, 60), width=1)
    hline(value=20, color=transparency(capitulationColor, 60), width=1)
}

// --- Sentiment Score (regime-colored) ---
plotLine(
    value=sentimentScore,
    width=lineWidth,
    colors=[regimeColor],
    label=["Sentiment Score"],
    desc=["Euphoria/Capitulation sentiment score (0-100)"]
)

// --- Volume Histogram ---
if (showHistogram) {
    var histBull = volHist >= 0
    plotBar(
        value=volHist,
        colors=[transparency(volSpikeColor, 60), transparency(neutralColor, 30)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Vol Significance"],
        desc=["Volume significance histogram: (relVol - 1) * 25"]
    )
}

// --- Euphoria Shape Markers ---
if (showShapes && euphoriaEvent) {
    plotShape(
        value=sentimentScore,
        shape="triangledown",
        colorIndex=euphoriaColor,
        width=shapeSize,
        label=["Euphoria"],
        desc=["Euphoria event: new high on volume spike"]
    )
}

// --- Capitulation Shape Markers ---
if (showShapes && capitulationEvent) {
    plotShape(
        value=sentimentScore,
        shape="triangleup",
        colorIndex=capitulationColor,
        width=shapeSize,
        label=["Capitulation"],
        desc=["Capitulation event: new low on volume spike"]
    )
}

// --- Volume Spike Shape Markers (volume spike without new extreme) ---
if (showShapes && volSpike && !euphoriaEvent && !capitulationEvent) {
    plotShape(
        value=sentimentScore,
        shape="circle",
        colorIndex=volSpikeColor,
        width=1,
        label=["Vol Spike"],
        desc=["Volume spike without new high/low"]
    )
}

// ---------------------------------------------------------------------------
// Regime Table (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeEuphoria ? "EUPHORIA" : (regimeCapitulation ? "CAPITULATION" : "NEUTRAL")
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["Euphoria & Capitulation", regimeText],
            ["Sentiment Score", sentimentScore[0]],
            ["Relative Volume", relVol[0]],
            ["Volume Spike", volSpike ? "YES" : "NO"],
            ["New High", newHigh ? "YES" : "NO"],
            ["New Low", newLow ? "YES" : "NO"]
        ],
        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
    )
}