MM Flow
FlowScripts

Perfected FlowScript

Awesome Oscillator

Awesome Oscillator — Perfected Edition is indexed as 131_awesome_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

11.8 KB

Lines

401

Native Signal Candidates

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

6/6 guarded

Zero Up

line 306:9

Trigger

(showShapes) && (zeroUp)

Value

ao

Deps

showShapes:input, zeroUp:var

Zero Down

line 316:9

Trigger

(showShapes) && (zeroDn)

Value

ao

Deps

showShapes:input, zeroDn:var

Twin Peak Bull

line 328:9

Trigger

(showShapes) && (peakBull)

Value

ao

Deps

peakBull:var, showShapes:input

Twin Peak Bear

line 338:9

Trigger

(showShapes) && (peakBear)

Value

ao

Deps

peakBear:var, showShapes:input

Saucer Bull

line 350:9

Trigger

(showShapes) && (saucerBull)

Value

ao

Deps

saucerBull:var, showShapes:input

Saucer Bear

line 360:9

Trigger

(showShapes) && (saucerBear)

Value

ao

Deps

saucerBear:var, showShapes:input

131_awesome_oscillator.flowscript

source path: kscripts/perfected/131_awesome_oscillator.flowscript · sha256:663fbe37a185c12c17c2d27bb209eef73efb8c4208cdef214669fe11ed4ab5c9

hash verified
//@version=2
// ============================================================================
// Awesome Oscillator — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #awesomeoscillator, #ao, #billwilliams, #momentum, #histogram
//
// Production-grade Awesome Oscillator with Bill Williams' canonical 5/34 SMA
// of midpoint calculation, color-coded histogram by zero-line and acceleration,
// zero-line cross detection with shape markers, twin-peaks and saucer pattern
// detection, signal line smoothing, fill visualization, and comprehensive
// state tracking.
//
// Research papers underpinning this design:
//  1. Williams (1995), "New Trading Dimensions": canonical AO publication.
//     AO = SMA(5, Midpoint) − SMA(34, Midpoint). Three primary signals:
//     (1) Zero-line cross, (2) Twin peaks, (3) Saucer. Fixed 5/34 to prevent
//     over-optimization.
//  2. Wilder (1978), "New Concepts in Technical Trading Systems": ATR and ADX
//     framework underpins volatility context for AO momentum signals.
//  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing": time-series momentum profitable since 1880. AO as a
//     momentum/trend-following tool aligns with this century of evidence.
//  4. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers":
//     established momentum as a premier cross-sectional anomaly. Validates
//     AO's momentum-measurement role.
//  5. Ponnusamy & Manual (2016): experimental finding that RSI outperforms
//     MACD and Stochastic in reliability; multi-indicator confirmation
//     recommended. Underpins the AO + signal-line architecture.
// ============================================================================

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

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

// --- AO Settings ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=5,
    label="Fast SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="AO Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=34,
    label="Slow SMA Length",
    constraints={min: 5, max: 200, step: 1},
    group="AO Settings"
)

// --- Signal ---
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal (SMA of AO)",
    group="Signal"
)
var sigLen = input(
    name="sigLen",
    type="number",
    defaultValue=5,
    label="Signal SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Signal"
)

// --- Display ---
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show AO / Signal Fill",
    group="Display"
)
var showZero = input(
    name="showZero",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    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="Bullish Color",
    group="Display"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Display"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Signal Color",
    group="Display"
)

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

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

timeseries midpoint = (h + l) / 2.0

// -----------------------------------------------------------------------------
// 3. AO CALCULATION (Bill Williams fixed 5/34)
// -----------------------------------------------------------------------------
// AO = SMA(5, midpoint) - SMA(34, midpoint)
// Per Williams, the midpoint (not close) reduces impact of whipsaws
// from unusual closing prices.

timeseries smaFast = sma(midpoint, fastLen)
timeseries smaSlow = sma(midpoint, slowLen)
timeseries ao = smaFast - smaSlow

// -----------------------------------------------------------------------------
// 4. SIGNAL LINE
// -----------------------------------------------------------------------------
timeseries signal = sma(ao, sigLen)

// -----------------------------------------------------------------------------
// 5. HISTOGRAM COLOR LOGIC
// -----------------------------------------------------------------------------
// Four-color scheme per Williams:
//   Above zero + rising   = strong bull (bright green)
//   Above zero + falling  = weakening bull (dim green)
//   Below zero + falling  = strong bear (bright red)
//   Below zero + rising   = weakening bear (dim red)

timeseries aoPrev = nz(ao[1])
var aboveZero = ao > 0
var rising = ao > aoPrev

var histColor = ""
if (aboveZero && rising) {
    histColor = bullColor
} else if (aboveZero && !rising) {
    histColor = transparency(bullColor, 60)
} else if (!aboveZero && !rising) {
    histColor = bearColor
} else {
    histColor = transparency(bearColor, 60)
}

