MM Flow
FlowScripts

Perfected FlowScript

Ethereum Sentiment Index - Tradingriot

Ethereum Sentiment Index [Tradingriot] — Perfected is indexed as 079_ethereum_sentiment_index_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

19.8 KB

Lines

582

Native Signal Candidates

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

6/6 guarded

Extreme Fear

line 490:9

Trigger

(showShapes) && (enterExtremeFear)

Value

composite

Deps

enterExtremeFear:var, showShapes:input

Exit Fear

line 500:9

Trigger

(showShapes) && (exitExtremeFear)

Value

composite

Deps

exitExtremeFear:var, showShapes:input

Extreme Greed

line 510:9

Trigger

(showShapes) && (enterExtremeGreed)

Value

composite

Deps

enterExtremeGreed:var, showShapes:input

Exit Greed

line 520:9

Trigger

(showShapes) && (exitExtremeGreed)

Value

composite

Deps

exitExtremeGreed:var, showShapes:input

Fear Entry

line 530:9

Trigger

(showShapes) && (enterFear)

Value

composite

Deps

enterFear:var, showShapes:input

Greed Entry

line 540:9

Trigger

(showShapes) && (enterGreed)

Value

composite

Deps

enterGreed:var, showShapes:input

079_ethereum_sentiment_index_tradingriot.flowscript

source path: kscripts/perfected/079_ethereum_sentiment_index_tradingriot.flowscript · sha256:32279f8ba71e7da90c1ed6c114741723b0d0b45c196dc716bfcc8822222ee185

hash verified
//@version=2
// ============================================================================
// Ethereum Sentiment Index [Tradingriot] — Perfected Edition
// Author: abetrade (@abetrade) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #skew, #risk, #reversal, #term, #structure, #sentiment, #zscore, #eth
//
// Production-grade composite sentiment index combining five positioning metrics:
// risk reversal skew (approximated from return asymmetry), funding rates,
// open interest delta, implied volatility (approximated from ATR), and price
// momentum. Each component is z-score normalized over a rolling window and
// combined into a weighted composite with 5-tier regime detection, color coding,
// extreme markers, fill visualization, and full toggles for individual components.
//
// FORMULA FOUNDATION:
// 1. Z-Score Normalization per component: z_i = (x_i - μ_i) / σ_i
//    per Zhao & Palomar (2018), entry thresholds at ±1σ, ±2σ, ±3σ.
// 2. Weighted Composite: Σ w_i × z_i / Σ w_i, with runtime weight normalization
//    per Baker & Wurgler (2006) composite sentiment via PCA of multiple proxies.
// 3. Five-Tier Regime Detection: Extreme Fear (<-2.5), Fear (-1.5 to -2.5),
//    Neutral (-1.5 to +1.5), Greed (+1.5 to +2.5), Extreme Greed (>+2.5).
// 4. Contrarian Signal: Extreme fear zones predict bullish reversal; extreme
//    greed zones predict bearish reversal per Rakovská (2021).
//
// RESEARCH BASIS:
//  • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//    Stock Returns": seminal paper on composite sentiment construction from
//    multiple proxies via PCA. Underpins the weighted multi-component
//    architecture.
//  • Carr & Wu (2009), "Variance Risk Premia": VRP measurement captures
//    the term-structure component. IV extremes flag crowded positioning.
//  • Carr & Wu (2007), "Stochastic Skew in Currency Options": risk reversal
//    = IV(25Δ Call) - IV(25Δ Put). Stochastic skew models validate dynamic
//    skew interpretation for sentiment extremes.
//  • He & Manela (2022), "Fundamentals of Perpetual Futures": funding rate
//    deviation as a sentiment indicator; momentum-funding relationship.
//  • Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//    Basis and Open Interest": OI levels predict future volatility;
//    unexpected OI changes carry more information than levels.
//  • Rakovská (2021), "Composite Survey Sentiment as a Predictor": composite
//    indices outperform single indicators; macro-orthogonalization.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//    z-score normalization framework; entry thresholds at ±1σ, ±2σ.
// ============================================================================

define(
    title="Ethereum Sentiment Index [Tradingriot] — Perfected",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Z-Score Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Window",
    constraints={min: 10, max: 200, step: 1},
    group="Z-Score Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Composite Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Settings"
)

