MM Flow
FlowScripts

Perfected FlowScript

Open Levels

Open Levels — Session Key Prices is indexed as 049_open_levels.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

13.1 KB

Lines

336

Native Signal Candidates

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

5/5 guarded

New Day Open

line 267:9

Trigger

(showOpenShapes) && (newDay && showDaily)

Value

valD

Deps

newDay:var, showDaily:input, showOpenShapes:input

New Week Open

line 277:9

Trigger

(showOpenShapes) && (newWeek && showWeekly)

Value

valW

Deps

newWeek:var, showOpenShapes:input, showWeekly:input

New Month Open

line 287:9

Trigger

(showOpenShapes) && (newMonth && showMonthly)

Value

valM

Deps

newMonth:var, showMonthly:input, showOpenShapes:input

New Year Open

line 297:9

Trigger

(showOpenShapes) && (newYear && showYearly)

Value

valY

Deps

newYear:var, showOpenShapes:input, showYearly:input

Unlabeled shape

line 326:5

Trigger

(showSessionLabel && isLastBar)

Value

h

Deps

isLastBar:builtin, showSessionLabel:input

049_open_levels.flowscript

source path: kscripts/perfected/049_open_levels.flowscript · sha256:94e359dfa31909944576e37be056122e4f4dd584b83ea4b42b505d2ec21e0146

hash verified
//@version=2
// ============================================================================
// Open Levels — Session-Based Key Opens with Calendar Math & Regime Detection
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #openlevels, #session, #calendar, #dailyopen, #weeklyopen, #monthlyopen
//
// Production-grade open levels indicator plotting daily, weekly, monthly, and
// yearly session opens with proper calendar mathematics using static variables,
// color coding by level type, fill between open and current price, shape markers
// for new period opens, and session tracking. Calendar math derived from
// 203_key_level implementation with robust anchor detection.
//
// Academic foundations:
//  - Harris (1986), "A Transaction Data Study of Weekly and Intradaily Patterns
//    in Stock Returns" (J. Financial Economics, 16(1), 99–117). The seminal
//    paper on intraday seasonality. Found significant weekday differences in
//    intraday returns during the first 45 minutes after market open. Opening
//    period carries distinct price discovery dynamics with higher volatility.
//  - Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section
//    of Stock Returns" (J. Finance, 65(4), 1369–1407). Opening half-hour earns
//    over 11 basis points in daily decile spread; close earns 8 bps. Return
//    effects are pronounced at session boundaries, validating open levels as
//    significant reference points.
//  - Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with Market
//    Profile" (Wiley Trading). The Initial Balance (price range in first hour)
//    is used as a reference point for the rest of the session. Opening prices
//    carry structural information about institutional intent for the session.
//  - Ito & Hashimoto (2006), "Intraday Seasonality in Activities of the Foreign
//    Exchange Markets" (NBER 12413). U-shaped pattern of quote revision and
//    trading volume for Tokyo and London participants. Opening hours are the
//    most informationally active periods of the trading day.
//  - Crabel (1990), "Playing the Opening Range Breakout" (Stocks & Commodities).
//    Foundational ORB work: if price moves a certain percentage from the
//    opening price, odds favor continuation. The opening range is a critical
//    structural level for intraday trading.
//  - SFI / Concretum Group (2024), "A Profitable Day Trading Strategy." ORB on
//    Stocks in Play achieved >1,600% total net return, Sharpe 2.81. Validates
//    opening levels as high-probability trading references.
// ============================================================================

define(title="Open Levels — Session Key Prices", position="onchart", axis=false)

// === USER INPUTS ===
// --- Level Selection ---
var showDaily = input(name="showDaily", type="boolean", defaultValue=true, label="Show Daily Open", group="Level Selection")
var showWeekly = input(name="showWeekly", type="boolean", defaultValue=true, label="Show Weekly Open", group="Level Selection")
var showMonthly = input(name="showMonthly", type="boolean", defaultValue=true, label="Show Monthly Open", group="Level Selection")
var showYearly = input(name="showYearly", type="boolean", defaultValue=true, label="Show Yearly Open", group="Level Selection")

