MM Flow
FlowScripts

Perfected FlowScript

Harmonic Oscillator

Harmonic Oscillator — Perfected Edition is indexed as 151_harmonic_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

20.3 KB

Lines

692

Native Signal Candidates

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

8/8 guarded

BSR Buy

line 559:9

Trigger

(showShapes) && (bullSig)

Value

bsr

Deps

bullSig:var, showShapes:input

BSR Sell

line 569:9

Trigger

(showShapes) && (bearSig)

Value

bsr

Deps

bearSig:var, showShapes:input

BSR OB

line 579:9

Trigger

(showShapes) && (bsrExtremeHigh)

Value

bsr

Deps

bsrExtremeHigh:var, showShapes:input

BSR OS

line 589:9

Trigger

(showShapes) && (bsrExtremeLow)

Value

bsr

Deps

bsrExtremeLow:var, showShapes:input

Cycle Peak

line 601:9

Trigger

(showShapes) && (peak)

Value

sine

Deps

peak:var, showShapes:input

Cycle Trough

line 611:9

Trigger

(showShapes) && (trough)

Value

sine

Deps

showShapes:input, trough:var

Phase Q1

line 621:9

Trigger

(showShapes) && (sineCrossUp)

Value

sine

Deps

showShapes:input, sineCrossUp:var

Phase Q3

line 631:9

Trigger

(showShapes) && (sineCrossDn)

Value

sine

Deps

showShapes:input, sineCrossDn:var

151_harmonic_oscillator.flowscript

source path: kscripts/perfected/151_harmonic_oscillator.flowscript · sha256:b829a5ccf8ce45995e53b66dbae1c68d190e2bf137641bbbc85a1391dac32d09

hash verified
//@version=2
// ============================================================================
// Harmonic Oscillator — Perfected Edition
// Author: Crypto Catipal (@Crypto Catipal) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, CORE, #trend, #volume, #volatility, #BSR, #harmonic, #cycle, #phase
//
// Production-quality dual-core oscillator combining (1) a Buy/Sell Ratio (BSR)
// momentum oscillator with overbought/oversold thresholds and MA cross signals,
// and (2) a price-based Harmonic Oscillator using detrended price cyclic
// components, phase-quadrant detection, and dynamic cycle-length estimation
// via zero-crossing analysis. Provides comprehensive fill, shape, histogram,
// and regime visualization with full static state tracking.
//
// Research papers underpinning this design:
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//     quote-midpoint comparison + tick test for buy/sell classification;
//     ~85–93% accuracy. Underpins BSR volume classification.
//  2. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns": extreme order imbalances predict return reversals.
//     Validates BSR overbought/oversold threshold logic.
//  3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     ΔP ≈ λ × OFI; linear relationship between flow imbalance and price changes.
//     Supports BSR extremes as reversal predictors.
//  4. Ehlers (2001), "Rocket Science for Traders": Hilbert-transform-based
//     sinewave indicator; dominant cycle estimation via zero crossings.
//     Underpins the price-based harmonic oscillator and phase detection.
//  5. Hurst (1951), "Long-Term Storage Capacity of Reservoirs": cycle
//     persistence and mean-reversion. Validates cycle-length estimation from
//     price oscillations as a regime detection tool.
// ============================================================================

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

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

// --- BSR Settings ---
var bsrLen = input(
    name="bsrLen",
    type="number",
    defaultValue=14,
    label="BSR Length",
    constraints={min: 5, max: 50, step: 1},
    group="BSR Settings"
)
var fastMA = input(
    name="fastMA",
    type="number",
    defaultValue=5,
    label="Fast MA",
    constraints={min: 2, max: 50, step: 1},
    group="BSR Settings"
)
var slowMA = input(
    name="slowMA",
    type="number",
    defaultValue=20,
    label="Slow MA",
    constraints={min: 5, max: 100, step: 1},
    group="BSR Settings"
)
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=0.7,
    label="Overbought Level",
    constraints={min: 0.1, max: 0.99, step: 0.05},
    group="BSR Settings"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=-0.7,
    label="Oversold Level",
    constraints={min: -0.99, max: -0.1, step: 0.05},
    group="BSR Settings"
)

