MM Flow
FlowScripts

Perfected FlowScript

SCF Cuban's Reversion Bands

SCF Cuban's Reversion Bands [Perfected] is indexed as 057_scf_cubans_reversion_bands.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

14.6 KB

Lines

489

Native Signal Candidates

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

6/6 guarded

Band 2 High Touch

line 394:9

Trigger

(showBandTouch) && (touchB2Hi)

Value

b2Hi

Deps

showBandTouch:input, touchB2Hi:var

Band 2 Low Touch

line 404:9

Trigger

(showBandTouch) && (touchB2Lo)

Value

b2Lo

Deps

showBandTouch:input, touchB2Lo:var

Band 1 High Touch

line 414:9

Trigger

(showBandTouch) && (touchB1Hi && !touchB2Hi)

Value

b1Hi

Deps

showBandTouch:input, touchB1Hi:var, touchB2Hi:var

Band 1 Low Touch

line 424:9

Trigger

(showBandTouch) && (touchB1Lo && !touchB2Lo)

Value

b1Lo

Deps

showBandTouch:input, touchB1Lo:var, touchB2Lo:var

Basis Cross Up

line 438:9

Trigger

(showBasisCross) && (basisCrossUp)

Value

low

Deps

basisCrossUp:var, showBasisCross:input

Basis Cross Down

line 448:9

Trigger

(showBasisCross) && (basisCrossDown)

Value

high

Deps

basisCrossDown:var, showBasisCross:input

057_scf_cubans_reversion_bands.flowscript

source path: kscripts/perfected/057_scf_cubans_reversion_bands.flowscript · sha256:76974fa8067fbd7f328d42496657fc85ae32b286859bdddac6ee3f7d210117fd

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

// ============================================================================
// SCF Cuban's Reversion Bands [Perfected]
// Author: SoulzBTC (@SoulzBTC) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #meanreversion, #bollinger, #keltner, #bands, #contrarian
//
// Production-quality mean-reversion bands combining Bollinger-style standard
// deviation bands and Keltner-style ATR bands with an adaptive centerline
// (EMA/SMA selectable). Features regime color coding, fill between bands,
// shape markers for band touches and centerline crosses, and static session
// tracking for per-session band anchoring.
//
// Research papers underpinning this design:
//  - Bollinger (2001), "Bollinger on Bollinger Bands": σ-based bands answer
//    "Are prices high or low on a relative basis?"; %B and BandWidth measures.
//  - Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//    autocorrelation at medium horizons validates contrarian entries at extremes.
//  - Leung & Chong (2003), "An Empirical Comparison of Moving Average Envelopes
//    and Bollinger Bands": BB superior at capturing abrupt fluctuations;
//    ATR-based bands (Keltner) smoother in trending conditions.
//  - Keltner (1960), "How to Make Money in Commodities": original volatility
//    channel concept using MA of typical price with high-low range bands.
//  - Wilder (1978), "New Concepts in Technical Trading Systems": ATR as
//    volatility measure; smoothed true range for adaptive band width.
// ============================================================================

define(
    title="SCF Cuban's Reversion Bands [Perfected]",
    position="onchart",
    axis=false
)

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

// --- Basis ---
var basisType = input(
    name="basisType",
    type="select",
    defaultValue="EMA",
    label="Basis Type",
    options=["SMA", "EMA", "KAMA"],
    group="Basis"
)
var basisLen = input(
    name="basisLen",
    type="number",
    defaultValue=20,
    label="Basis Length",
    constraints={min: 5, max: 200, step: 1},
    group="Basis"
)

// --- Band Type ---
var bandType = input(
    name="bandType",
    type="select",
    defaultValue="Bollinger",
    label="Band Type",
    options=["Bollinger", "Keltner", "Hybrid"],
    group="Bands"
)
var bandMult = input(
    name="bandMult",
    type="number",
    defaultValue=2.0,
    label="Band Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Bands"
)
var band1Mult = input(
    name="band1Mult",
    type="number",
    defaultValue=1.0,
    label="Inner Band Multiplier",
    constraints={min: 0.25, max: 5.0, step: 0.1},
    group="Bands"
)
var band2Mult = input(
    name="band2Mult",
    type="number",
    defaultValue=2.0,
    label="Outer Band Multiplier",
    constraints={min: 0.5, max: 8.0, step: 0.1},
    group="Bands"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length (Keltner)",
    constraints={min: 5, max: 50, step: 1},
    group="Bands"
)
var showBand1 = input(
    name="showBand1",
    type="boolean",
    defaultValue=true,
    label="Show Band 1",
    group="Bands"
)
var showBand2 = input(
    name="showBand2",
    type="boolean",
    defaultValue=true,
    label="Show Band 2",
    group="Bands"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fills",
    group="Bands"
)

// --- Session Anchoring ---
var useSessionAnchor = input(
    name="useSessionAnchor",
    type="boolean",
    defaultValue=false,
    label="Use Session Anchor",
    group="Session"
)

