MM Flow
FlowScripts

Perfected FlowScript

Swing Points • [Leviathan]

Swing Points — Fractal Structure & ATR Validation is indexed as 158_swing_points_leviathan.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.2 KB

Lines

440

Native Signal Candidates

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

9/9 guarded

HH

line 282:9

Trigger

(showSwingShapes) && (hhEvent)

Value

high

Deps

hhEvent:var, showSwingShapes:input

LH

line 292:9

Trigger

(showSwingShapes) && (lhEvent)

Value

high

Deps

lhEvent:var, showSwingShapes:input

HL

line 302:9

Trigger

(showSwingShapes) && (hlEvent)

Value

low

Deps

hlEvent:var, showSwingShapes:input

LL

line 312:9

Trigger

(showSwingShapes) && (llEvent)

Value

low

Deps

llEvent:var, showSwingShapes:input

HH

line 326:9

Trigger

(showStructureLabels) && (hhEvent)

Value

high

Deps

hhEvent:var, showStructureLabels:input

LH

line 336:9

Trigger

(showStructureLabels) && (lhEvent)

Value

high

Deps

lhEvent:var, showStructureLabels:input

HL

line 346:9

Trigger

(showStructureLabels) && (hlEvent)

Value

low

Deps

hlEvent:var, showStructureLabels:input

LL

line 356:9

Trigger

(showStructureLabels) && (llEvent)

Value

low

Deps

llEvent:var, showStructureLabels:input

Unlabeled shape

line 430:5

Trigger

(showTrendLabel && isLastBar)

Value

high

Deps

isLastBar:builtin, showTrendLabel:input

158_swing_points_leviathan.flowscript

source path: kscripts/perfected/158_swing_points_leviathan.flowscript · sha256:fa5b37d6813ab3ff7823ec571f1901c06f4afa61e715698eeb56c38bb6b444de

hash verified
//@version=2
// ============================================================================
// Swing Points — Production-Grade Fractal Swing Detection & Market Structure
// Author: Leviathan (@Leviathan) — Perfected by: kScript Perfection Engineer
// Tags: CORE, #swingpoints, #marketstructure, #pivotpoints, #fractal, #atr
//
// Automated detection and plotting of swing highs/lows as structural pivot
// points with ATR-based validation, fractal confirmation, color-coded trend
// lines, shape markers, and static state tracking for full market structure
// analysis (HH, LH, LL, HL classification).
//
// Academic foundations:
//  - Frykmer & Johnsson (2019), "Pivot Point Trading in the Foreign Exchange
//    Market: A Test for Market Efficiency". Found that exchange rates tend to
//    stop trending at pivot levels — a novel finding supporting the practical
//    utility of swing point detection. Inverse pivot implementation can be
//    profitable. Key concept: pivot levels act as trend-interruption points.
//  - Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete Resource
//    for Financial Market Technicians". Comprehensive practitioner survey showing
//    support/resistance levels (rating 4.41/5) and trend lines (4.39/5) are
//    among the most valued technical analysis tools. Swing highs/lows are the
//    structural building blocks of S/R and trend analysis.
//  - Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with Market
//    Profile". Market Profile's structural concepts (Initial Balance, single
//    prints, value area) rely on identifying key structural pivots. Swing
//    points are the price-action equivalent of these structural markers.
//  - Wilder (1978), "New Concepts in Technical Trading Systems". ATR as the
//    canonical volatility measure for adaptive thresholding and zone validation.
//  - Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//    (SSRN 5276088). Swing points are the structural levels targeted by
//    stop-hunting algorithms; ATR-based padding helps filter engineered sweeps.
// ============================================================================

define(title="Swing Points — Fractal Structure & ATR Validation", position="onchart", axis=false)

// === USER INPUTS ===
// --- Swing Detection ---
var left = input(name="left", type="number", defaultValue=5, label="Left Strength", constraints={min: 1, max: 50, step: 1}, group="Swing Detection")
var right = input(name="right", type="number", defaultValue=5, label="Right Strength", constraints={min: 1, max: 50, step: 1}, group="Swing Detection")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 100, step: 1}, group="Swing Detection")
var atrConfirmMult = input(name="atrConfirmMult", type="number", defaultValue=0.5, label="ATR Confirmation Multiple", constraints={min: 0.0, max: 3.0, step: 0.1}, group="Swing Detection")
var requireATRConfirm = input(name="requireATRConfirm", type="boolean", defaultValue=true, label="Require ATR Confirmation", group="Swing Detection")