// -----------------------------------------------------------------------------
// 6. PATTERN DETECTION (static state tracking)
// -----------------------------------------------------------------------------
// --- Zero-line cross ---
var zeroUp = ao > 0 && ao[1] <= 0
var zeroDn = ao < 0 && ao[1] >= 0

// --- Twin Peaks ---
// Bullish twin peaks: two peaks below zero, second peak higher than first
// Bearish twin peaks: two peaks above zero, second peak lower than first
static lastPeakBelow = 0.0
static lastPeakAbove = 0.0
static lastPeakBelowBar = 0
static lastPeakAboveBar = 0

var peakBull = false
var peakBear = false

// A peak is a local maximum (AO > AO[1] && AO > AO[2])
// A trough is a local minimum (AO < AO[1] && AO < AO[2])

// For bullish twin peaks: we need a trough below zero
var isTrough = ao < 0 && ao > ao[1] && ao[1] < ao[2]
var isPeak = ao > 0 && ao < ao[1] && ao[1] > ao[2]

if (!isLiveUpdate) {
    if (isTrough) {
        // Check if previous trough exists and this one is higher
        if (lastPeakBelowBar > 0 && ao[1] > lastPeakBelow) {
            peakBull = true
        }
        lastPeakBelow = ao[1]
        lastPeakBelowBar = barIndex
    }
    if (isPeak) {
        // Check if previous peak exists and this one is lower
        if (lastPeakAboveBar > 0 && ao[1] < lastPeakAbove) {
            peakBear = true
        }
        lastPeakAbove = ao[1]
        lastPeakAboveBar = barIndex
    }
}

// --- Saucer Pattern ---
// Bullish saucer: AO > 0, and three consecutive bars where AO[i] > AO[i+1] > AO[i+2]
// Bearish saucer: AO < 0, and three consecutive bars where AO[i] < AO[i+1] < AO[i+2]
static saucerBullCount = 0
static saucerBearCount = 0

var saucerBull = false
var saucerBear = false

if (!isLiveUpdate) {
    if (ao > 0 && ao > ao[1] && ao[1] > ao[2]) {
        saucerBullCount = saucerBullCount + 1
        if (saucerBullCount >= 3) {
            saucerBull = true
            saucerBullCount = 0
        }
    } else {
        saucerBullCount = 0
    }

    if (ao < 0 && ao < ao[1] && ao[1] < ao[2]) {
        saucerBearCount = saucerBearCount + 1
        if (saucerBearCount >= 3) {
            saucerBear = true
            saucerBearCount = 0
        }
    } else {
        saucerBearCount = 0
    }
}

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

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

// --- Histogram ---
if (showHistogram) {
    plotBar(
        value=ao,
        colors=[histColor],
        width=1,
        label=["AO"],
        desc=["Awesome Oscillator: SMA(" + fastLen + ") − SMA(" + slowLen + ") of midpoint"]
    )
}

// --- Signal Line ---
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal"],
        desc=["SMA of AO (" + sigLen + ") — momentum signal line"]
    )
}

// --- AO / Signal Fill ---
if (showFill && showSignal) {
    var signalBull = ao > signal
    plotLine(
        value=[ao, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["AO", "Signal"],
        desc=["Fill between Awesome Oscillator and signal SMA"]
    )
}

// --- Alert Shapes ---
if (showShapes) {
    // Zero-line crosses
    if (zeroUp) {
        plotShape(
            value=ao,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Zero Up"],
            desc=["AO crossed above zero — bullish momentum shift"]
        )
    }
    if (zeroDn) {
        plotShape(
            value=ao,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Zero Down"],
            desc=["AO crossed below zero — bearish momentum shift"]
        )
    }

    // Twin peaks
    if (peakBull) {
        plotShape(
            value=ao,
            shape="arrowup",
            colorIndex=bullColor,
            width=2,
            label=["Twin Peak Bull"],
            desc=["Bullish twin peaks: higher trough below zero — reversal signal"]
        )
    }
    if (peakBear) {
        plotShape(
            value=ao,
            shape="arrowdown",
            colorIndex=bearColor,
            width=2,
            label=["Twin Peak Bear"],
            desc=["Bearish twin peaks: lower peak above zero — reversal signal"]
        )
    }

    // Saucer patterns
    if (saucerBull) {
        plotShape(
            value=ao,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Saucer Bull"],
            desc=["Bullish saucer: AO > 0 with three consecutive rising bars — momentum resumption"]
        )
    }
    if (saucerBear) {
        plotShape(
            value=ao,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Saucer Bear"],
            desc=["Bearish saucer: AO < 0 with three consecutive falling bars — momentum resumption"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = aboveZero ? "ABOVE ZERO" : "BELOW ZERO"
    var regimeTextColor = aboveZero ? bullColor : bearColor
    var momentumText = rising ? "ACCELERATING" : "DECELERATING"
    var momentumColor = rising ? bullColor : bearColor

    plotTable(
        data=[
            ["AO — Perfected", regimeText],
            ["AO", ao[0]],
            ["Signal", signal[0]],
            ["Momentum", momentumText],
            ["Fast SMA", smaFast[0]],
            ["Slow SMA", smaSlow[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
    )
}