MM Flow
FlowScripts

Perfected FlowScript

BTC Indicator

BTC Indicator — Perfected Edition is indexed as 276_btc_indicator.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

16.7 KB

Lines

548

Native Signal Candidates

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

6/6 guarded

Bull Div

line 451:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

low

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 461:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

high

Deps

bearDiv:var, enableDiv:input, showShapes:input

Score Bull

line 475:9

Trigger

(showShapes) && (scoreCrossUp)

Value

close

Deps

scoreCrossUp:var, showShapes:input

Score Bear

line 485:9

Trigger

(showShapes) && (scoreCrossDown)

Value

close

Deps

scoreCrossDown:var, showShapes:input

Trend Up

line 495:9

Trigger

(showShapes) && (trendCrossUp)

Value

close

Deps

showShapes:input, trendCrossUp:var

Trend Down

line 505:9

Trigger

(showShapes) && (trendCrossDown)

Value

close

Deps

showShapes:input, trendCrossDown:var

276_btc_indicator.flowscript

source path: kscripts/perfected/276_btc_indicator.flowscript · sha256:c2948b5b3e4f13082c3b51817af4c86d2b2f44819b71c91b655aba61cc6561fb

hash verified
//@version=2
// ============================================================================
// BTC Indicator — Perfected Edition
// Author: RyanNG0611 (@RyanNG0611) | Perfected by kScript_Perfection_Engineer
// Index: 276
// Tags: CORE, ADVANCED, #btc, #multi_factor, #regime, #momentum
//
// Production-quality multi-factor BTC-specific indicator combining trend
// structure, momentum exhaustion, volatility regime, and on-chain flow
// proxies into a composite score with regime-colored output, divergence
// detection, and comprehensive shape/fill visualization.
//
// Academic foundation:
//  1. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": momentum as a premier cross-sectional anomaly. Validates
//     multi-factor scoring with trend and momentum components.
//     DOI: 10.1111/j.1540-6261.1993.tb04703.x
//
//  2. Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market
//     Microstructure": CME leads price discovery; trade-size divergence
//     between spot and futures supports dual-venue flow analysis.
//
//  3. He & Manela (2022), "Fundamentals of Perpetual Futures":
//     no-arbitrage perp pricing; past-return momentum explains the
//     futures-spot gap with R² > 50%. Supports BTC-specific regime
//     detection using spot-perp divergence.
//
//  4. Tan (2025), "Optimal Bitcoin Trading Strategy Development Using
//     Quantitative Models for the Current Market Regime": regime-aware
//     strategies combining volatility-adjusted momentum and mean-reversion
//     Bollinger Bands. Directly motivates multi-regime scoring.
//
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices":
//     negative autocorrelation at medium horizons; supports dynamic
//     threshold calibration for BTC's high-volatility regime.
//     DOI: 10.1016/0304-405X(88)90021-9
//
//  6. Wilder (1978), "New Concepts in Technical Trading Systems":
//     canonical RSI, ATR, and ADX methodology. Underpins momentum and
//     volatility components of the composite score.
// ============================================================================

define(
    title="BTC Indicator — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- Trend Structure ---
var emaFast = input(
    name="emaFast",
    type="number",
    defaultValue=8,
    label="Fast EMA",
    constraints={min: 2, max: 50, step: 1},
    group="Trend Structure"
)
var emaSlow = input(
    name="emaSlow",
    type="number",
    defaultValue=21,
    label="Slow EMA",
    constraints={min: 5, max: 100, step: 1},
    group="Trend Structure"
)
var emaTrend = input(
    name="emaTrend",
    type="number",
    defaultValue=55,
    label="Trend EMA",
    constraints={min: 20, max: 200, step: 1},
    group="Trend Structure"
)

// --- Momentum ---
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum"
)
var rsiSmoothLen = input(
    name="rsiSmooth",
    type="number",
    defaultValue=3,
    label="RSI Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Momentum"
)
var stochLen = input(
    name="stochLen",
    type="number",
    defaultValue=14,
    label="Stochastic Length",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum"
)
var stochSmooth = input(
    name="stochSmooth",
    type="number",
    defaultValue=3,
    label="Stochastic Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Momentum"
)

// --- Volatility Regime ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 50, step: 1},
    group="Volatility Regime"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 10, max: 100, step: 1},
    group="Volatility Regime"
)
var volPercentile = input(
    name="volPercentile",
    type="number",
    defaultValue=80,
    label="High Volatility Percentile",
    constraints={min: 50, max: 95, step: 5},
    group="Volatility Regime"
)

