MM Flow
FlowScripts

Perfected FlowScript

Stochastic Oscillator

Stochastic Oscillator — Perfected Edition is indexed as 121_stochastic_oscillator.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

13.4 KB

Lines

486

Native Signal Candidates

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

6/6 guarded

Bull Div

line 391:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

k

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 401:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

k

Deps

bearDiv:var, enableDiv:input, showShapes:input

Cross Up

line 415:9

Trigger

(showShapes) && (crossUp)

Value

k

Deps

crossUp:var, showShapes:input

Cross Down

line 425:9

Trigger

(showShapes) && (crossDn)

Value

k

Deps

crossDn:var, showShapes:input

OB Enter

line 435:9

Trigger

(showShapes) && (obEnter)

Value

obLevel

Deps

obEnter:var, showShapes:input

OS Enter

line 445:9

Trigger

(showShapes) && (osEnter)

Value

osLevel

Deps

osEnter:var, showShapes:input

121_stochastic_oscillator.flowscript

source path: kscripts/perfected/121_stochastic_oscillator.flowscript · sha256:597593967a4752ddbc3e61190b62a3797029b233c2010a92fb01007f5a977bd7

hash verified
//@version=2
// ============================================================================
// Stochastic Oscillator — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #stochastic, #oscillator, #meanreversion, #divergence, #momentum
//
// Production-quality Lane Stochastic Oscillator with full stateful divergence
// detection, overbought/oversold zone fills, momentum histogram, %K/%D fill,
// and multi-regime color coding. Implements the canonical Lane formula with
// configurable slowing and signal smoothing.
//
// Research papers underpinning this design:
//  1. Lane (1950s), "Lane's Stochastic Oscillator". The original publication.
//     Lane stated it "doesn't follow price, it doesn't follow volume... It
//     follows the speed or the momentum of price. As a rule, the momentum
//     changes direction before price."
//     [Formula] %K = 100 × (Close − Lown) / (Highn − Lown); %D = SMA(%K, 3).
//  2. Wilder (1978), "New Concepts in Technical Trading Systems". Wilder's
//     work on momentum indicators (RSI, ATR, ADX) established the mathematical
//     rigor for range-bound oscillators. The 0-100 scale and divergence
//     detection methodology parallel Wilder's RSI framework.
//  3. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns". The most comprehensive early
//     academic study using 90 years of DJIA data. Found every trading rule
//     significantly outperformed cash benchmarks.
//     DOI: https://doi.org/10.1016/0304-405X(92)90022-K
//  4. Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability
//     in Technical Analysis". Found RSI outperformed MACD and Stochastic in
//     signal reliability; multi-indicator confirmation recommended.
//  5. Murphy (1999), "Technical Analysis of the Financial Markets". Divergence
//     as a leading reversal signal — price/indicator disagreement at extremes
//     precedes regime shifts. Underpins the stateful divergence engine.
// ============================================================================

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

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

// --- Stochastic Settings ---
var kLen = input(
    name="kLen",
    type="number",
    defaultValue=14,
    label="%K Length",
    constraints={min: 2, max: 50, step: 1},
    group="Stochastic Settings"
)
var dLen = input(
    name="dLen",
    type="number",
    defaultValue=3,
    label="%D Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Stochastic Settings"
)
var smoothK = input(
    name="smoothK",
    type="number",
    defaultValue=1,
    label="%K Slowing",
    constraints={min: 1, max: 10, step: 1},
    group="Stochastic Settings"
)
var dSmoothType = input(
    name="dSmoothType",
    type="select",
    defaultValue="SMA",
    label="%D Smoothing Type",
    options=["SMA", "EMA"],
    group="Stochastic Settings"
)

// --- Thresholds ---
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=80,
    label="Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=20,
    label="Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)

// --- 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 (pivot bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)