// --- Harmonic Oscillator ---
var cycleLen = input(
    name="cycleLen",
    type="number",
    defaultValue=20,
    label="Cycle Length (seed)",
    constraints={min: 8, max: 100, step: 1},
    group="Harmonic Oscillator"
)
var smoothCycle = input(
    name="smoothCycle",
    type="number",
    defaultValue=3,
    label="Cycle Smoothing",
    constraints={min: 1, max: 10, step: 1},
    group="Harmonic Oscillator"
)
var minCycle = input(
    name="minCycle",
    type="number",
    defaultValue=8,
    label="Min Estimated Cycle",
    constraints={min: 4, max: 50, step: 1},
    group="Harmonic Oscillator"
)
var maxCycle = input(
    name="maxCycle",
    type="number",
    defaultValue=60,
    label="Max Estimated Cycle",
    constraints={min: 10, max: 200, step: 1},
    group="Harmonic Oscillator"
)

// --- Display ---
var showBSR = input(
    name="showBSR",
    type="boolean",
    defaultValue=true,
    label="Show BSR Lines",
    group="Display"
)
var showBSRFill = input(
    name="showBSRFill",
    type="boolean",
    defaultValue=true,
    label="Show BSR Fast/Slow Fill",
    group="Display"
)
var showHarmonic = input(
    name="showHarmonic",
    type="boolean",
    defaultValue=true,
    label="Show Harmonic Sine Wave",
    group="Display"
)
var showHarmonicFill = input(
    name="showHarmonicFill",
    type="boolean",
    defaultValue=true,
    label="Show Harmonic Fill",
    group="Display"
)
var showPhaseColors = input(
    name="showPhaseColors",
    type="boolean",
    defaultValue=true,
    label="Color-Code by Phase",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Cycle / BSR Shapes",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show BSR Histogram",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Guide Lines",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ff1744",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var maUp = input(
    name="maUp",
    type="color",
    defaultValue="#26a69a",
    label="MA Bull Color",
    group="Colors"
)
var maDn = input(
    name="maDn",
    type="color",
    defaultValue="#ef5350",
    label="MA Bear Color",
    group="Colors"
)
var q1Color = input(
    name="q1Color",
    type="color",
    defaultValue="#00e676",
    label="Phase Q1 (Rise/Above)",
    group="Colors"
)
var q2Color = input(
    name="q2Color",
    type="color",
    defaultValue="#69f0ae",
    label="Phase Q2 (Fall/Above)",
    group="Colors"
)
var q3Color = input(
    name="q3Color",
    type="color",
    defaultValue="#ff1744",
    label="Phase Q3 (Fall/Below)",
    group="Colors"
)
var q4Color = input(
    name="q4Color",
    type="color",
    defaultValue="#ff8a80",
    label="Phase Q4 (Rise/Below)",
    group="Colors"
)

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

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

// -----------------------------------------------------------------------------
// 3. BUY/SELL RATIO (BSR) — Lee-Ready style proxy
// -----------------------------------------------------------------------------
// Volume classification: up-bar → 100% buy-initiated; down-bar → 100% sell-initiated.
// Lee & Ready (1991) showed this simple tick-test achieves ~85% accuracy vs.
// quote-midpoint classification. The BSR is then smoothed and bounded to [−1, +1].

var isUp = close >= open
timeseries buyVol = isUp ? volume : volume * 0.5
timeseries sellVol = isUp ? volume * 0.5 : volume
timeseries netVol = buyVol - sellVol
timeseries totalVol = buyVol + sellVol

// Smoothed Buy/Sell Ratio in [−1, +1]
timeseries buyAvg = sma(buyVol, bsrLen)
timeseries sellAvg = sma(sellVol, bsrLen)
var bsrDenom = buyAvg + sellAvg
timeseries bsr = bsrDenom > 0 ? (buyAvg - sellAvg) / bsrDenom : 0.0

// Moving averages of BSR
timeseries fast = ema(bsr, fastMA)
timeseries slow = ema(bsr, slowMA)

// BSR momentum histogram
timeseries bsrHist = fast - slow

// -----------------------------------------------------------------------------
// 4. HARMONIC OSCILLATOR — price-based sine wave with phase detection
// -----------------------------------------------------------------------------
// Inspired by Ehlers' sinewave indicator: detrend price, estimate dominant cycle
// via zero crossings, accumulate phase, and generate sine/cosine waves.
// Phase quadrants (Q1–Q4) map to ascending/descending above/below zero.

// 4a. Smoothing (Ehlers 4-bar weighted smoothing)
timeseries smooth4 = (close + 2.0 * close[1] + 2.0 * close[2] + close[3]) / 6.0

// 4b. Detrended price oscillator (cycle component)
timeseries detrend = smooth4 - ema(smooth4, cycleLen)

// 4c. Normalize by rolling standard deviation
timeseries detStd = stddev(detrend, cycleLen)
var detNorm = detStd > 0 ? detrend / detStd : 0.0

// 4d. Smooth the normalized cycle
timeseries cycleSmooth = ema(detNorm, smoothCycle)

// 4e. Cycle identification via zero crossings
// Tracks time between successive zero crossings to estimate the dominant cycle length.
static lastCrossBar = 0
static lastCrossDir = 0
static estCycleLen = 20.0

var crossUp = cycleSmooth > 0 && !isnan(cycleSmooth[1]) && cycleSmooth[1] <= 0
var crossDn = cycleSmooth < 0 && !isnan(cycleSmooth[1]) && cycleSmooth[1] >= 0

if (!isLiveUpdate && (crossUp || crossDn)) {
    if (lastCrossDir != 0 && lastCrossBar > 0) {
        var barsSince = bar_index[0] - lastCrossBar
        // Half-cycle (zero to zero) → full cycle estimate
        var newCycle = barsSince * 2.0
        // Smooth transition: EMA-style update of the cycle estimate
        estCycleLen = 0.7 * estCycleLen + 0.3 * newCycle
        // Clamp to bounds
        estCycleLen = math.max(minCycle, math.min(maxCycle, estCycleLen))
    }
    lastCrossBar = bar_index[0]
    lastCrossDir = crossUp ? 1 : -1
}

// 4f. Phase accumulator
// Accumulates phase at rate 2π / estCycleLen, wrapping at 2π.
static phase = 0.0
var phaseInc = 2.0 * 3.141592653589793 / estCycleLen

if (!isLiveUpdate) {
    phase = phase + phaseInc
    if (phase > 2.0 * 3.141592653589793) {
        phase = phase - 2.0 * 3.141592653589793
    }
}

// 4g. Sine and Cosine waves (harmonic oscillator outputs)
timeseries sine = math.sin(phase)
timeseries lead = math.cos(phase)

// 4h. Phase quadrant detection
// Q1: sine > 0, lead > 0  (rising, above zero)
// Q2: sine > 0, lead < 0  (falling, above zero)
// Q3: sine < 0, lead < 0  (falling, below zero)
// Q4: sine < 0, lead > 0  (rising, below zero)

var phaseQ = 0
var phaseColor = neutralColor
if (sine > 0) {
    if (lead > 0) {
        phaseQ = 1
        phaseColor = q1Color
    } else {
        phaseQ = 2
        phaseColor = q2Color
    }
} else {
    if (lead < 0) {
        phaseQ = 3
        phaseColor = q3Color
    } else {
        phaseQ = 4
        phaseColor = q4Color
    }
}

// 4i. Cycle extreme detection (peak / trough)
// Peak: sine > sine[1] and sine > sine[2] (local maximum)
// Trough: sine < sine[1] and sine < sine[2] (local minimum)

var peak = !isnan(sine[1]) && !isnan(sine[2]) && sine > sine[1] && sine > sine[2]
var trough = !isnan(sine[1]) && !isnan(sine[2]) && sine < sine[1] && sine < sine[2]

// Crossover of sine and lead (quadrant change signal)
var sineCrossUp = sine > lead && !isnan(sine[1]) && sine[1] <= lead[1]
var sineCrossDn = sine < lead && !isnan(sine[1]) && sine[1] >= lead[1]

// -----------------------------------------------------------------------------
// 5. BSR SIGNAL DETECTION
// -----------------------------------------------------------------------------
var maCrossUp = crossover(fast, slow)
var maCrossDn = crossunder(fast, slow)
var overbought = bsr > obLevel
var oversold = bsr < osLevel

// Bullish signal: BSR was oversold AND fast MA crosses above slow MA
var bullSig = oversold[1] && maCrossUp
// Bearish signal: BSR was overbought AND fast MA crosses below slow MA
var bearSig = overbought[1] && maCrossDn

// BSR extreme shapes (independent of MA cross)
var bsrExtremeHigh = bsr > obLevel && !isnan(bsr[1]) && bsr[1] <= obLevel
var bsrExtremeLow = bsr < osLevel && !isnan(bsr[1]) && bsr[1] >= osLevel

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime based on both harmonic oscillator and BSR for confirmation.
//   Bullish: sine > 0 (Q1/Q2) AND fast > slow (BSR momentum positive)
//   Bearish: sine < 0 (Q3/Q4) AND fast < slow (BSR momentum negative)
//   Neutral: everything else (phase/BSR disagreement)

var regimeBull = sine > 0 && fast > slow
var regimeBear = sine < 0 && fast < slow
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)

// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static cyclePeakCount = 0
static cycleTroughCount = 0
static sessionHighBSR = -1.0
static sessionLowBSR = 1.0
static lastBarIndex = 0
static totalCycles = 0.0

var currentBarIndex = bar_index[0]

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

    // BSR session extremes
    if (bsr > sessionHighBSR) {
        sessionHighBSR = bsr
    }
    if (bsr < sessionLowBSR) {
        sessionLowBSR = bsr
    }

    // Regime transitions
    var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Cycle extreme counting
    if (peak) {
        cyclePeakCount = cyclePeakCount + 1
    }
    if (trough) {
        cycleTroughCount = cycleTroughCount + 1
    }

    // Running average of estimated cycle length
    totalCycles = totalCycles + estCycleLen
}

// Initialize on first bar
if (sessionHighBSR < -0.5) {
    sessionHighBSR = bsr
    sessionLowBSR = bsr
    lastRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
}

// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------

// --- Guide lines ---
if (showGuides) {
    hline(value=obLevel, color=transparency(dnColor, 60), width=1)
    hline(value=osLevel, color=transparency(upColor, 60), width=1)
    hline(value=0, color="#ffffff20", width=1)
    hline(value=1, color=transparency(q1Color, 20), width=1)
    hline(value=-1, color=transparency(q3Color, 20), width=1)
}