// --- Component Weights ---
var skewWeight = input(
    name="skewWeight",
    type="number",
    defaultValue=0.20,
    label="Skew Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var fundingWeight = input(
    name="fundingWeight",
    type="number",
    defaultValue=0.25,
    label="Funding Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var oiWeight = input(
    name="oiWeight",
    type="number",
    defaultValue=0.20,
    label="OI Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var ivWeight = input(
    name="ivWeight",
    type="number",
    defaultValue=0.20,
    label="IV Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)
var retWeight = input(
    name="retWeight",
    type="number",
    defaultValue=0.15,
    label="Return Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Component Weights"
)

// --- Regime Thresholds ---
var extremeFearThresh = input(
    name="extremeFearThresh",
    type="number",
    defaultValue=-2.5,
    label="Extreme Fear Threshold",
    constraints={min: -4.0, max: -1.0, step: 0.1},
    group="Regime Thresholds"
)
var fearThresh = input(
    name="fearThresh",
    type="number",
    defaultValue=-1.5,
    label="Fear Threshold",
    constraints={min: -3.0, max: -0.5, step: 0.1},
    group="Regime Thresholds"
)
var greedThresh = input(
    name="greedThresh",
    type="number",
    defaultValue=1.5,
    label="Greed Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Regime Thresholds"
)
var extremeGreedThresh = input(
    name="extremeGreedThresh",
    type="number",
    defaultValue=2.5,
    label="Extreme Greed Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Regime Thresholds"
)

// --- Display ---
var showSkew = input(
    name="showSkew",
    type="boolean",
    defaultValue=true,
    label="Show Skew Component",
    group="Display"
)
var showFunding = input(
    name="showFunding",
    type="boolean",
    defaultValue=true,
    label="Show Funding Component",
    group="Display"
)
var showOI = input(
    name="showOI",
    type="boolean",
    defaultValue=true,
    label="Show OI Component",
    group="Display"
)
var showIV = input(
    name="showIV",
    type="boolean",
    defaultValue=true,
    label="Show IV Component",
    group="Display"
)
var showReturn = input(
    name="showReturn",
    type="boolean",
    defaultValue=true,
    label="Show Return Component",
    group="Display"
)
var showComposite = input(
    name="showComposite",
    type="boolean",
    defaultValue=true,
    label="Show Composite Index",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish/Extreme Fear Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish/Extreme Greed Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var fearColor = input(
    name="fearColor",
    type="color",
    defaultValue="#42a5f5",
    label="Fear Color",
    group="Colors"
)
var greedColor = input(
    name="greedColor",
    type="color",
    defaultValue="#ffa726",
    label="Greed Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. 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

timeseries funding = source("funding_rate", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)

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

// -----------------------------------------------------------------------------
// 3. COMPONENT 1 — SKEW (approximated from return asymmetry)
// -----------------------------------------------------------------------------
// Since 25-delta risk reversal skew is not directly accessible in this DSL,
// we approximate it from the rolling skewness of returns (asymmetric tail risk).
// Positive skew = left tail heavier (fear); negative skew = right tail heavier (greed).
timeseries ret = (px - px[1]) / math.max(0.0001, px[1])

// Rolling third moment (skewness numerator)
timeseries retMean = sma(ret, lookback)
timeseries retStd = stdev(ret, lookback)
timeseries retDev = ret - retMean
timeseries retCubed = retDev * retDev * retDev
timeseries retCubedMean = sma(retCubed, lookback)

// Skewness approximation: E[(x-μ)³] / σ³; guard against div by zero
timeseries skewProxy = retStd > 0 ? retCubedMean / (retStd * retStd * retStd) : 0

// Z-score of skew proxy
timeseries skewMean = sma(skewProxy, lookback)
timeseries skewStd = stdev(skewProxy, lookback)
timeseries skewZ = skewStd > 0 ? (skewProxy - skewMean) / skewStd : 0

// -----------------------------------------------------------------------------
// 4. COMPONENT 2 — FUNDING RATE
// -----------------------------------------------------------------------------
timeseries fundingSeries = isnum(funding.value) ? funding.value : 0
timeseries fundingMean = sma(fundingSeries, lookback)
timeseries fundingStd = stdev(fundingSeries, lookback)
timeseries fundingZ = fundingStd > 0 ? (fundingSeries - fundingMean) / fundingStd : 0

// -----------------------------------------------------------------------------
// 5. COMPONENT 3 — OPEN INTEREST DELTA
// -----------------------------------------------------------------------------
timeseries oiChange = oi.close - oi.close[1]
timeseries oiMean = sma(oiChange, lookback)
timeseries oiStd = stdev(oiChange, lookback)
timeseries oiZ = oiStd > 0 ? (oiChange - oiMean) / oiStd : 0

// -----------------------------------------------------------------------------
// 6. COMPONENT 4 — IMPLIED VOLATILITY (approximated from ATR)
// -----------------------------------------------------------------------------
// IV proxy = annualized ATR volatility: (ATR / price) × sqrt(252) × 100
timeseries prevClose = isnan(px[1]) ? px : px[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, 14)

timeseries ivProxy = px > 0 ? (atr / px) * math.sqrt(252) * 100 : 0

timeseries ivMean = sma(ivProxy, lookback)
timeseries ivStd = stdev(ivProxy, lookback)
timeseries ivZ = ivStd > 0 ? (ivProxy - ivMean) / ivStd : 0

// -----------------------------------------------------------------------------
// 7. COMPONENT 5 — PRICE MOMENTUM / RETURN
// -----------------------------------------------------------------------------
// Returns already computed above
timeseries retMean2 = sma(ret, lookback)
timeseries retStd2 = stdev(ret, lookback)
timeseries retZ = retStd2 > 0 ? (ret - retMean2) / retStd2 : 0

// -----------------------------------------------------------------------------
// 8. WEIGHTED COMPOSITE SENTIMENT INDEX
// -----------------------------------------------------------------------------
// Normalize weights so they sum to 1.0
timeseries totalWeight = skewWeight + fundingWeight + oiWeight + ivWeight + retWeight
timeseries wSkew = totalWeight > 0 ? skewWeight / totalWeight : 0.2
timeseries wFunding = totalWeight > 0 ? fundingWeight / totalWeight : 0.2
timeseries wOI = totalWeight > 0 ? oiWeight / totalWeight : 0.2
timeseries wIV = totalWeight > 0 ? ivWeight / totalWeight : 0.2
timeseries wRet = totalWeight > 0 ? retWeight / totalWeight : 0.2

// Raw composite (unsmoothed)
timeseries rawComposite = wSkew * skewZ + wFunding * fundingZ + wOI * oiZ + wIV * ivZ + wRet * retZ

// Smoothed composite
timeseries composite = ema(source=rawComposite, period=smoothLen)

// -----------------------------------------------------------------------------
// 9. REGIME DETECTION
// -----------------------------------------------------------------------------
// Five-tier regime classification: extreme fear, fear, neutral, greed, extreme greed
var regimeExtremeFear = composite < extremeFearThresh
var regimeFear = composite < fearThresh && composite >= extremeFearThresh
var regimeNeutral = composite >= fearThresh && composite <= greedThresh
var regimeGreed = composite > greedThresh && composite <= extremeGreedThresh
var regimeExtremeGreed = composite > extremeGreedThresh

// Regime color for composite line
var regimeColor = regimeExtremeFear ? bullColor : (regimeFear ? fearColor : (regimeGreed ? greedColor : (regimeExtremeGreed ? bearColor : neutralColor)))

// -----------------------------------------------------------------------------
// 10. EXTREME EVENT FLAGS
// -----------------------------------------------------------------------------
// Extreme events for shape markers: entering/leaving extreme zones
var enterExtremeFear = composite < extremeFearThresh && !isnan(composite[1]) && composite[1] >= extremeFearThresh
var exitExtremeFear = composite >= extremeFearThresh && !isnan(composite[1]) && composite[1] < extremeFearThresh
var enterExtremeGreed = composite > extremeGreedThresh && !isnan(composite[1]) && composite[1] <= extremeGreedThresh
var exitExtremeGreed = composite <= extremeGreedThresh && !isnan(composite[1]) && composite[1] > extremeGreedThresh

var enterFear = composite < fearThresh && !isnan(composite[1]) && composite[1] >= fearThresh
var exitFear = composite >= fearThresh && !isnan(composite[1]) && composite[1] < fearThresh
var enterGreed = composite > greedThresh && !isnan(composite[1]) && composite[1] <= greedThresh
var exitGreed = composite <= greedThresh && !isnan(composite[1]) && composite[1] > greedThresh

// -----------------------------------------------------------------------------
// 11. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighComposite = -999999.0
static sessionLowComposite = 999999.0
static extremeFearCount = 0
static extremeGreedCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (composite > sessionHighComposite) {
        sessionHighComposite = composite
    }
    if (composite < sessionLowComposite) {
        sessionLowComposite = composite
    }

    var currentRegime = regimeExtremeFear ? -2 : (regimeFear ? -1 : (regimeGreed ? 1 : (regimeExtremeGreed ? 2 : 0)))
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regimeExtremeFear) {
        extremeFearCount = extremeFearCount + 1
    } else if (regimeExtremeGreed) {
        extremeGreedCount = extremeGreedCount + 1
    }
}

// -----------------------------------------------------------------------------
// 12. PLOTTING
// -----------------------------------------------------------------------------

// --- Reference Lines ---
hline(value=0, color="#ffffff40", width=1)
hline(value=extremeGreedThresh, color=opacity(bearColor, 30), width=1)
hline(value=greedThresh, color=opacity(greedColor, 30), width=1)
hline(value=fearThresh, color=opacity(fearColor, 30), width=1)
hline(value=extremeFearThresh, color=opacity(bullColor, 30), width=1)

// --- Composite Line (regime-colored) ---
if (showComposite) {
    plotLine(
        value=composite,
        width=2,
        colors=[regimeColor],
        label=["Composite Sentiment"],
        desc=["Weighted composite sentiment index (smoothed)"]
    )
}

// --- Regime Fill (composite vs zero) ---
if (showFill) {
    var fillBull = composite >= 0
    plotLine(
        value=[composite, 0],
        width=1,
        colors=[opacity(bullColor, 20), opacity(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Composite", "Zero"],
        desc=["Fill between composite sentiment and zero line", "Regime-colored fill"]
    )
}

// --- Individual Component Lines ---
if (showSkew) {
    plotLine(
        value=skewZ,
        width=1,
        colors=[opacity("#ab47bc", 50)],
        label=["Skew Z"],
        desc=["Return skewness z-score (asymmetric tail risk proxy)"]
    )
}
if (showFunding) {
    plotLine(
        value=fundingZ,
        width=1,
        colors=[opacity("#42a5f5", 50)],
        label=["Funding Z"],
        desc=["Funding rate z-score (perpetual futures sentiment)"]
    )
}
if (showOI) {
    plotLine(
        value=oiZ,
        width=1,
        colors=[opacity("#66bb6a", 50)],
        label=["OI Z"],
        desc=["Open interest delta z-score (positioning changes)"]
    )
}
if (showIV) {
    plotLine(
        value=ivZ,
        width=1,
        colors=[opacity("#ffa726", 50)],
        label=["IV Z"],
        desc=["Implied volatility z-score (ATR-based annualized vol proxy)"]
    )
}
if (showReturn) {
    plotLine(
        value=retZ,
        width=1,
        colors=[opacity("#ec407a", 50)],
        label=["Return Z"],
        desc=["Bar return z-score (price momentum)"]
    )
}

// --- Extreme Event Shape Markers ---
if (showShapes) {
    if (enterExtremeFear) {
        plotShape(
            value=composite,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Extreme Fear"],
            desc=["Entered extreme fear zone: potential bullish reversal (contrarian)"]
        )
    }
    if (exitExtremeFear) {
        plotShape(
            value=composite,
            shape="arrowup",
            color=fearColor,
            width=2,
            label=["Exit Fear"],
            desc=["Exited extreme fear zone: sentiment improving"]
        )
    }
    if (enterExtremeGreed) {
        plotShape(
            value=composite,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Extreme Greed"],
            desc=["Entered extreme greed zone: potential bearish reversal (contrarian)"]
        )
    }
    if (exitExtremeGreed) {
        plotShape(
            value=composite,
            shape="arrowdown",
            color=greedColor,
            width=2,
            label=["Exit Greed"],
            desc=["Exited extreme greed zone: sentiment cooling"]
        )
    }
    if (enterFear) {
        plotShape(
            value=composite,
            shape="circle",
            color=fearColor,
            width=2,
            label=["Fear Entry"],
            desc=["Entered fear zone"]
        )
    }
    if (enterGreed) {
        plotShape(
            value=composite,
            shape="circle",
            color=greedColor,
            width=2,
            label=["Greed Entry"],
            desc=["Entered greed zone"]
        )
    }
}

// -----------------------------------------------------------------------------
// 13. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeExtremeFear ? "EXTREME FEAR" : (regimeFear ? "FEAR" : (regimeGreed ? "GREED" : (regimeExtremeGreed ? "EXTREME GREED" : "NEUTRAL")))
    var regimeTextColor = regimeExtremeFear ? bullColor : (regimeFear ? fearColor : (regimeGreed ? greedColor : (regimeExtremeGreed ? bearColor : neutralColor)))

    plotTable(
        data=[
            ["ETH Sentiment Index — Perfected", regimeText],
            ["Composite", composite[0]],
            ["Skew Z", skewZ[0]],
            ["Funding Z", fundingZ[0]],
            ["OI Z", oiZ[0]],
            ["IV Z", ivZ[0]],
            ["Return Z", retZ[0]],
            ["Raw Composite", rawComposite[0]]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}