// --- Display ---
var showSwingShapes = input(name="showSwingShapes", type="boolean", defaultValue=true, label="Show Swing Shape Markers", group="Display")
var showSwingLines = input(name="showSwingLines", type="boolean", defaultValue=true, label="Show Swing Trend Lines", group="Display")
var showStructureLabels = input(name="showStructureLabels", type="boolean", defaultValue=true, label="Show Structure Labels (HH/LH/LL/HL)", group="Display")
var showSwingZones = input(name="showSwingZones", type="boolean", defaultValue=true, label="Show Swing Zones", group="Display")
var showTrendLabel = input(name="showTrendLabel", type="boolean", defaultValue=true, label="Show Trend State Label", group="Display")

// --- Colors ---
var hhColor = input(name="hhColor", type="color", defaultValue="#26a69a", label="Higher High (HH) Color", group="Colors")
var hlColor = input(name="hlColor", type="color", defaultValue="#66bb6a", label="Higher Low (HL) Color", group="Colors")
var lhColor = input(name="lhColor", type="color", defaultValue="#ffa726", label="Lower High (LH) Color", group="Colors")
var llColor = input(name="llColor", type="color", defaultValue="#ef5350", label="Lower Low (LL) Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#ffffff", label="Trend Line Color", group="Colors")
var zoneColor = input(name="zoneColor", type="color", defaultValue="#ffffff", label="Swing Zone Color", group="Colors")

// === DATA SOURCES ===
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries open = price.open

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(open[0])) {
    return
}

// === COMPUTATION ===
// ATR (Wilder) for swing validation and zone sizing.
// TR = max(high - low, |high - close[1]|, |low - close[1]|)
// ATR = SMA(TR, atrLen)
timeseries prevClose = isnan(close[1]) ? close : close[1]
timeseries tr1 = high - low
timeseries tr2 = math.abs(high - prevClose)
timeseries tr3 = math.abs(low - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)
timeseries atrConfirm = atr * atrConfirmMult

// Swing detection: fractal confirmation at [left] bars ago confirmed when
// current bar completes the right-side lookback.
// Formula: P_high = H_{t-left} == max(H_{t-left:t+right}) AND H_{t-left} > max(H_{t-left+1:t})
// P_low = L_{t-left} == min(L_{t-left:t+right}) AND L_{t-left} < min(L_{t-left+1:t})
var isSwingHigh = high[left] == highest(high, left + right + 1) && high[left] > highest(high, left)
var isSwingLow = low[left] == lowest(low, left + right + 1) && low[left] < lowest(low, left)

// ATR-based validation: swing must exceed previous swing by at least ATR×mult
// to avoid false signals from noise (Frykmer & Johnsson 2019 trend-interruption).
// This filters out engineered wick spikes that don't represent true structure.

// Bar counter for event tracking.
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// --- STATIC STATE: Swing Tracking ---
static lastSwingHigh = 0.0
static lastSwingLow = 0.0
static prevSwingHigh = 0.0
static prevSwingLow = 0.0
static lastSwingHighBar = 0
static lastSwingLowBar = 0
static prevSwingHighBar = 0
static prevSwingLowBar = 0
static trend = 0  // 1 = bullish, -1 = bearish

// --- STATIC STATE: Confirmed Swings (ATR-validated) ---
static confirmedHigh = 0.0
static confirmedLow = 0.0
static confirmedHighBar = 0
static confirmedLowBar = 0
static prevConfirmedHigh = 0.0
static prevConfirmedLow = 0.0
static prevConfirmedHighBar = 0
static prevConfirmedLowBar = 0

// --- STATIC STATE: Structure Classification ---
static isHH = 0
static isLH = 0
static isHL = 0
static isLL = 0
static hhBar = 0
static lhBar = 0
static hlBar = 0
static llBar = 0

// --- STATIC STATE: Trend Lines ---
static trendLineStartPrice = 0.0
static trendLineEndPrice = 0.0
static trendLineStartBar = 0
static trendLineEndBar = 0
static trendLineActive = 0

// --- STATIC STATE: Session Tracking ---
static sessionSwingCount = 0
static sessionHHCount = 0
static sessionHLCount = 0
static sessionLHCount = 0
static sessionLLCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