// --- BSR Fast & Slow Lines with Fill ---
if (showBSR) {
    plotLine(
        value=fast,
        width=2,
        colors=[maUp],
        label=["Fast MA"],
        desc=["Fast EMA of BSR (" + fastMA + ")"]
    )
    plotLine(
        value=slow,
        width=2,
        colors=[maDn],
        label=["Slow MA"],
        desc=["Slow EMA of BSR (" + slowMA + ")"]
    )
}

if (showBSRFill) {
    var bsrBull = fast > slow
    plotLine(
        value=[fast, slow],
        width=1,
        colors=[transparency(maUp, 25), transparency(maDn, 25)],
        colorIndex=bsrBull ? 0 : 1,
        fill=true,
        label=["Fast MA", "Slow MA"],
        desc=["BSR fast/slow ribbon fill"]
    )
}

// --- BSR Histogram (fast minus slow) ---
if (showHistogram) {
    var histBull = bsrHist >= 0
    plotBar(
        value=bsrHist,
        colors=[transparency(upColor, 50), transparency(dnColor, 50)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["BSR Momentum"],
        desc=["BSR fast MA minus slow MA histogram"]
    )
}

// --- Harmonic Sine Wave (phase-colored) ---
if (showHarmonic) {
    var sinColor = showPhaseColors ? phaseColor : upColor
    plotLine(
        value=sine,
        width=2,
        colors=[sinColor],
        label=["Sine"],
        desc=["Price-based harmonic sine wave (cycle " + estCycleLen + ")"]
    )
    plotLine(
        value=lead,
        width=1,
        colors=[transparency(neutralColor, 60)],
        label=["Cosine (Lead)"],
        desc=["Leading cosine wave (90° phase shift)"]
    )
}

// --- Harmonic Fill (sine vs zero) ---
if (showHarmonicFill) {
    var harmBull = sine > 0
    plotLine(
        value=[sine, 0],
        width=1,
        colors=[transparency(upColor, 15), transparency(dnColor, 15)],
        colorIndex=harmBull ? 0 : 1,
        fill=true,
        label=["Sine", "Zero"],
        desc=["Harmonic oscillator fill between sine wave and zero line"]
    )
}

// --- BSR Signal Shapes ---
if (showShapes) {
    if (bullSig) {
        plotShape(
            value=bsr,
            shape="triangleup",
            color=upColor,
            width=3,
            label=["BSR Buy"],
            desc=["BSR oversold + fast MA crossed above slow MA"]
        )
    }
    if (bearSig) {
        plotShape(
            value=bsr,
            shape="triangledown",
            color=dnColor,
            width=3,
            label=["BSR Sell"],
            desc=["BSR overbought + fast MA crossed below slow MA"]
        )
    }
    if (bsrExtremeHigh) {
        plotShape(
            value=bsr,
            shape="xcross",
            color=dnColor,
            width=2,
            label=["BSR OB"],
            desc=["BSR entered overbought zone (" + obLevel + ")"]
        )
    }
    if (bsrExtremeLow) {
        plotShape(
            value=bsr,
            shape="xcross",
            color=upColor,
            width=2,
            label=["BSR OS"],
            desc=["BSR entered oversold zone (" + osLevel + ")"]
        )
    }

    // --- Harmonic Cycle Shapes ---
    if (peak) {
        plotShape(
            value=sine,
            shape="diamond",
            color=q2Color,
            width=3,
            label=["Cycle Peak"],
            desc=["Harmonic oscillator cycle peak detected (phase Q2)"]
        )
    }
    if (trough) {
        plotShape(
            value=sine,
            shape="diamond",
            color=q4Color,
            width=3,
            label=["Cycle Trough"],
            desc=["Harmonic oscillator cycle trough detected (phase Q4)"]
        )
    }
    if (sineCrossUp) {
        plotShape(
            value=sine,
            shape="circle",
            color=q1Color,
            width=2,
            label=["Phase Q1"],
            desc=["Sine crossed above cosine — entering Q1 (ascending, above zero)"]
        )
    }
    if (sineCrossDn) {
        plotShape(
            value=sine,
            shape="circle",
            color=q3Color,
            width=2,
            label=["Phase Q3"],
            desc=["Sine crossed below cosine — entering Q3 (descending, below zero)"]
        )
    }
}

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

    var phaseText = (phaseQ == 1) ? "Q1 (Rise/Above)"
        : (phaseQ == 2) ? "Q2 (Fall/Above)"
        : (phaseQ == 3) ? "Q3 (Fall/Below)"
        : "Q4 (Rise/Below)"
    var phaseTextColor = (phaseQ == 1) ? q1Color
        : (phaseQ == 2) ? q2Color
        : (phaseQ == 3) ? q3Color
        : q4Color

    var avgCycle = (currentBarIndex > 0) ? (totalCycles / currentBarIndex) : estCycleLen

    plotTable(
        data=[
            ["Harmonic Oscillator — Perfected", regimeText],
            ["Phase", phaseText],
            ["BSR", bsr],
            ["Fast MA", fast],
            ["Slow MA", slow],
            ["Sine", sine],
            ["Cosine", lead],
            ["Est. Cycle", estCycleLen],
            ["Avg Cycle", avgCycle],
            ["BSR Session High", sessionHighBSR],
            ["BSR Session Low", sessionLowBSR],
            ["Peaks", cyclePeakCount],
            ["Troughs", cycleTroughCount],
            ["Regime Changes", regimeChangeCount]
        ],
        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=9,
        cellPadding=3
    )
}