// --- Display ---
var showBasis = input(
    name="showBasis",
    type="boolean",
    defaultValue=true,
    label="Show Centerline",
    group="Display"
)
var showBandTouch = input(
    name="showBandTouch",
    type="boolean",
    defaultValue=true,
    label="Show Band Touch Shapes",
    group="Display"
)
var showBasisCross = input(
    name="showBasisCross",
    type="boolean",
    defaultValue=true,
    label="Show Basis Cross Shapes",
    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 ---
var basisColor = input(
    name="basisColor",
    type="color",
    defaultValue="#ff9800",
    label="Basis Color",
    group="Colors"
)
var bandUpColor = input(
    name="bandUpColor",
    type="color",
    defaultValue="#26a69a",
    label="Band Up / Bull Color",
    group="Colors"
)
var bandDnColor = input(
    name="bandDnColor",
    type="color",
    defaultValue="#ef5350",
    label="Band Down / Bear Color",
    group="Colors"
)
var touchColor = input(
    name="touchColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Touch Shape Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries o = bars.open
timeseries src = (high + low + close) / 3.0

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

// ---------------------------------------------------------------------------
// 3. SESSION ANCHOR DETECTION (static variables for per-session tracking)
// ---------------------------------------------------------------------------
var day_id = math.floor(t / 86400000)

static last_day_id = -1
static sess_barCount = 0

var newSession = last_day_id != -1 && day_id > last_day_id
last_day_id = day_id

if (newSession || sess_barCount == 0) {
    sess_barCount = 1
} else {
    sess_barCount = sess_barCount + 1
}

var activeLen = useSessionAnchor ? sess_barCount : basisLen

// ---------------------------------------------------------------------------
// 4. BASIS COMPUTATION
// ---------------------------------------------------------------------------
timeseries basis = 0.0
if (basisType == "SMA") {
    basis = sma(source=src, period=activeLen)
} else if (basisType == "EMA") {
    basis = ema(source=src, period=activeLen)
} else {
    // KAMA-like adaptive basis (Kaufman Adaptive Moving Average)
    timeseries change = abs(src - src[activeLen])
    timeseries vol = sum(abs(src - src[1]), activeLen)
    timeseries er = vol > 0 ? change / vol : 0.0
    timeseries fastAlpha = 2.0 / (2.0 + 1.0)
    timeseries slowAlpha = 2.0 / (30.0 + 1.0)
    timeseries sc = (er * (fastAlpha - slowAlpha) + slowAlpha)
    timeseries alpha = sc * sc
    alpha = math.min(math.max(alpha, slowAlpha * slowAlpha), fastAlpha * fastAlpha)

    static kamaBasis = 0.0
    if (kamaBasis == 0.0 || isnan(kamaBasis)) {
        kamaBasis = src
    }
    kamaBasis = alpha * src + (1.0 - alpha) * kamaBasis
    basis = kamaBasis
}

// ---------------------------------------------------------------------------
// 5. BAND WIDTH COMPUTATION (Bollinger / Keltner / Hybrid)
// ---------------------------------------------------------------------------
timeseries bandWidth = 0.0

if (bandType == "Bollinger") {
    // Standard deviation of source around basis
    timeseries dev = src - basis
    timeseries varSum = sum(dev * dev, activeLen)
    timeseries variance = activeLen > 0 ? varSum / activeLen : 0
    bandWidth = math.sqrt(math.max(0, variance))
} else if (bandType == "Keltner") {
    // ATR-based band width
    timeseries tr1 = high - low
    timeseries tr2 = abs(high - close[1])
    timeseries tr3 = abs(low - close[1])
    timeseries tr = math.max(tr1, math.max(tr2, tr3))
    timeseries atr = ema(source=tr, period=atrLen)
    bandWidth = atr
} else {
    // Hybrid: average of Bollinger SD and Keltner ATR
    timeseries dev = src - basis
    timeseries varSum = sum(dev * dev, activeLen)
    timeseries variance = activeLen > 0 ? varSum / activeLen : 0
    timeseries bbWidth = math.sqrt(math.max(0, variance))

    timeseries tr1 = high - low
    timeseries tr2 = abs(high - close[1])
    timeseries tr3 = abs(low - close[1])
    timeseries tr = math.max(tr1, math.max(tr2, tr3))
    timeseries atr = ema(source=tr, period=atrLen)

    bandWidth = (bbWidth + atr) / 2.0
}

// Band levels
timeseries b1Hi = basis + band1Mult * bandWidth
timeseries b1Lo = basis - band1Mult * bandWidth
timeseries b2Hi = basis + band2Mult * bandWidth
timeseries b2Lo = basis - band2Mult * bandWidth

// ---------------------------------------------------------------------------
// 6. REGIME DETECTION (color coding by price position)
// ---------------------------------------------------------------------------
var aboveBasis = close > basis
var touchB1Hi = high >= b1Hi && low <= b1Hi
var touchB1Lo = high >= b1Lo && low <= b1Lo
var touchB2Hi = high >= b2Hi && low <= b2Hi
var touchB2Lo = high >= b2Lo && low <= b2Lo
var basisCrossUp = cross(close, basis) && close > basis
var basisCrossDown = cross(close, basis) && close < basis

// Regime: 0 = neutral (inside band1), 1 = above upper band1, -1 = below lower band1
var regime = close > b1Hi ? 1 : (close < b1Lo ? -1 : 0)
var regimeColor = regime > 0 ? bandUpColor : (regime < 0 ? bandDnColor : basisColor)

// ---------------------------------------------------------------------------
// 7. PLOTTING
// ---------------------------------------------------------------------------

// --- Centerline (regime-colored) ---
if (showBasis) {
    plotLine(
        value=basis,
        width=lineWidth,
        colors=[bandUpColor, bandDnColor, basisColor],
        colorIndex=regime > 0 ? 0 : (regime < 0 ? 1 : 2),
        label=["Basis (" + basisType + ")"],
        desc=["Centerline basis: " + basisType + " of typical price"]
    )
}

// --- Band 1 Fill & Lines ---
if (showBand1) {
    if (showFill) {
        var fillBull = regime >= 0
        plotLine(
            value=([b1Lo, b1Hi]),
            width=1,
            colors=[transparency(bandUpColor, 12), transparency(bandDnColor, 12)],
            colorIndex=fillBull ? 0 : 1,
            fill=true,
            label=["Band 1 Fill"],
            desc=["Fill between ±1× band width"]
        )
    }
    plotLine(
        value=b1Hi,
        width=1,
        colors=[transparency(bandUpColor, 40)],
        label=["Band 1 Upper"],
        desc=["Upper band at " + band1Mult + "× band width"]
    )
    plotLine(
        value=b1Lo,
        width=1,
        colors=[transparency(bandDnColor, 40)],
        label=["Band 1 Lower"],
        desc=["Lower band at " + band1Mult + "× band width"]
    )
}

// --- Band 2 Fill & Lines ---
if (showBand2) {
    if (showFill) {
        var fillBull2 = regime >= 0
        plotLine(
            value=([b2Lo, b2Hi]),
            width=1,
            colors=[transparency(bandUpColor, 6), transparency(bandDnColor, 6)],
            colorIndex=fillBull2 ? 0 : 1,
            fill=true,
            label=["Band 2 Fill"],
            desc=["Fill between ±2× band width"]
        )
    }
    plotLine(
        value=b2Hi,
        width=1,
        colors=[transparency(bandUpColor, 25)],
        label=["Band 2 Upper"],
        desc=["Upper band at " + band2Mult + "× band width"]
    )
    plotLine(
        value=b2Lo,
        width=1,
        colors=[transparency(bandDnColor, 25)],
        label=["Band 2 Lower"],
        desc=["Lower band at " + band2Mult + "× band width"]
    )
}

// --- Band Touch Shapes ---
if (showBandTouch) {
    if (touchB2Hi) {
        plotShape(
            value=b2Hi,
            shape="triangledown",
            colorIndex=touchColor,
            width=shapeSize,
            label=["Band 2 High Touch"],
            desc=["Price touched upper band 2 — extreme overbought / mean reversion zone"]
        )
    }
    if (touchB2Lo) {
        plotShape(
            value=b2Lo,
            shape="triangleup",
            colorIndex=touchColor,
            width=shapeSize,
            label=["Band 2 Low Touch"],
            desc=["Price touched lower band 2 — extreme oversold / mean reversion zone"]
        )
    }
    if (touchB1Hi && !touchB2Hi) {
        plotShape(
            value=b1Hi,
            shape="circle",
            colorIndex=transparency(bandUpColor, 50),
            width=shapeSize,
            label=["Band 1 High Touch"],
            desc=["Price touched upper band 1"]
        )
    }
    if (touchB1Lo && !touchB2Lo) {
        plotShape(
            value=b1Lo,
            shape="circle",
            colorIndex=transparency(bandDnColor, 50),
            width=shapeSize,
            label=["Band 1 Low Touch"],
            desc=["Price touched lower band 1"]
        )
    }
}

// --- Basis Cross Shapes ---
if (showBasisCross) {
    if (basisCrossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=bandUpColor,
            width=shapeSize,
            label=["Basis Cross Up"],
            desc=["Price crossed above basis centerline"]
        )
    }
    if (basisCrossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=bandDnColor,
            width=shapeSize,
            label=["Basis Cross Down"],
            desc=["Price crossed below basis centerline"]
        )
    }
}

// ---------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime > 0 ? "ABOVE BANDS" : (regime < 0 ? "BELOW BANDS" : "INSIDE BANDS")
    var regimeTextColor = regime > 0 ? bandUpColor : (regime < 0 ? bandDnColor : basisColor)
    var bandTypeLabel = bandType + " (" + basisType + ")"

    plotTable(
        data=[
            ["Reversion Bands", regimeText],
            ["Basis", basis[0]],
            ["Band Width", bandWidth[0]],
            ["Upper Band 2", b2Hi[0]],
            ["Lower Band 2", b2Lo[0]],
            ["Type", bandTypeLabel]
        ],
        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
    )
}