// --- STATE UPDATE (only on bar close) ---
if (!isLiveUpdate) {
    // Track raw swings for ATR validation.
    if (isSwingHigh) {
        if (lastSwingHigh > 0) {
            prevSwingHigh = lastSwingHigh
            prevSwingHighBar = lastSwingHighBar
        }
        lastSwingHigh = high[left]
        lastSwingHighBar = barCount - left
    }

    if (isSwingLow) {
        if (lastSwingLow > 0) {
            prevSwingLow = lastSwingLow
            prevSwingLowBar = lastSwingLowBar
        }
        lastSwingLow = low[left]
        lastSwingLowBar = barCount - left
    }

    // ATR-based confirmation: only confirm swings that exceed previous by ATR threshold.
    // This filters noise and engineered wicks (Bhusal 2025 stop-hunt protection).
    if (isSwingHigh) {
        var atrValid = true
        if (requireATRConfirm && prevConfirmedHigh > 0) {
            atrValid = high[left] > prevConfirmedHigh + atrConfirm
        }

        if (atrValid) {
            if (confirmedHigh > 0) {
                prevConfirmedHigh = confirmedHigh
                prevConfirmedHighBar = confirmedHighBar
            }
            confirmedHigh = high[left]
            confirmedHighBar = barCount - left

            // Structure classification: HH vs LH
            if (prevConfirmedHigh > 0) {
                if (confirmedHigh > prevConfirmedHigh) {
                    isHH = 1
                    isLH = 0
                    hhBar = barCount - left
                    sessionHHCount = sessionHHCount + 1
                } else {
                    isHH = 0
                    isLH = 1
                    lhBar = barCount - left
                    sessionLHCount = sessionLHCount + 1
                }
            }

            // Trend determination: higher high = bullish structure
            if (trend != 1) {
                trend = 1
            }

            sessionSwingCount = sessionSwingCount + 1
        }
    }

    if (isSwingLow) {
        var atrValid = true
        if (requireATRConfirm && prevConfirmedLow > 0) {
            atrValid = low[left] < prevConfirmedLow - atrConfirm
        }

        if (atrValid) {
            if (confirmedLow > 0) {
                prevConfirmedLow = confirmedLow
                prevConfirmedLowBar = confirmedLowBar
            }
            confirmedLow = low[left]
            confirmedLowBar = barCount - left

            // Structure classification: HL vs LL
            if (prevConfirmedLow > 0) {
                if (confirmedLow > prevConfirmedLow) {
                    isHL = 1
                    isLL = 0
                    hlBar = barCount - left
                    sessionHLCount = sessionHLCount + 1
                } else {
                    isHL = 0
                    isLL = 1
                    llBar = barCount - left
                    sessionLLCount = sessionLLCount + 1
                }
            }

            // Trend determination: lower low = bearish structure
            if (trend != -1) {
                trend = -1
            }

            sessionSwingCount = sessionSwingCount + 1
        }
    }

    // Trend line tracking: connect consecutive swings of same type.
    if (isHH == 1 && prevConfirmedHigh > 0) {
        trendLineStartPrice = prevConfirmedHigh
        trendLineStartBar = prevConfirmedHighBar
        trendLineEndPrice = confirmedHigh
        trendLineEndBar = confirmedHighBar
        trendLineActive = 1
    }
    if (isLL == 1 && prevConfirmedLow > 0) {
        trendLineStartPrice = prevConfirmedLow
        trendLineStartBar = prevConfirmedLowBar
        trendLineEndPrice = confirmedLow
        trendLineEndBar = confirmedLowBar
        trendLineActive = 1
    }

    // Update session bar tracking.
    if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
        lastBarIndex = currentBarIndex
    }
}

// === EVENT FLAGS FOR PLOTTING ===
var hhEvent = hhBar == barCount - left
var lhEvent = lhBar == barCount - left
var hlEvent = hlBar == barCount - left
var llEvent = llBar == barCount - left

// Regime detection for color coding.
var regimeColor = trend == 1 ? hhColor : (trend == -1 ? llColor : "#ffffff")
var regimeLabel = trend == 1 ? "BULLISH STRUCTURE (HH/HL)" : (trend == -1 ? "BEARISH STRUCTURE (LL/LH)" : "NEUTRAL")