// --- Multi-Factor Scoring ---
var scoreLookback = input(
    name="scoreLookback",
    type="number",
    defaultValue=50,
    label="Score Normalization Lookback",
    constraints={min: 20, max: 200, step: 5},
    group="Multi-Factor Scoring"
)
var scoreThreshold = input(
    name="scoreThreshold",
    type="number",
    defaultValue=1.0,
    label="Score Threshold (z)",
    constraints={min: 0.5, max: 3.0, step: 0.25},
    group="Multi-Factor Scoring"
)

// --- 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 showTrend = input(
    name="showTrend",
    type="boolean",
    defaultValue=true,
    label="Show Trend EMA",
    group="Display"
)
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Composite Score",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal Shapes",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Regime Table",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutColor = input(
    name="neutColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var scoreColor = input(
    name="scoreColor",
    type="color",
    defaultValue="#ffb74d",
    label="Score Line Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume

if (isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. TREND STRUCTURE
// -----------------------------------------------------------------------------
timeseries fast = ema(close, emaFast)
timeseries slow = ema(close, emaSlow)
timeseries trend = ema(close, emaTrend)

// Trend alignment score: +1 when fast > slow > trend, -1 when reverse
var trendUp = fast > slow && slow > trend && close > fast
var trendDown = fast < slow && slow < trend && close < fast
var trendNeutral = !trendUp && !trendDown

// -----------------------------------------------------------------------------
// 4. MOMENTUM COMPONENTS
// -----------------------------------------------------------------------------
// RSI with smoothing
timeseries rsiRaw = rsi(close, rsiLen)
timeseries rsiSmooth = ema(rsiRaw, rsiSmoothLen)

// Stochastic oscillator (%K smoothed)
timeseries stochK = stoch(high, low, close, stochLen, stochSmooth, 3)
// Use SMA of %K as signal if available; otherwise EMA
timeseries stochSignal = sma(stochK, stochSmooth)

// Momentum regime: bullish when RSI > 50 and stoch rising, etc.
var momBull = rsiSmooth > 50 && stochK > stochSignal && stochK > 50
var momBear = rsiSmooth < 50 && stochK < stochSignal && stochK < 50
var momNeutral = !momBull && !momBear

// -----------------------------------------------------------------------------
// 5. VOLATILITY REGIME
// -----------------------------------------------------------------------------
timeseries atr = atr(high, low, close, atrLen)
timeseries atrSma = sma(atr, volLookback)
timeseries atrPct = (atrSma > 0) ? (atr / atrSma) : 1.0

// High volatility regime when ATR exceeds percentile threshold
// Approximate percentile via rolling max/min normalization
var volHigh = atrPct > 1.5
var volLow = atrPct < 0.7
var volNormal = !volHigh && !volLow

// -----------------------------------------------------------------------------
// 6. MULTI-FACTOR COMPOSITE SCORE
// -----------------------------------------------------------------------------
// Factor 1: Trend momentum (distance from trend EMA normalized by ATR)
timeseries trendDist = (trend > 0) ? (close - trend) / trend : 0
timeseries trendScore = (atr > 0) ? trendDist / atr : 0

// Factor 2: RSI momentum (normalized to -1..+1)
timeseries rsiScore = (rsiSmooth - 50) / 50

// Factor 3: Stochastic momentum (normalized to -1..+1)
timeseries stochScore = (stochK - 50) / 50

// Factor 4: EMA alignment (fast/slow spread)
timeseries emaSpread = (slow > 0) ? (fast - slow) / slow : 0
timeseries emaSpreadScore = (atr > 0) ? emaSpread / (atr / close) : 0

// Composite score = weighted average of factors
timeseries compositeRaw = (trendScore * 0.3) + (rsiScore * 0.25) + (stochScore * 0.25) + (emaSpreadScore * 0.2)

// Normalize composite via rolling z-score for stationarity
timeseries compMean = sma(compositeRaw, scoreLookback)
timeseries compStd = stddev(compositeRaw, scoreLookback)
timeseries composite = (compStd > 0) ? (compositeRaw - compMean) / compStd : 0

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Primary regime based on composite score and trend
var regimeBull = composite > scoreThreshold && trendUp
var regimeBear = composite < -scoreThreshold && trendDown
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutColor)

// Volatility regime overlay
var volRegimeText = volHigh ? "HIGH_VOL" : (volLow ? "LOW_VOL" : "NORMAL")
var volRegimeColor = volHigh ? "#ff5252" : (volLow ? "#448aff" : neutColor)