// --- Display ---
var showOpenShapes = input(name="showOpenShapes", type="boolean", defaultValue=true, label="Show New Period Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Between Open and Price", group="Display")
var showSessionLabel = input(name="showSessionLabel", type="boolean", defaultValue=true, label="Show Session Regime Label", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, 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 dailyColor = input(name="dailyColor", type="color", defaultValue="#2962ff", label="Daily Open Color", group="Colors")
var weeklyColor = input(name="weeklyColor", type="color", defaultValue="#ff6d00", label="Weekly Open Color", group="Colors")
var monthlyColor = input(name="monthlyColor", type="color", defaultValue="#d50000", label="Monthly Open Color", group="Colors")
var yearlyColor = input(name="yearlyColor", type="color", defaultValue="#6a1b9a", label="Yearly Open Color", group="Colors")
var fillBullColor = input(name="fillBullColor", type="color", defaultValue="#26a69a20", label="Bullish Fill Color", group="Colors")
var fillBearColor = input(name="fillBearColor", type="color", defaultValue="#ef535020", label="Bearish Fill Color", group="Colors")

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries o = bars.open
timeseries c = bars.close
timeseries h = bars.high

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(t[0]) || isnan(o[0]) || isnan(c[0])) {
    return
}

// === CALENDAR MATH (from 203_key_level) ===
var day_id = math.floor(t / 86400000)
var week_id = math.floor((day_id + 3) / 7)

// Monthly calendar math using proleptic Gregorian calendar (from 203_key_level)
var z = day_id + 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 y = 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 year_final = y + (m <= 2 ? 1 : 0)
var month_id = year_final * 12 + m
var year_id = year_final

// === STATIC STATE: Session Tracking ===
// Each level uses static variables to detect new periods and store open prices.
// This pattern mirrors the 203_key_level implementation and the VWAP Leviathan
// anchor detection logic.
static last_day_id = -1
static last_week_id = -1
static last_month_id = -1
static last_year_id = -1
static barCount = 0

// Current open values (updated when new period detected)
static valD = 0.0
static valW = 0.0
static valM = 0.0
static valY = 0.0

// New period flags for shape markers
var newDay = false
var newWeek = false
var newMonth = false
var newYear = false

if (!isLiveUpdate) {
    barCount = barCount + 1

    // Daily open detection
    if (last_day_id == -1) {
        last_day_id = day_id
        valD = o
        newDay = true
    } else if (day_id > last_day_id) {
        last_day_id = day_id
        valD = o
        newDay = true
    }

    // Weekly open detection (Monday anchor)
    if (last_week_id == -1) {
        last_week_id = week_id
        valW = o
        newWeek = true
    } else if (week_id > last_week_id) {
        last_week_id = week_id
        valW = o
        newWeek = true
    }

    // Monthly open detection
    if (last_month_id == -1) {
        last_month_id = month_id
        valM = o
        newMonth = true
    } else if (month_id > last_month_id) {
        last_month_id = month_id
        valM = o
        newMonth = true
    }

    // Yearly open detection
    if (last_year_id == -1) {
        last_year_id = year_id
        valY = o
        newYear = true
    } else if (year_id > last_year_id) {
        last_year_id = year_id
        valY = o
        newYear = true
    }
}

// === REGIME DETECTION ===
// Price relative to daily open determines short-term bias
var aboveDailyOpen = c > valD
var aboveWeeklyOpen = c > valW
var aboveMonthlyOpen = c > valM
var aboveYearlyOpen = c > valY

// Overall regime: bullish if price above all active opens, bearish if below all
var bullishCount = (aboveDailyOpen ? 1 : 0) + (showWeekly && aboveWeeklyOpen ? 1 : 0) + (showMonthly && aboveMonthlyOpen ? 1 : 0) + (showYearly && aboveYearlyOpen ? 1 : 0)
var bearishCount = (!aboveDailyOpen ? 1 : 0) + (showWeekly && !aboveWeeklyOpen ? 1 : 0) + (showMonthly && !aboveMonthlyOpen ? 1 : 0) + (showYearly && !aboveYearlyOpen ? 1 : 0)
var totalActive = (showDaily ? 1 : 0) + (showWeekly ? 1 : 0) + (showMonthly ? 1 : 0) + (showYearly ? 1 : 0)
var regimeScore = totalActive > 0 ? bullishCount / totalActive : 0.5