// === PLOTS: SWING SHAPE MARKERS ===
if (showSwingShapes) {
    if (hhEvent) {
        plotShape(
            value=high,
            shape="triangleup",
            colorIndex=hhColor,
            width=4,
            label=["HH"],
            desc=["Higher High: confirmed swing high exceeds previous swing high. Bullish structure."]
        )
    }
    if (lhEvent) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=lhColor,
            width=4,
            label=["LH"],
            desc=["Lower High: confirmed swing high fails to exceed previous swing high. Bearish structure."]
        )
    }
    if (hlEvent) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=hlColor,
            width=4,
            label=["HL"],
            desc=["Higher Low: confirmed swing low exceeds previous swing low. Bullish structure."]
        )
    }
    if (llEvent) {
        plotShape(
            value=low,
            shape="triangledown",
            colorIndex=llColor,
            width=4,
            label=["LL"],
            desc=["Lower Low: confirmed swing low fails to exceed previous swing low. Bearish structure."]
        )
    }
}

// === PLOTS: STRUCTURE LABELS (Diamond markers) ===
if (showStructureLabels) {
    if (hhEvent) {
        plotShape(
            value=high,
            shape="diamond",
            colorIndex=hhColor,
            width=3,
            label=["HH"],
            desc=["Higher High structural pivot. ATR-validated."]
        )
    }
    if (lhEvent) {
        plotShape(
            value=high,
            shape="diamond",
            colorIndex=lhColor,
            width=3,
            label=["LH"],
            desc=["Lower High structural pivot. ATR-validated."]
        )
    }
    if (hlEvent) {
        plotShape(
            value=low,
            shape="diamond",
            colorIndex=hlColor,
            width=3,
            label=["HL"],
            desc=["Higher Low structural pivot. ATR-validated."]
        )
    }
    if (llEvent) {
        plotShape(
            value=low,
            shape="diamond",
            colorIndex=llColor,
            width=3,
            label=["LL"],
            desc=["Lower Low structural pivot. ATR-validated."]
        )
    }
}

// === PLOTS: SWING ZONES (ATR-based support/resistance bands) ===
if (showSwingZones && confirmedHigh > 0) {
    var highZoneTop = confirmedHigh + atrConfirm
    var highZoneBot = confirmedHigh - atrConfirm
    plotLine(
        value=[highZoneTop, highZoneBot],
        width=1,
        colors=[opacity(zoneColor, 30), opacity(zoneColor, 30)],
        fill=opacity(zoneColor, 15),
        label=["Swing High Zone", "Swing High Zone"],
        desc=["ATR-validated swing high zone. Resistance region.", "Swing high zone bottom boundary."]
    )
}
if (showSwingZones && confirmedLow > 0) {
    var lowZoneTop = confirmedLow + atrConfirm
    var lowZoneBot = confirmedLow - atrConfirm
    plotLine(
        value=[lowZoneTop, lowZoneBot],
        width=1,
        colors=[opacity(zoneColor, 30), opacity(zoneColor, 30)],
        fill=opacity(zoneColor, 15),
        label=["Swing Low Zone", "Swing Low Zone"],
        desc=["ATR-validated swing low zone. Support region.", "Swing low zone bottom boundary."]
    )
}

// === PLOTS: TREND LINES ===
if (showSwingLines && trendLineActive == 1) {
    // Draw a line connecting consecutive swing points of the same structural type.
    // For HH/HL sequences: ascending trend line (support).
    // For LL/LH sequences: descending trend line (resistance).
    var lineColorUse = trend == 1 ? hhColor : (trend == -1 ? llColor : lineColor)
    plotLine(
        value=trendLineEndPrice,
        width=1,
        colors=[opacity(lineColorUse, 50)],
        label=["Trend Line"],
        desc=["Structural trend line connecting validated swing points."]
    )
}

// === PLOTS: LAST CONFIRMED SWING LEVELS (plotLine) ===
if (confirmedHigh > 0) {
    plotLine(
        value=confirmedHigh,
        width=1,
        colors=[opacity(hhColor, 40)],
        label=["Last Confirmed High"],
        desc=["Last ATR-validated swing high. Confirmed after right-side bars complete."]
    )
}
if (confirmedLow > 0) {
    plotLine(
        value=confirmedLow,
        width=1,
        colors=[opacity(llColor, 40)],
        label=["Last Confirmed Low"],
        desc=["Last ATR-validated swing low. Confirmed after right-side bars complete."]
    )
}

// === REGIME LABEL (plotPriceLabel) ===
if (showTrendLabel && isLastBar) {
    plotPriceLabel(
        price=high,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}