MM Flow
FlowScripts

Perfected FlowScript

Key Levels • [Leviathan]

Key Levels [Leviathan] Perfected is indexed as 077_key_levels_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

27.2 KB

Lines

632

Native Signal Candidates

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

9/9 guarded

Day H Touch

line 584:9

Trigger

(showTouchMarkers && anyTouch) && (touchDayH)

Value

valDayH

Deps

anyTouch:var, showTouchMarkers:input, touchDayH:var

Day L Touch

line 587:9

Trigger

(showTouchMarkers && anyTouch) && (touchDayL)

Value

valDayL

Deps

anyTouch:var, showTouchMarkers:input, touchDayL:var

Week H Touch

line 590:9

Trigger

(showTouchMarkers && anyTouch) && (touchWeekH)

Value

valWeekH

Deps

anyTouch:var, showTouchMarkers:input, touchWeekH:var

Week L Touch

line 593:9

Trigger

(showTouchMarkers && anyTouch) && (touchWeekL)

Value

valWeekL

Deps

anyTouch:var, showTouchMarkers:input, touchWeekL:var

Month H Touch

line 596:9

Trigger

(showTouchMarkers && anyTouch) && (touchMonthH)

Value

valMonthH

Deps

anyTouch:var, showTouchMarkers:input, touchMonthH:var

Month L Touch

line 599:9

Trigger

(showTouchMarkers && anyTouch) && (touchMonthL)

Value

valMonthL

Deps

anyTouch:var, showTouchMarkers:input, touchMonthL:var

Pivot Hi Touch

line 602:9

Trigger

(showTouchMarkers && anyTouch) && (touchPivotHi)

Value

lastPivotHi

Deps

anyTouch:var, showTouchMarkers:input, touchPivotHi:var

Pivot Lo Touch

line 605:9

Trigger

(showTouchMarkers && anyTouch) && (touchPivotLo)

Value

lastPivotLo

Deps

anyTouch:var, showTouchMarkers:input, touchPivotLo:var

Unlabeled shape

line 621:9

Trigger

(showStrength && isLastBar) && (strengthLabel != "")

Value

h

Deps

isLastBar:builtin, showStrength:input, strengthLabel:var

077_key_levels_leviathan.flowscript

source path: kscripts/perfected/077_key_levels_leviathan.flowscript · sha256:3b71a3e70058d447b6f39f3946409b13ab40b78c5ef8fd75d81c310f9c397c49

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

// ============================================================================
// Key Levels — Multi-Timeframe Level Detection & Strength Scoring [Leviathan]
// Author: Leviathan (@Leviathan) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #levels, #pivots, #supportresistance, #confluence, #leviathan
//
// Production-grade key level detection across daily, weekly, monthly, quarterly,
// and yearly periods plus swing pivot detection, level strength scoring based on
// touch frequency and recency, color coding by level type, and shape markers for
// level touches. Tracks previous-period OHLC values using static variables for
// proper stateful computation.
//
// Research papers underpinning this design:
//  - Harris (1986), "A Transaction Data Study": intraday return seasonality;
//    weekly patterns; opening/closing effects as key reference levels.
//  - Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete Resource":
//    support/resistance levels rated 4.41/5 by practitioners; pivot points as
//    high-probability reversal zones.
//  - Frykmer & Johnsson (2019), "Pivot Point Trading in the Foreign Exchange
//    Market": exchange rates tend to stop trending at pivot levels; inverse
//    pivot implementation can be profitable.
//  - Brock et al. (1992), "Does Technical Analysis Work?": prices move rapidly
//    once support/resistance levels are breached.
//  - Ito & Hashimoto (2006), "Intraday Seasonality": overlapping session effects
//    create confluence zones at daily opens/highs/lows.
// ============================================================================