// === PLOTS: OPEN LEVELS (plotLine) ===
if (showDaily && valD > 0) {
    plotLine(
        value=valD,
        colors=[dailyColor],
        width=lineWidth,
        label=["Daily Open"],
        desc=["Start of the current UTC trading day. Harris (1986) found first 45 minutes carry distinct seasonality."]
    )
}
if (showWeekly && valW > 0) {
    plotLine(
        value=valW,
        colors=[weeklyColor],
        width=lineWidth,
        label=["Weekly Open"],
        desc=["Start of the current calendar week (Monday). Weekly opens carry medium-term structural weight."]
    )
}
if (showMonthly && valM > 0) {
    plotLine(
        value=valM,
        colors=[monthlyColor],
        width=lineWidth,
        label=["Monthly Open"],
        desc=["Start of the current calendar month. Monthly opens are key institutional rebalancing references."]
    )
}
if (showYearly && valY > 0) {
    plotLine(
        value=valY,
        colors=[yearlyColor],
        width=lineWidth,
        label=["Yearly Open"],
        desc=["Start of the current calendar year. Yearly opens define long-term market structure."]
    )
}

// === PLOTS: FILL BETWEEN OPEN AND CURRENT PRICE ===
// Fill between each open level and current price, color-coded by regime
if (showFill) {
    if (showDaily && valD > 0) {
        var dailyFillColor = aboveDailyOpen ? fillBullColor : fillBearColor
        plotLine(
            value=[valD, c],
            width=1,
            colors=[dailyFillColor, dailyFillColor],
            fill=true,
            label=["Daily Open Fill"],
            desc=["Fill between daily open and current close. Bullish = above open, Bearish = below open."]
        )
    }
    if (showWeekly && valW > 0) {
        var weeklyFillColor = aboveWeeklyOpen ? fillBullColor : fillBearColor
        plotLine(
            value=[valW, c],
            width=1,
            colors=[weeklyFillColor, weeklyFillColor],
            fill=true,
            label=["Weekly Open Fill"],
            desc=["Fill between weekly open and current close."]
        )
    }
    if (showMonthly && valM > 0) {
        var monthlyFillColor = aboveMonthlyOpen ? fillBullColor : fillBearColor
        plotLine(
            value=[valM, c],
            width=1,
            colors=[monthlyFillColor, monthlyFillColor],
            fill=true,
            label=["Monthly Open Fill"],
            desc=["Fill between monthly open and current close."]
        )
    }
    if (showYearly && valY > 0) {
        var yearlyFillColor = aboveYearlyOpen ? fillBullColor : fillBearColor
        plotLine(
            value=[valY, c],
            width=1,
            colors=[yearlyFillColor, yearlyFillColor],
            fill=true,
            label=["Yearly Open Fill"],
            desc=["Fill between yearly open and current close."]
        )
    }
}

// === PLOTS: NEW PERIOD SHAPE MARKERS ===
if (showOpenShapes) {
    if (newDay && showDaily) {
        plotShape(
            value=valD,
            shape="rectangle",
            colorIndex=dailyColor,
            width=shapeSize,
            label=["New Day Open"],
            desc=["New daily session open detected. First 45 minutes carry highest intraday volatility (Harris 1986)."]
        )
    }
    if (newWeek && showWeekly) {
        plotShape(
            value=valW,
            shape="triangleup",
            colorIndex=weeklyColor,
            width=shapeSize,
            label=["New Week Open"],
            desc=["New weekly session open (Monday). Monday openings show distinct return patterns."]
        )
    }
    if (newMonth && showMonthly) {
        plotShape(
            value=valM,
            shape="triangleup",
            colorIndex=monthlyColor,
            width=shapeSize,
            label=["New Month Open"],
            desc=["New monthly session open. Institutional rebalancing often occurs at month boundaries."]
        )
    }
    if (newYear && showYearly) {
        plotShape(
            value=valY,
            shape="triangleup",
            colorIndex=yearlyColor,
            width=shapeSize,
            label=["New Year Open"],
            desc=["New yearly session open. Defines long-term market structure and annual VWAP benchmarks."]
        )
    }
}

// === SESSION REGIME LABEL (plotPriceLabel) ===
if (showSessionLabel && isLastBar) {
    var regimeLabel = ""
    var regimeColor = "#ffffff"
    if (regimeScore >= 0.75) {
        regimeLabel = "STRONG BULL — Above All Opens"
        regimeColor = "#26a69a"
    } else if (regimeScore >= 0.5) {
        regimeLabel = "BULLISH — Above Most Opens"
        regimeColor = "#4db6ac"
    } else if (regimeScore >= 0.25) {
        regimeLabel = "BEARISH — Below Most Opens"
        regimeColor = "#ef9a9a"
    } else {
        regimeLabel = "STRONG BEAR — Below All Opens"
        regimeColor = "#ef5350"
    }

    plotPriceLabel(
        price=h,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}