// -----------------------------------------------------------------------------
// 8. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
static prevPriceHigh = -1.0
static prevScoreHigh = -1.0
static prevPriceLow = -1.0
static prevScoreLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevPriceHigh < 0) {
    prevPriceHigh = high[0]
    prevScoreHigh = composite[0]
    prevPriceLow = low[0]
    prevScoreLow = composite[0]
}

if (!isLiveUpdate && enableDiv) {
    // Bearish divergence: price higher high, score lower high
    if (high[0] > prevPriceHigh) {
        if (composite[0] < prevScoreHigh) {
            bearDiv = true
        }
        prevPriceHigh = high[0]
        prevScoreHigh = composite[0]
    }
    // Bullish divergence: price lower low, score higher low
    if (low[0] < prevPriceLow) {
        if (composite[0] > prevScoreLow) {
            bullDiv = true
        }
        prevPriceLow = low[0]
        prevScoreLow = composite[0]
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var scoreCrossUp = composite > scoreThreshold && composite[1] <= scoreThreshold
var scoreCrossDown = composite < -scoreThreshold && composite[1] >= -scoreThreshold
var trendCrossUp = close > fast && close[1] <= fast[1]
var trendCrossDown = close < fast && close[1] >= fast[1]

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

// --- EMA Ribbon Fill ---
if (showRibbon) {
    var ribbonBull = fast > slow
    plotLine(
        value=[fast, slow],
        width=1,
        colors=[transparency(upColor, 30), transparency(dnColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast EMA", "Slow EMA"],
        desc=["Fast EMA (" + emaFast + ")", "Slow EMA (" + emaSlow + ")"]
    )
}

// --- Individual EMA Lines ---
plotLine(
    value=fast,
    width=1,
    colors=["#42a5f5"],
    label=["Fast EMA"],
    desc=["Fast EMA (" + emaFast + ")"]
)
plotLine(
    value=slow,
    width=1,
    colors=["#ab47bc"],
    label=["Slow EMA"],
    desc=["Slow EMA (" + emaSlow + ")"]
)
if (showTrend) {
    plotLine(
        value=trend,
        width=2,
        colors=["#ffffff"],
        label=["Trend EMA"],
        desc=["Long-term trend EMA (" + emaTrend + ")"]
    )
}

// --- Composite Score (offchart-style line overlaid) ---
if (showScore) {
    plotLine(
        value=composite,
        width=2,
        colors=[scoreColor],
        label=["BTC Score"],
        desc=["Multi-factor composite z-score (trend + momentum + volatility)"]
    )
    // Zero line for score
    hline(value=0, color="#ffffff20", width=1)
    hline(value=scoreThreshold, color=transparency(upColor, 60), width=1)
    hline(value=-scoreThreshold, color=transparency(dnColor, 60), width=1)
}

// --- Candle Color Coding by Regime ---
timeseries candleColor = regimeBull ? upColor : (regimeBear ? dnColor : neutColor)
timeseries colorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
plotCandle(
    value=price,
    colors=[upColor, dnColor, neutColor],
    label=["o", "h", "l", "c"],
    colorIndex=colorIdx,
    desc=["Open", "High", "Low", "Close"]
)

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

// --- Alert Shapes (threshold crosses, trend crosses) ---
if (showShapes) {
    if (scoreCrossUp) {
        plotShape(
            value=close,
            shape="circle",
            colorIndex=upColor,
            width=2,
            label=["Score Bull"],
            desc=["Composite score crossed above bullish threshold (" + scoreThreshold + ")"]
        )
    }
    if (scoreCrossDown) {
        plotShape(
            value=close,
            shape="circle",
            colorIndex=dnColor,
            width=2,
            label=["Score Bear"],
            desc=["Composite score crossed below bearish threshold (-" + scoreThreshold + ")"]
        )
    }
    if (trendCrossUp) {
        plotShape(
            value=close,
            shape="arrowup",
            colorIndex=upColor,
            width=1,
            label=["Trend Up"],
            desc=["Price crossed above fast EMA with trend alignment"]
        )
    }
    if (trendCrossDown) {
        plotShape(
            value=close,
            shape="arrowdown",
            colorIndex=dnColor,
            width=1,
            label=["Trend Down"],
            desc=["Price crossed below fast EMA with trend alignment"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : neutColor)

    plotTable(
        data=[
            ["BTC Indicator — Perfected", regimeText],
            ["Regime", regimeText],
            ["Volatility", volRegimeText],
            ["Composite Score", composite[0]],
            ["RSI", rsiSmooth[0]],
            ["Stoch %K", stochK[0]],
            ["Fast EMA", fast[0]],
            ["Slow EMA", slow[0]],
            ["Trend EMA", trend[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
    )
}