MM Flow
FlowScripts

Perfected FlowScript

Valuation

Valuation — Perfected Edition is indexed as 147_valuation.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

16.7 KB

Lines

562

Native Signal Candidates

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

6/6 guarded

Bull Div

line 467:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

compFinal

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 477:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

compFinal

Deps

bearDiv:var, enableDiv:input, showShapes:input

Cross Up

line 491:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Cross Down

line 501:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

Extreme High

line 511:9

Trigger

(showShapes) && (extremeHigh)

Value

bandStretch

Deps

extremeHigh:var, showShapes:input

Extreme Low

line 521:9

Trigger

(showShapes) && (extremeLow)

Value

-bandStretch

Deps

extremeLow:var, showShapes:input

147_valuation.flowscript

source path: kscripts/perfected/147_valuation.flowscript · sha256:c56a249664031eb1fffb3a995eecd6cb0f4e9d428a3dcdbf4b249562c6f90991

hash verified
//@version=2
// ============================================================================
// Valuation — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, SPECIALIZED, CORE, #funding, #oi, #zscore, #volume, #valuation
//
// Production-quality composite valuation oscillator. Averages z-scored
// components (VZO, Bollinger %B, Momentum, OI Delta, Funding, CCI, MVRV proxy,
// NVT proxy) into a single mean-reversion/trend-following line. Implements
// full stateful divergence detection, dynamic volatility-adjusted valuation
// bands, multi-regime color coding, fill/shape/histogram visualization, and a
// comprehensive regime table.
//
// Research papers underpinning this design:
//  1. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//     Stock Returns": seminal composite sentiment index using PCA of multiple
//     proxies; validates z-score aggregation of heterogeneous signals.
//  2. Fama & French (1993), "Common Risk Factors in the Returns on Stocks and
//     Bonds": multi-factor asset pricing framework; technical analogue to
//     factor model construction.
//  3. Bollinger (2001), "Bollinger on Bollinger Bands": %B as normalized
//     position within bands; direct component of this composite.
//  4. Wang, Zhuang & Feng (2022), "Intelligent Optimization Based Multi-Factor
//     Deep Learning Stock Selection Model": multi-factor selection methodology.
//  5. Woo (2019) / Santiment (2018): NVT Ratio = Network Value / Transaction
//     Volume; MVRV = Market Value / Realized Value. On-chain valuation
//     metrics for crypto assets. Approximated here with available price/volume.
// ============================================================================

define(
    title="Valuation — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Component Toggles ---
var useVzo = input(
    name="useVzo",
    type="boolean",
    defaultValue=true,
    label="Include VZO",
    group="Components"
)
var usePB = input(
    name="usePB",
    type="boolean",
    defaultValue=true,
    label="Include Bollinger %B",
    group="Components"
)
var useMom = input(
    name="useMom",
    type="boolean",
    defaultValue=true,
    label="Include Momentum",
    group="Components"
)
var useOiDelta = input(
    name="useOiDelta",
    type="boolean",
    defaultValue=true,
    label="Include OI Delta",
    group="Components"
)
var useFunding = input(
    name="useFunding",
    type="boolean",
    defaultValue=true,
    label="Include Funding",
    group="Components"
)
var useCci = input(
    name="useCci",
    type="boolean",
    defaultValue=true,
    label="Include CCI",
    group="Components"
)
var useMvrv = input(
    name="useMvrv",
    type="boolean",
    defaultValue=true,
    label="Include MVRV Proxy",
    group="Components"
)
var useNvt = input(
    name="useNvt",
    type="boolean",
    defaultValue=true,
    label="Include NVT Proxy",
    group="Components"
)

// --- Z-Score & Smoothing ---
var win = input(
    name="win",
    type="number",
    defaultValue=30,
    label="Z-Score Window",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score & Smoothing"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score & Smoothing"
)
var useEma = input(
    name="useEma",
    type="boolean",
    defaultValue=true,
    label="Use EMA (off=SMA)",
    group="Z-Score & Smoothing"
)

// --- Valuation Bands ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Reference Bands",
    group="Bands"
)
var bandColor = input(
    name="bandColor",
    type="color",
    defaultValue="#ff5252",
    label="Band Color",
    group="Bands"
)
var dynBands = input(
    name="dynBands",
    type="boolean",
    defaultValue=true,
    label="Dynamic Bands (volatility-adjusted)",
    group="Bands"
)
var bandVolLookback = input(
    name="bandVolLookback",
    type="number",
    defaultValue=20,
    label="Band Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Bands"
)

// --- Divergence ---
var enableDiv = input(
    name="enableDiv",
    type="boolean",
    defaultValue=true,
    label="Enable Divergence Detection",
    group="Divergence"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=10,
    label="Divergence Lookback",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)