// --- Display ---
var showK = input(
    name="showK",
    type="boolean",
    defaultValue=true,
    label="Show %K Line",
    group="Display"
)
var showD = input(
    name="showD",
    type="boolean",
    defaultValue=true,
    label="Show %D Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show %K/%D Fill",
    group="Display"
)
var showObOs = input(
    name="showObOs",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zones",
    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 kColor = input(
    name="kColor",
    type="color",
    defaultValue="#26a69a",
    label="%K Color",
    group="Colors"
)
var dColor = input(
    name="dColor",
    type="color",
    defaultValue="#ef5350",
    label="%D 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"
)

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

if (isnan(c[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. STOCHASTIC CALCULATION — canonical Lane implementation
// -----------------------------------------------------------------------------
// %K = 100 × (Close − Lown) / (Highn − Lown)
// Slow %K = EMA(rawK, smoothK) if smoothK > 1, else rawK
// %D = SMA(%K, dLen) or EMA(%K, dLen) per user toggle

timeseries hh = highest(h, kLen)
timeseries ll = lowest(l, kLen)
timeseries range = hh - ll

timeseries rawK = 100.0 * (c - ll) / max(range, 1e-9)

timeseries k = (smoothK > 1) ? ema(rawK, smoothK) : rawK

timeseries d = (dSmoothType == "EMA") ? ema(k, dLen) : sma(k, dLen)

// Momentum histogram (%K − %D)
timeseries hist = k - d

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
//   Bullish: %K > %D AND %K > 50
//   Bearish: %K < %D AND %K < 50
//   Neutral: everything else (chop zone)

var regimeBull = k > d && k > 50
var regimeBear = k < d && k < 50
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

// OB/OS state
var inOB = k > obLevel
var inOS = k < osLevel

// -----------------------------------------------------------------------------
// 5. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, %K disagrees.

static prevPxHigh = -1.0
static prevPxLow = -1.0
static prevKHigh = -1.0
static prevKLow = -1.0

var bearDiv = false
var bullDiv = false

// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
    prevPxHigh = h[0]
    prevKHigh = k[0]
    prevPxLow = l[0]
    prevKLow = k[0]
}

if (!isLiveUpdate && enableDiv) {
    // --- Regular Bearish Divergence ---
    // Price makes a higher high; %K makes a lower high
    if (h[0] > prevPxHigh) {
        if (k[0] < prevKHigh) {
            bearDiv = true
        }
        prevPxHigh = h[0]
        prevKHigh = k[0]
    }

    // --- Regular Bullish Divergence ---
    // Price makes a lower low; %K makes a higher low
    if (l[0] < prevPxLow) {
        if (k[0] > prevKLow) {
            bullDiv = true
        }
        prevPxLow = l[0]
        prevKLow = k[0]
    }
}

// -----------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = k > d && k[1] <= d[1]
var crossDn = k < d && k[1] >= d[1]
var obEnter = k > obLevel && k[1] <= obLevel
var osEnter = k < osLevel && k[1] >= osLevel
var obExit = k < obLevel && k[1] >= obLevel
var osExit = k > osLevel && k[1] <= osLevel

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

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

// --- OB / OS Zone Fills ---
if (showObOs) {
    timeseries obTop = 100
    timeseries obBot = obLevel
    timeseries osTop = osLevel
    timeseries osBot = 0

    plotLine(
        value=[obTop, obBot],
        width=1,
        colors=[transparency(bearColor, 15)],
        fill=true,
        label=["OB Zone"],
        desc=["Overbought zone fill (" + obLevel + "–100)"]
    )
    plotLine(
        value=[osTop, osBot],
        width=1,
        colors=[transparency(bullColor, 15)],
        fill=true,
        label=["OS Zone"],
        desc=["Oversold zone fill (0–" + osLevel + ")"]
    )

    hline(value=obLevel, color=transparency(bearColor, 50), width=1)
    hline(value=osLevel, color=transparency(bullColor, 50), width=1)
}

// --- %K / %D Ribbon Fill ---
if (showFill) {
    var kAboveD = k > d
    plotLine(
        value=[k, d],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=kAboveD ? 0 : 1,
        fill=true,
        label=["%K", "%D"],
        desc=["Fill between %K and %D"]
    )
}

// --- %K Line (regime-colored) ---
if (showK) {
    plotLine(
        value=k,
        width=2,
        colors=[regimeColor],
        label=["%K"],
        desc=["Smoothed %K (Lane " + kLen + ")"]
    )
}

// --- %D Line ---
if (showD) {
    plotLine(
        value=d,
        width=1,
        colors=[dColor],
        label=["%D"],
        desc=["%D signal line (" + dSmoothType + " " + dLen + ")"]
    )
}

// --- 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=["Stoch Momentum"],
        desc=["Histogram of %K minus %D"]
    )
}

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

// --- Alert Shapes (crossovers, OB/OS) ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=k,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["%K crossed above %D"]
        )
    }
    if (crossDn) {
        plotShape(
            value=k,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["%K crossed below %D"]
        )
    }
    if (obEnter) {
        plotShape(
            value=obLevel,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["OB Enter"],
            desc=["%K entered overbought zone (>" + obLevel + ")"]
        )
    }
    if (osEnter) {
        plotShape(
            value=osLevel,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["OS Enter"],
            desc=["%K entered oversold zone (<" + osLevel + ")"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

    plotTable(
        data=[
            ["Stochastic — Perfected", regimeText],
            ["%K", k[0]],
            ["%D", d[0]],
            ["Momentum", hist[0]],
            ["OB Level", obLevel],
            ["OS Level", osLevel],
            ["Divergence", enableDiv ? "On" : "Off"]
        ],
        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
    )
}