define(
    title="Key Levels [Leviathan] Perfected",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------

// --- Period Selection ---
var showDaily     = input(name="showDaily",     type="boolean", defaultValue=true,  label="Show Daily Levels",     group="Period Selection")
var showWeekly    = input(name="showWeekly",    type="boolean", defaultValue=true,  label="Show Weekly Levels",    group="Period Selection")
var showMonthly   = input(name="showMonthly",   type="boolean", defaultValue=true,  label="Show Monthly Levels",   group="Period Selection")
var showQuarterly = input(name="showQuarterly", type="boolean", defaultValue=false, label="Show Quarterly Levels", group="Period Selection")
var showYearly    = input(name="showYearly",    type="boolean", defaultValue=false, label="Show Yearly Levels",    group="Period Selection")
var showPrev      = input(name="showPrev",      type="boolean", defaultValue=true,  label="Show Previous Period Levels", group="Period Selection")

// --- Pivot Detection ---
var showPivots    = input(name="showPivots",    type="boolean", defaultValue=true,  label="Show Swing Pivots",     group="Pivot Detection")
var pivotLen      = input(name="pivotLen",      type="number",  defaultValue=5,     label="Pivot Length (each side)", constraints={min: 2, max: 50, step: 1}, group="Pivot Detection")
var pivotLookback = input(name="pivotLookback", type="number",  defaultValue=50,    label="Pivot Lookback (bars)", constraints={min: 10, max: 500, step: 5}, group="Pivot Detection")

// --- Level Scoring ---
var showStrength    = input(name="showStrength",    type="boolean", defaultValue=true,  label="Show Strength Labels", group="Level Scoring")
var strengthLookback = input(name="strengthLookback", type="number",  defaultValue=50,    label="Strength Lookback (bars)", constraints={min: 10, max: 500, step: 5}, group="Level Scoring")
var touchThreshold  = input(name="touchThreshold",  type="number",  defaultValue=2,     label="Min Touches for Strong", constraints={min: 1, max: 10, step: 1}, group="Level Scoring")

// --- Display ---
var showOpenLevels    = input(name="showOpenLevels",    type="boolean", defaultValue=true,  label="Show Open Levels",    group="Display")
var showHighLevels    = input(name="showHighLevels",    type="boolean", defaultValue=true,  label="Show High Levels",    group="Display")
var showLowLevels     = input(name="showLowLevels",     type="boolean", defaultValue=true,  label="Show Low Levels",     group="Display")
var showCloseLevels   = input(name="showCloseLevels",   type="boolean", defaultValue=false, label="Show Close Levels",   group="Display")
var showEqLevels      = input(name="showEqLevels",      type="boolean", defaultValue=true,  label="Show Equilibrium",    group="Display")
var showTouchMarkers  = input(name="showTouchMarkers",  type="boolean", defaultValue=true,  label="Show Touch Markers",  group="Display")
var lineWidth         = input(name="lineWidth",         type="number",  defaultValue=1,     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 openColor      = input(name="openColor",      type="color", defaultValue="#2962ff", label="Open Level Color",      group="Colors")
var highColor      = input(name="highColor",      type="color", defaultValue="#d50000", label="High Level Color",      group="Colors")
var lowColor       = input(name="lowColor",       type="color", defaultValue="#00c853", label="Low Level Color",       group="Colors")
var closeColor     = input(name="closeColor",     type="color", defaultValue="#ff6d00", label="Close Level Color",     group="Colors")
var eqColor        = input(name="eqColor",        type="color", defaultValue="#9e9e9e", label="Equilibrium Color",     group="Colors")
var pivotHiColor   = input(name="pivotHiColor",   type="color", defaultValue="#ef5350", label="Pivot High Color",      group="Colors")
var pivotLoColor   = input(name="pivotLoColor",   type="color", defaultValue="#26a69a", label="Pivot Low Color",       group="Colors")
var strongColor    = input(name="strongColor",    type="color", defaultValue="#ffd700", label="Strong Level Color",    group="Colors")
var touchColor     = input(name="touchColor",     type="color", defaultValue="#ffffff", label="Touch Marker Color",    group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = ohlcvData.time
timeseries o = ohlcvData.open
timeseries h = ohlcvData.high
timeseries l = ohlcvData.low
timeseries c = ohlcvData.close

// isnan guard: prevent NaN propagation on startup
if (isnan(t[0]) || isnan(o[0]) || isnan(h[0]) || isnan(l[0]) || isnan(c[0])) {
    return
}

// ---------------------------------------------------------------------------
// Calendar Math (Period Buckets)
// ---------------------------------------------------------------------------
// Daily bucket: 86400000 ms per day
var dayId = math.floor(t / 86400000)
// Weekly bucket: 1970-01-01 is Thursday -> shift 3 days to make Monday start
var weekId = math.floor((dayId + 3) / 7)
// Monthly bucket: precise calendar math
var z = dayId + 719468
var era = math.floor(z / 146097)
var doe = z - era * 146097
var yoe = math.floor((doe - math.floor(doe / 1460) + math.floor(doe / 36524) - math.floor(doe / 146096)) / 365)
var yCalc = yoe + era * 400
var doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100))
var mp = math.floor((5 * doy + 2) / 153)
var m = mp + (mp < 10 ? 3 : -9)
var yearCalc = yCalc + (m <= 2 ? 1 : 0)
var monthId = yearCalc * 12 + m
// Quarterly bucket: 3-month groups
var quarterId = math.floor((monthId - 1) / 3)
// Yearly bucket
var yearId = yearCalc

// ---------------------------------------------------------------------------
// Static State: Current & Previous Period OHLC
// ---------------------------------------------------------------------------
static lastDay = -1
static lastWeek = -1
static lastMonth = -1
static lastQuarter = -1
static lastYear = -1

// Current period values (updated as period progresses)
static valDayO = 0.0
static valDayH = 0.0
static valDayL = 0.0
static valDayC = 0.0
static valWeekO = 0.0
static valWeekH = 0.0
static valWeekL = 0.0
static valWeekC = 0.0
static valMonthO = 0.0
static valMonthH = 0.0
static valMonthL = 0.0
static valMonthC = 0.0
static valQuarterO = 0.0
static valQuarterH = 0.0
static valQuarterL = 0.0
static valQuarterC = 0.0
static valYearO = 0.0
static valYearH = 0.0
static valYearL = 0.0
static valYearC = 0.0

// Previous period values (stored on transition)
static prevDayH = 0.0
static prevDayL = 0.0
static prevDayC = 0.0
static prevWeekH = 0.0
static prevWeekL = 0.0
static prevWeekC = 0.0
static prevMonthH = 0.0
static prevMonthL = 0.0
static prevMonthC = 0.0
static prevQuarterH = 0.0
static prevQuarterL = 0.0
static prevQuarterC = 0.0
static prevYearH = 0.0
static prevYearL = 0.0
static prevYearC = 0.0

static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// ---------------------------------------------------------------------------
// Period State Update (on bar close for consistency)
// ---------------------------------------------------------------------------
if (!isLiveUpdate) {
    // --- Daily ---
    if (lastDay == -1) {
        lastDay = dayId
        valDayO = o
        valDayH = h
        valDayL = l
        valDayC = c
    } else if (dayId > lastDay) {
        prevDayH = valDayH
        prevDayL = valDayL
        prevDayC = valDayC
        lastDay = dayId
        valDayO = o
        valDayH = h
        valDayL = l
        valDayC = c
    } else {
        valDayH = math.max(valDayH, h)
        valDayL = math.min(valDayL, l)
        valDayC = c
    }

    // --- Weekly ---
    if (lastWeek == -1) {
        lastWeek = weekId
        valWeekO = o
        valWeekH = h
        valWeekL = l
        valWeekC = c
    } else if (weekId > lastWeek) {
        prevWeekH = valWeekH
        prevWeekL = valWeekL
        prevWeekC = valWeekC
        lastWeek = weekId
        valWeekO = o
        valWeekH = h
        valWeekL = l
        valWeekC = c
    } else {
        valWeekH = math.max(valWeekH, h)
        valWeekL = math.min(valWeekL, l)
        valWeekC = c
    }

    // --- Monthly ---
    if (lastMonth == -1) {
        lastMonth = monthId
        valMonthO = o
        valMonthH = h
        valMonthL = l
        valMonthC = c
    } else if (monthId > lastMonth) {
        prevMonthH = valMonthH
        prevMonthL = valMonthL
        prevMonthC = valMonthC
        lastMonth = monthId
        valMonthO = o
        valMonthH = h
        valMonthL = l
        valMonthC = c
    } else {
        valMonthH = math.max(valMonthH, h)
        valMonthL = math.min(valMonthL, l)
        valMonthC = c
    }

    // --- Quarterly ---
    if (lastQuarter == -1) {
        lastQuarter = quarterId
        valQuarterO = o
        valQuarterH = h
        valQuarterL = l
        valQuarterC = c
    } else if (quarterId > lastQuarter) {
        prevQuarterH = valQuarterH
        prevQuarterL = valQuarterL
        prevQuarterC = valQuarterC
        lastQuarter = quarterId
        valQuarterO = o
        valQuarterH = h
        valQuarterL = l
        valQuarterC = c
    } else {
        valQuarterH = math.max(valQuarterH, h)
        valQuarterL = math.min(valQuarterL, l)
        valQuarterC = c
    }

    // --- Yearly ---
    if (lastYear == -1) {
        lastYear = yearId
        valYearO = o
        valYearH = h
        valYearL = l
        valYearC = c
    } else if (yearId > lastYear) {
        prevYearH = valYearH
        prevYearL = valYearL
        prevYearC = valYearC
        lastYear = yearId
        valYearO = o
        valYearH = h
        valYearL = l
        valYearC = c
    } else {
        valYearH = math.max(valYearH, h)
        valYearL = math.min(valYearL, l)
        valYearC = c
    }
}

// ---------------------------------------------------------------------------
// Equilibrium = Midpoint of Period H/L
// ---------------------------------------------------------------------------
var eqDay     = (valDayH + valDayL) / 2
var eqWeek    = (valWeekH + valWeekL) / 2
var eqMonth   = (valMonthH + valMonthL) / 2
var eqQuarter = (valQuarterH + valQuarterL) / 2
var eqYear    = (valYearH + valYearL) / 2

// ---------------------------------------------------------------------------
// Swing Pivot Detection (confirmed after right-side lookback)
// Formula: P_high = H_{t-p} == max(H_{t-p:t+p}) && H_{t-p} > highest(H_{t-p:t})
// P_low = L_{t-p} == min(L_{t-p:t+p}) && L_{t-p} < lowest(L_{t-p:t})
// ---------------------------------------------------------------------------
var isSwingHigh = h[pivotLen] == highest(h, pivotLen * 2 + 1) && h[pivotLen] > highest(h, pivotLen)
var isSwingLow  = l[pivotLen] == lowest(l, pivotLen * 2 + 1) && l[pivotLen] < lowest(l, pivotLen)

// Static pivot tracking: store last N pivot levels
static lastPivotHi = 0.0
static lastPivotLo = 0.0
static prevPivotHi = 0.0
static prevPivotLo = 0.0
static pivotHiBar = 0
static pivotLoBar = 0

if (!isLiveUpdate) {
    if (isSwingHigh) {
        if (lastPivotHi > 0) {
            prevPivotHi = lastPivotHi
        }
        lastPivotHi = h[pivotLen]
        pivotHiBar = barCount
    }
    if (isSwingLow) {
        if (lastPivotLo > 0) {
            prevPivotLo = lastPivotLo
        }
        lastPivotLo = l[pivotLen]
        pivotLoBar = barCount
    }
}

// ---------------------------------------------------------------------------
// Level Strength Scoring (touch-based)
// A level is "strong" if price has touched or crossed it multiple times
// within the lookback period without a decisive break.
// ---------------------------------------------------------------------------
static dayHTouches = 0
static dayLTouches = 0
static weekHTouches = 0
static weekLTouches = 0
static monthHTouches = 0
static monthLTouches = 0

if (!isLiveUpdate) {
    // Touch counting with decay: increment on touch, reset on decisive break
    if (h >= valDayH && l <= valDayH) {
        dayHTouches = dayHTouches + 1
    }
    if (l <= valDayL && h >= valDayL) {
        dayLTouches = dayLTouches + 1
    }
    if (h >= valWeekH && l <= valWeekH) {
        weekHTouches = weekHTouches + 1
    }
    if (l <= valWeekL && h >= valWeekL) {
        weekLTouches = weekLTouches + 1
    }
    if (h >= valMonthH && l <= valMonthH) {
        monthHTouches = monthHTouches + 1
    }
    if (l <= valMonthL && h >= valMonthL) {
        monthLTouches = monthLTouches + 1
    }

    // Reset touch counts on new period (levels change, so touch history resets)
    if (dayId > lastDay) {
        dayHTouches = 0
        dayLTouches = 0
    }
    if (weekId > lastWeek) {
        weekHTouches = 0
        weekLTouches = 0
    }
    if (monthId > lastMonth) {
        monthHTouches = 0
        monthLTouches = 0
    }
}

// Strength classification
var dayHStrong = dayHTouches >= touchThreshold
var dayLStrong = dayLTouches >= touchThreshold
var weekHStrong = weekHTouches >= touchThreshold
var weekLStrong = weekLTouches >= touchThreshold
var monthHStrong = monthHTouches >= touchThreshold
var monthLStrong = monthLTouches >= touchThreshold

// ---------------------------------------------------------------------------
// Touch Detection (current bar touching any level)
// ---------------------------------------------------------------------------
var touchDayH     = showDaily     && h >= valDayH     && l <= valDayH
var touchDayL     = showDaily     && h >= valDayL     && l <= valDayL
var touchDayEq    = showDaily     && h >= eqDay       && l <= eqDay
var touchWeekH    = showWeekly    && h >= valWeekH    && l <= valWeekH
var touchWeekL    = showWeekly    && h >= valWeekL    && l <= valWeekL
var touchWeekEq   = showWeekly    && h >= eqWeek      && l <= eqWeek
var touchMonthH   = showMonthly   && h >= valMonthH   && l <= valMonthH
var touchMonthL   = showMonthly   && h >= valMonthL   && l <= valMonthL
var touchMonthEq  = showMonthly   && h >= eqMonth     && l <= eqMonth
var touchQuarterH = showQuarterly && h >= valQuarterH && l <= valQuarterH
var touchQuarterL = showQuarterly && h >= valQuarterL && l <= valQuarterL
var touchYearH    = showYearly    && h >= valYearH    && l <= valYearH
var touchYearL    = showYearly    && h >= valYearL    && l <= valYearL
var touchPivotHi  = showPivots    && lastPivotHi > 0  && h >= lastPivotHi && l <= lastPivotHi
var touchPivotLo  = showPivots    && lastPivotLo > 0  && h >= lastPivotLo && l <= lastPivotLo

var anyTouch = touchDayH || touchDayL || touchDayEq || touchWeekH || touchWeekL || touchWeekEq ||
               touchMonthH || touchMonthL || touchMonthEq || touchQuarterH || touchQuarterL ||
               touchYearH || touchYearL || touchPivotHi || touchPivotLo

// ---------------------------------------------------------------------------
// Plotting: Daily Levels
// ---------------------------------------------------------------------------
if (showDaily) {
    var dayHColor = dayHStrong ? strongColor : highColor
    var dayLColor = dayLStrong ? strongColor : lowColor
    if (showOpenLevels) {
        plotLine(value=valDayO, width=lineWidth, colors=[openColor], label=["Daily Open"], desc=["Daily period open"])
    }
    if (showHighLevels) {
        plotLine(value=valDayH, width=lineWidth, colors=[dayHColor], label=["Daily High"], desc=["Daily period high (touches: " + dayHTouches + ")"])
    }
    if (showLowLevels) {
        plotLine(value=valDayL, width=lineWidth, colors=[dayLColor], label=["Daily Low"], desc=["Daily period low (touches: " + dayLTouches + ")"])
    }
    if (showCloseLevels) {
        plotLine(value=valDayC, width=lineWidth, colors=[closeColor], label=["Daily Close"], desc=["Daily period close"])
    }
    if (showEqLevels) {
        plotLine(value=eqDay, width=lineWidth, colors=[eqColor], label=["Daily EQ"], desc=["Daily equilibrium: midpoint of H/L"])
    }
    if (showPrev && prevDayH > 0) {
        plotLine(value=prevDayH, width=1, colors=[opacity(highColor, 50)], label=["Prev Day H"], desc=["Previous day high"])
        plotLine(value=prevDayL, width=1, colors=[opacity(lowColor, 50)], label=["Prev Day L"], desc=["Previous day low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Weekly Levels
// ---------------------------------------------------------------------------
if (showWeekly) {
    var weekHColor = weekHStrong ? strongColor : highColor
    var weekLColor = weekLStrong ? strongColor : lowColor
    if (showOpenLevels) {
        plotLine(value=valWeekO, width=lineWidth, colors=[openColor], label=["Weekly Open"], desc=["Weekly period open"])
    }
    if (showHighLevels) {
        plotLine(value=valWeekH, width=lineWidth, colors=[weekHColor], label=["Weekly High"], desc=["Weekly period high (touches: " + weekHTouches + ")"])
    }
    if (showLowLevels) {
        plotLine(value=valWeekL, width=lineWidth, colors=[weekLColor], label=["Weekly Low"], desc=["Weekly period low (touches: " + weekLTouches + ")"])
    }
    if (showCloseLevels) {
        plotLine(value=valWeekC, width=lineWidth, colors=[closeColor], label=["Weekly Close"], desc=["Weekly period close"])
    }
    if (showEqLevels) {
        plotLine(value=eqWeek, width=lineWidth, colors=[eqColor], label=["Weekly EQ"], desc=["Weekly equilibrium: midpoint of H/L"])
    }
    if (showPrev && prevWeekH > 0) {
        plotLine(value=prevWeekH, width=1, colors=[opacity(highColor, 50)], label=["Prev Week H"], desc=["Previous week high"])
        plotLine(value=prevWeekL, width=1, colors=[opacity(lowColor, 50)], label=["Prev Week L"], desc=["Previous week low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Monthly Levels
// ---------------------------------------------------------------------------
if (showMonthly) {
    var monthHColor = monthHStrong ? strongColor : highColor
    var monthLColor = monthLStrong ? strongColor : lowColor
    if (showOpenLevels) {
        plotLine(value=valMonthO, width=lineWidth, colors=[openColor], label=["Monthly Open"], desc=["Monthly period open"])
    }
    if (showHighLevels) {
        plotLine(value=valMonthH, width=lineWidth, colors=[monthHColor], label=["Monthly High"], desc=["Monthly period high (touches: " + monthHTouches + ")"])
    }
    if (showLowLevels) {
        plotLine(value=valMonthL, width=lineWidth, colors=[monthLColor], label=["Monthly Low"], desc=["Monthly period low (touches: " + monthLTouches + ")"])
    }
    if (showCloseLevels) {
        plotLine(value=valMonthC, width=lineWidth, colors=[closeColor], label=["Monthly Close"], desc=["Monthly period close"])
    }
    if (showEqLevels) {
        plotLine(value=eqMonth, width=lineWidth, colors=[eqColor], label=["Monthly EQ"], desc=["Monthly equilibrium: midpoint of H/L"])
    }
    if (showPrev && prevMonthH > 0) {
        plotLine(value=prevMonthH, width=1, colors=[opacity(highColor, 50)], label=["Prev Month H"], desc=["Previous month high"])
        plotLine(value=prevMonthL, width=1, colors=[opacity(lowColor, 50)], label=["Prev Month L"], desc=["Previous month low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Quarterly Levels
// ---------------------------------------------------------------------------
if (showQuarterly) {
    if (showOpenLevels) {
        plotLine(value=valQuarterO, width=lineWidth, colors=[openColor], label=["Quarterly Open"], desc=["Quarterly period open"])
    }
    if (showHighLevels) {
        plotLine(value=valQuarterH, width=lineWidth, colors=[highColor], label=["Quarterly High"], desc=["Quarterly period high"])
    }
    if (showLowLevels) {
        plotLine(value=valQuarterL, width=lineWidth, colors=[lowColor], label=["Quarterly Low"], desc=["Quarterly period low"])
    }
    if (showCloseLevels) {
        plotLine(value=valQuarterC, width=lineWidth, colors=[closeColor], label=["Quarterly Close"], desc=["Quarterly period close"])
    }
    if (showEqLevels) {
        plotLine(value=eqQuarter, width=lineWidth, colors=[eqColor], label=["Quarterly EQ"], desc=["Quarterly equilibrium: midpoint of H/L"])
    }
    if (showPrev && prevQuarterH > 0) {
        plotLine(value=prevQuarterH, width=1, colors=[opacity(highColor, 50)], label=["Prev Q H"], desc=["Previous quarter high"])
        plotLine(value=prevQuarterL, width=1, colors=[opacity(lowColor, 50)], label=["Prev Q L"], desc=["Previous quarter low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Yearly Levels
// ---------------------------------------------------------------------------
if (showYearly) {
    if (showOpenLevels) {
        plotLine(value=valYearO, width=lineWidth, colors=[openColor], label=["Yearly Open"], desc=["Yearly period open"])
    }
    if (showHighLevels) {
        plotLine(value=valYearH, width=lineWidth, colors=[highColor], label=["Yearly High"], desc=["Yearly period high"])
    }
    if (showLowLevels) {
        plotLine(value=valYearL, width=lineWidth, colors=[lowColor], label=["Yearly Low"], desc=["Yearly period low"])
    }
    if (showCloseLevels) {
        plotLine(value=valYearC, width=lineWidth, colors=[closeColor], label=["Yearly Close"], desc=["Yearly period close"])
    }
    if (showEqLevels) {
        plotLine(value=eqYear, width=lineWidth, colors=[eqColor], label=["Yearly EQ"], desc=["Yearly equilibrium: midpoint of H/L"])
    }
    if (showPrev && prevYearH > 0) {
        plotLine(value=prevYearH, width=1, colors=[opacity(highColor, 50)], label=["Prev Year H"], desc=["Previous year high"])
        plotLine(value=prevYearL, width=1, colors=[opacity(lowColor, 50)], label=["Prev Year L"], desc=["Previous year low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Swing Pivots
// ---------------------------------------------------------------------------
if (showPivots) {
    if (lastPivotHi > 0) {
        plotLine(
            value=lastPivotHi,
            width=lineWidth,
            colors=[pivotHiColor],
            label=["Pivot High"],
            desc=["Last confirmed swing pivot high (length " + pivotLen + ")"]
        )
    }
    if (prevPivotHi > 0) {
        plotLine(
            value=prevPivotHi,
            width=1,
            colors=[opacity(pivotHiColor, 50)],
            label=["Prev Pivot Hi"],
            desc=["Previous swing pivot high"]
        )
    }
    if (lastPivotLo > 0) {
        plotLine(
            value=lastPivotLo,
            width=lineWidth,
            colors=[pivotLoColor],
            label=["Pivot Low"],
            desc=["Last confirmed swing pivot low (length " + pivotLen + ")"]
        )
    }
    if (prevPivotLo > 0) {
        plotLine(
            value=prevPivotLo,
            width=1,
            colors=[opacity(pivotLoColor, 50)],
            label=["Prev Pivot Lo"],
            desc=["Previous swing pivot low"]
        )
    }
}

// ---------------------------------------------------------------------------
// Plotting: Touch Markers
// ---------------------------------------------------------------------------
if (showTouchMarkers && anyTouch) {
    if (touchDayH) {
        plotShape(value=valDayH, shape="triangledown", colorIndex=touchColor, width=shapeSize, label=["Day H Touch"], desc=["Price touched daily high"])
    }
    if (touchDayL) {
        plotShape(value=valDayL, shape="triangleup", colorIndex=touchColor, width=shapeSize, label=["Day L Touch"], desc=["Price touched daily low"])
    }
    if (touchWeekH) {
        plotShape(value=valWeekH, shape="triangledown", colorIndex=touchColor, width=shapeSize, label=["Week H Touch"], desc=["Price touched weekly high"])
    }
    if (touchWeekL) {
        plotShape(value=valWeekL, shape="triangleup", colorIndex=touchColor, width=shapeSize, label=["Week L Touch"], desc=["Price touched weekly low"])
    }
    if (touchMonthH) {
        plotShape(value=valMonthH, shape="triangledown", colorIndex=touchColor, width=shapeSize, label=["Month H Touch"], desc=["Price touched monthly high"])
    }
    if (touchMonthL) {
        plotShape(value=valMonthL, shape="triangleup", colorIndex=touchColor, width=shapeSize, label=["Month L Touch"], desc=["Price touched monthly low"])
    }
    if (touchPivotHi) {
        plotShape(value=lastPivotHi, shape="triangledown", colorIndex=touchColor, width=shapeSize, label=["Pivot Hi Touch"], desc=["Price touched swing pivot high"])
    }
    if (touchPivotLo) {
        plotShape(value=lastPivotLo, shape="triangleup", colorIndex=touchColor, width=shapeSize, label=["Pivot Lo Touch"], desc=["Price touched swing pivot low"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Strength Labels (on last bar)
// ---------------------------------------------------------------------------
if (showStrength && isLastBar) {
    var strengthLabel = ""
    if (dayHStrong)     { strengthLabel = strengthLabel + "D-H " }
    if (dayLStrong)     { strengthLabel = strengthLabel + "D-L " }
    if (weekHStrong)    { strengthLabel = strengthLabel + "W-H " }
    if (weekLStrong)    { strengthLabel = strengthLabel + "W-L " }
    if (monthHStrong)   { strengthLabel = strengthLabel + "M-H " }
    if (monthLStrong)   { strengthLabel = strengthLabel + "M-L " }
    if (strengthLabel != "") {
        plotPriceLabel(
            price=h,
            text="Strong: " + strengthLabel,
            type="callout",
            color="#ffffff",
            backgroundColor="#424242",
            size=8,
            fontWeight=700
        )
    }
}