// --- Display ---
var showZero = input(
    name="showZero",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    group="Display"
)
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var divBullColor = input(
    name="divBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Divergence Color",
    group="Colors"
)
var divBearColor = input(
    name="divBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Divergence Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#ab47bc",
    label="Composite Line Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

timeseries oiBybit = open_interest(symbol="BTCUSDT", exchange="BYBIT")
timeseries fBybit = funding_rate(symbol="BTCUSDT", exchange="BYBIT")

if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. COMPONENT CALCULATIONS
// -----------------------------------------------------------------------------

// --- COMPONENT 1: VZO (Volume Zone Oscillator) ---
timeseries mid = (h + l) / 2.0
timeseries buyV = (c >= mid) ? v : 0.0
timeseries sellV = (c < mid) ? v : 0.0
timeseries vzo = (buyV - sellV) / max(v, 1e-9) * 100.0
timeseries vzoZ = (vzo - sma(vzo, win)) / max(stdev(vzo, win), 1e-9)

// --- COMPONENT 2: BOLLINGER %B ---
timeseries bbBasis = sma(c, 20)
timeseries bbStd = stdev(c, 20)
timeseries bbUpper = bbBasis + 2.0 * bbStd
timeseries bbLower = bbBasis - 2.0 * bbStd
timeseries pctB = (c - bbLower) / max(bbUpper - bbLower, 1e-9)
timeseries pbZ = (pctB - sma(pctB, win)) / max(stdev(pctB, win), 1e-9)

// --- COMPONENT 3: MOMENTUM Z-SCORE ---
timeseries mom = c - nz(c[14])
timeseries momZ = (mom - sma(mom, win)) / max(stdev(mom, win), 1e-9)

// --- COMPONENT 4: OI DELTA Z ---
timeseries oiDelta = nz(oiBybit.close) - nz(oiBybit.close[1])
timeseries oidZ = (oiDelta - sma(oiDelta, win)) / max(stdev(oiDelta, win), 1e-9)

// --- COMPONENT 5: FUNDING Z ---
timeseries fZ = (fBybit - sma(fBybit, win)) / max(stdev(fBybit, win), 1e-9)

// --- COMPONENT 6: CCI (Commodity Channel Index) ---
timeseries tp = (h + l + c) / 3.0
timeseries tpSma = sma(tp, 20)
timeseries meanDev = rma(abs(tp - tpSma), 20)
timeseries cci = (tp - tpSma) / (0.015 * max(meanDev, 1e-9))
timeseries cciZ = (cci - sma(cci, win)) / max(stdev(cci, win), 1e-9)

// --- COMPONENT 7: MVRV PROXY (Price vs Long-Term Cost Basis) ---
timeseries realizedProxy = ema(c, 200)
timeseries mvrv = c / max(realizedProxy, 1e-9)
timeseries mvrvZ = (mvrv - sma(mvrv, win)) / max(stdev(mvrv, win), 1e-9)

// --- COMPONENT 8: NVT PROXY (Price Velocity / Volume Velocity) ---
timeseries nvt = c / max(sma(v, 50), 1e-9)
timeseries nvtZ = (nvt - sma(nvt, win)) / max(stdev(nvt, win), 1e-9)

// -----------------------------------------------------------------------------
// 4. COMPOSITE & SMOOTHING
// -----------------------------------------------------------------------------
timeseries compSum = 0.0
timeseries compCount = 0
if (useVzo) { compSum = compSum + vzoZ; compCount = compCount + 1 }
if (usePB) { compSum = compSum + pbZ; compCount = compCount + 1 }
if (useMom) { compSum = compSum + momZ; compCount = compCount + 1 }
if (useOiDelta) { compSum = compSum + oidZ; compCount = compCount + 1 }
if (useFunding) { compSum = compSum + fZ; compCount = compCount + 1 }
if (useCci) { compSum = compSum + cciZ; compCount = compCount + 1 }
if (useMvrv) { compSum = compSum + mvrvZ; compCount = compCount + 1 }
if (useNvt) { compSum = compSum + nvtZ; compCount = compCount + 1 }

timeseries composite = compSum / max(compCount, 1)

// Smoothing
timeseries compEma = ema(composite, smoothLen)
timeseries compSma = sma(composite, smoothLen)
timeseries compFinal = useEma ? compEma : compSma

// Signal line
timeseries signal = sma(compFinal, win)

// Momentum histogram
timeseries hist = compFinal - signal

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION (Overvalued / Undervalued / Neutral)
// -----------------------------------------------------------------------------
var regimeOvervalued = compFinal > 2.0
var regimeUndervalued = compFinal < -2.0
var regimeNeutral = !regimeOvervalued && !regimeUndervalued

var regimeColor = regimeOvervalued ? bearColor : (regimeUndervalued ? bullColor : lineColor)

// -----------------------------------------------------------------------------
// 6. DYNAMIC BANDS
// -----------------------------------------------------------------------------
timeseries compVol = stddev(compFinal, bandVolLookback)
var bandExtreme = dynBands ? 2.0 + compVol * 0.5 : 2.0
var bandStretch = dynBands ? 3.0 + compVol * 0.8 : 3.0
if (bandExtreme > 3.5) { bandExtreme = 3.5 }
if (bandStretch > 5.0) { bandStretch = 5.0 }

// -----------------------------------------------------------------------------
// 7. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
static prevCompHigh = -1.0
static prevPxHigh = -1.0
static prevCompLow = -1.0
static prevPxLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevCompHigh < 0) {
    prevCompHigh = compFinal[0]
    prevPxHigh = h[0]
    prevCompLow = compFinal[0]
    prevPxLow = l[0]
}

if (!isLiveUpdate && enableDiv) {
    // Bearish divergence: price higher high, composite lower high
    if (h[0] > prevPxHigh) {
        if (compFinal[0] < prevCompHigh) {
            bearDiv = true
        }
        prevPxHigh = h[0]
        prevCompHigh = compFinal[0]
    }

    // Bullish divergence: price lower low, composite higher low
    if (l[0] < prevPxLow) {
        if (compFinal[0] > prevCompLow) {
            bullDiv = true
        }
        prevPxLow = l[0]
        prevCompLow = compFinal[0]
    }
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = compFinal > signal && compFinal[1] <= signal[1]
var crossDown = compFinal < signal && compFinal[1] >= signal[1]
var extremeHigh = compFinal > bandStretch && compFinal[1] <= bandStretch
var extremeLow = compFinal < -bandStretch && compFinal[1] >= -bandStretch
var stretchHigh = compFinal > bandExtreme && compFinal[1] <= bandExtreme
var stretchLow = compFinal < -bandExtreme && compFinal[1] >= -bandExtreme

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero Line ---
if (showZero) {
    hline(value=0, color="#ffffff20", width=1)
}

// --- Reference Bands ---
if (showBands) {
    hline(value=bandStretch, color=transparency(bandColor, 60), width=1)
    hline(value=-bandStretch, color=transparency(bandColor, 60), width=1)
    hline(value=bandExtreme, color=transparency(bandColor, 40), width=1)
    hline(value=-bandExtreme, color=transparency(bandColor, 40), width=1)
}

// --- Composite Line (regime-colored) ---
plotLine(
    value=compFinal,
    width=2,
    colors=[regimeColor],
    label=["Valuation Composite"],
    desc=["Z-scored composite valuation oscillator"]
)

// --- Signal Line ---
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=["#ffffff"],
        label=["Signal"],
        desc=["SMA of composite valuation (" + win + ")"]
    )
}

// --- Signal Fill ---
if (showFill && showSignal) {
    var fillBull = compFinal > signal
    plotLine(
        value=[compFinal, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Composite", "Signal"],
        desc=["Fill between composite and signal"]
    )
}

// --- Momentum Histogram ---
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Momentum"],
        desc=["Histogram of composite minus signal"]
    )
}

// --- Divergence Shapes ---
if (showShapes && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=compFinal,
            shape="triangleup",
            colorIndex=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, composite higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=compFinal,
            shape="triangledown",
            colorIndex=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, composite lower high"]
        )
    }
}

// --- Alert Shapes ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["Composite crossed above signal"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["Composite crossed below signal"]
        )
    }
    if (extremeHigh) {
        plotShape(
            value=bandStretch,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["Extreme High"],
            desc=["Composite entered extreme overvalued zone"]
        )
    }
    if (extremeLow) {
        plotShape(
            value=-bandStretch,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["Extreme Low"],
            desc=["Composite entered extreme undervalued zone"]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeOvervalued ? "OVERVALUED" : (regimeUndervalued ? "UNDERVALUED" : "NEUTRAL")
    var regimeTextColor = regimeOvervalued ? bearColor : (regimeUndervalued ? bullColor : "#9e9e9e")

    plotTable(
        data=[
            ["Valuation — Perfected", regimeText],
            ["Composite", compFinal[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            ["Active Components", compCount[0]],
            ["MVRV Z", useMvrv ? mvrvZ[0] : "—"],
            ["NVT Z", useNvt ? nvtZ[0] : "—"]
        ],
        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
    )
}