Perfected FlowScript
5_open_prices
5 Open Prices (Y/M/W/D/PrevD) Perfected is indexed as 340_5_open_prices.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
19.1 KB
Lines
470
Native Signal Candidates
10 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Year Open Cross Up
line 370:9
Trigger
(showCrossShapes) && (crossYearUp)
Value
val_y
Deps
crossYearUp:var, showCrossShapes:input
Year Open Cross Down
line 380:9
Trigger
(showCrossShapes) && (crossYearDn)
Value
val_y
Deps
crossYearDn:var, showCrossShapes:input
Month Open Cross Up
line 390:9
Trigger
(showCrossShapes) && (crossMonthUp)
Value
val_m
Deps
crossMonthUp:var, showCrossShapes:input
Month Open Cross Down
line 400:9
Trigger
(showCrossShapes) && (crossMonthDn)
Value
val_m
Deps
crossMonthDn:var, showCrossShapes:input
Week Open Cross Up
line 410:9
Trigger
(showCrossShapes) && (crossWeekUp)
Value
val_w
Deps
crossWeekUp:var, showCrossShapes:input
Week Open Cross Down
line 420:9
Trigger
(showCrossShapes) && (crossWeekDn)
Value
val_w
Deps
crossWeekDn:var, showCrossShapes:input
Day Open Cross Up
line 430:9
Trigger
(showCrossShapes) && (crossDayUp)
Value
val_d
Deps
crossDayUp:var, showCrossShapes:input
Day Open Cross Down
line 440:9
Trigger
(showCrossShapes) && (crossDayDn)
Value
val_d
Deps
crossDayDn:var, showCrossShapes:input
Prev Day Cross Up
line 450:9
Trigger
(showCrossShapes) && (crossPrevDayUp)
Value
val_pd
Deps
crossPrevDayUp:var, showCrossShapes:input
Prev Day Cross Down
line 460:9
Trigger
(showCrossShapes) && (crossPrevDayDn)
Value
val_pd
Deps
crossPrevDayDn:var, showCrossShapes:input
340_5_open_prices.flowscript
source path: kscripts/perfected/340_5_open_prices.flowscript · sha256:71c8accf0c74237f6016b8b4bb5424d13ba3cc8c34e02e9da93be55c5c2c1b58
//@version=2
// ============================================================================
// 5 Open Prices (Y/M/W/D/PrevD) — Production-Quality Multi-Session Open Tracker
// Author: A (@Alexsandr Lavrov) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #opens, #session, #pivot, #institutional, #initialbalance
//
// Comprehensive multi-session opening price tracker with proximity analysis,
// deviation scoring, cross detection, and institutional benchmark visualization.
// Opening prices serve as session anchors, institutional cost basis references,
// and dynamic support/resistance levels.
//
// FORMULA FOUNDATION:
// 1. Opening Price as Session Anchor: O = first traded price of the session.
// Harris (1986) found intraday return patterns cluster in the first 45 minutes;
// opening prices serve as session anchors for subsequent price action.
// 2. Initial Balance (IB): Steidlmayer & Hawkins (2002) define the first-hour range
// as the Initial Balance; the opening is the reference for the entire session's
// auction. IB extension signals directional commitment.
// 3. Opening Returns Predict Same-Window Returns: Heston, Korajczyk & Sadka (2010)
// found Day 1 decile spread > 11 bps in the opening half-hour; opening returns
// predict subsequent same-window returns with statistical significance.
// 4. Proximity Score: z_open = (P − O) / σ_ATR measures price deviation from
// each open level in volatility units, enabling cross-instrument comparison.
// 5. Open Price as S/R: Kirkpatrick & Dahlquist (2010) rate S/R levels 4.41/5 among
// practitioners; opening prices are institutional consensus points where large
// flows first crossed, creating memory in the order book.
//
// RESEARCH BASIS:
// • Harris (1986), "A Transaction Data Study of Weekly and Intradaily Patterns in
// Stock Returns", J. Financial Economics 16(1), 99–117. Seminal intraday
// seasonality; opening prices anchor session behavior.
// • Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with Market
// Profile", Wiley. Initial Balance = first-hour range; opening is the reference
// for the entire session's auction mechanics.
// • Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section of
// Stock Returns", J. Finance 65(4), 1369–1407. Opening returns predict
// subsequent same-window returns; Day 1 decile spread > 11 bps.
// • Kirkpatrick & Dahlquist (2010), "Technical Analysis: The Complete Resource for
// Financial Market Technicians", FT Press. S/R levels rated 4.41/5 among
// practitioners; opening prices are consensus-driven S/R levels.
// • Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and the
// Stochastic Properties of Stock Returns", J. Finance. Buy signals after level
// breaches are followed by positive returns; opens act as structural levels.
// • Crabel (1990), "Playing the Opening Range Breakout", Stocks & Commodities.
// Opening range defines the stretch; breakout from open predicts continuation.
// ============================================================================
define(
title="5 Open Prices (Y/M/W/D/PrevD) Perfected",
position="onchart",
axis=false
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Display Group ---
var showYear = input(name="showYear", type="boolean", defaultValue=true, label="Show Year Open", group="Display")
var showMonth = input(name="showMonth", type="boolean", defaultValue=true, label="Show Month Open", group="Display")
var showWeek = input(name="showWeek", type="boolean", defaultValue=true, label="Show Week Open", group="Display")
var showDay = input(name="showDay", type="boolean", defaultValue=true, label="Show Day Open", group="Display")
var showPrevDay = input(name="showPrevDay", type="boolean", defaultValue=true, label="Show Prev Day Open", group="Display")
// --- Proximity Analysis ---
var showProximity = input(name="showProximity", type="boolean", defaultValue=true, label="Show Proximity Oscillator", group="Analysis")
var showDeviation = input(name="showDeviation", type="boolean", defaultValue=true, label="Show Open Deviation Score", group="Analysis")
var showNearestOpen = input(name="showNearestOpen", type="boolean", defaultValue=true, label="Highlight Nearest Open", group="Analysis")
var showCrossShapes = input(name="showCrossShapes", type="boolean", defaultValue=true, label="Show Open Cross Shapes", group="Analysis")
var proximityLookback = input(name="proximityLookback", type="number", defaultValue=14, label="Proximity ATR Lookback", constraints={min: 5, max: 100, step: 1}, group="Analysis")
// --- Line Styles ---
var lineWidth = input(name="lineWidth", type="number", defaultValue=1, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Line Style")
var showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Open Labels", group="Line Style")
// --- Colors ---
var yearColor = input(name="yearColor", type="color", defaultValue="#d50000", label="Year Open Color", group="Colors")
var monthColor = input(name="monthColor", type="color", defaultValue="#ff6d00", label="Month Open Color", group="Colors")
var weekColor = input(name="weekColor", type="color", defaultValue="#2962ff", label="Week Open Color", group="Colors")
var dayColor = input(name="dayColor", type="color", defaultValue="#00c853", label="Day Open Color", group="Colors")
var prevDayColor = input(name="prevDayColor", type="color", defaultValue="#9e9e9e", label="Prev Day Color", group="Colors")
var aboveColor = input(name="aboveColor", type="color", defaultValue="#26a69a", label="Above Open Color (Bull)", group="Colors")
var belowColor = input(name="belowColor", type="color", defaultValue="#ef5350", label="Below Open Color (Bear)", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries o = bars.open
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
// isnan guard: prevent computation on incomplete data
if (isnan(t[0]) || isnan(o[0]) || isnan(close[0])) {
return
}
// ------------------------------------------------------------------------------
// Calendar Math (UTC-based session boundaries)
// ------------------------------------------------------------------------------
var dayId = math.floor(t[0] / 86400000)
// Precise proleptic Gregorian calendar math (same foundation as 203_key_level)
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 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 month = mp + (mp < 10 ? 3 : -9)
var year = y + (month <= 2 ? 1 : 0)
var monthId = year * 12 + month
var yearId = year
// Year boundary
static lastYearId = -1
static val_y = 0.0
if (lastYearId == -1) {
lastYearId = yearId
val_y = o[0]
} else if (yearId > lastYearId) {
lastYearId = yearId
val_y = o[0]
}
// Month boundary
static lastMonthId = -1
static val_m = 0.0
if (lastMonthId == -1) {
lastMonthId = monthId
val_m = o[0]
} else if (monthId > lastMonthId) {
lastMonthId = monthId
val_m = o[0]
}
// Week: anchor Monday (1970-01-01 is Thursday, +3 day offset)
static lastWeekId = -1
static val_w = 0.0
var weekId = math.floor((dayId + 3) / 7)
if (lastWeekId == -1) {
lastWeekId = weekId
val_w = o[0]
} else if (weekId > lastWeekId) {
lastWeekId = weekId
val_w = o[0]
}
// Day: changes whenever dayId increments
static lastDayId = -1
static val_d = 0.0
static val_pd = 0.0
if (lastDayId == -1) {
lastDayId = dayId
val_d = o[0]
} else if (dayId > lastDayId) {
val_pd = val_d
lastDayId = dayId
val_d = o[0]
}
// ------------------------------------------------------------------------------
// Proximity Analysis — Price Deviation from Each Open Level
// ------------------------------------------------------------------------------
// Compute ATR for volatility-normalized deviation scoring
var trueRange = math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
timeseries atr = atr(proximityLookback)
var atrSafe = !isnan(atr) && atr > 0 ? atr : (high - low)
// Deviation from each open level in ATR units (volatility-normalized)
var devYear = atrSafe > 0 ? (close - val_y) / atrSafe : 0.0
var devMonth = atrSafe > 0 ? (close - val_m) / atrSafe : 0.0
var devWeek = atrSafe > 0 ? (close - val_w) / atrSafe : 0.0
var devDay = atrSafe > 0 ? (close - val_d) / atrSafe : 0.0
var devPrevDay = (val_pd > 0 && atrSafe > 0) ? (close - val_pd) / atrSafe : 0.0
// Composite open deviation (average of active deviations)
var activeDevCount = 0.0
var compositeDev = 0.0
if (showYear) { compositeDev = compositeDev + devYear; activeDevCount = activeDevCount + 1 }
if (showMonth) { compositeDev = compositeDev + devMonth; activeDevCount = activeDevCount + 1 }
if (showWeek) { compositeDev = compositeDev + devWeek; activeDevCount = activeDevCount + 1 }
if (showDay) { compositeDev = compositeDev + devDay; activeDevCount = activeDevCount + 1 }
if (showPrevDay && val_pd > 0) { compositeDev = compositeDev + devPrevDay; activeDevCount = activeDevCount + 1 }
var avgDev = activeDevCount > 0 ? compositeDev / activeDevCount : 0.0
// Proximity to nearest open level (distance in price terms)
var distYear = math.abs(close - val_y)
var distMonth = math.abs(close - val_m)
var distWeek = math.abs(close - val_w)
var distDay = math.abs(close - val_d)
var distPrevDay = val_pd > 0 ? math.abs(close - val_pd) : 999999.0
var minDist = distYear
var nearestOpen = val_y
var nearestColor = yearColor
var nearestLabel = "Year"
if (showMonth && distMonth < minDist) { minDist = distMonth; nearestOpen = val_m; nearestColor = monthColor; nearestLabel = "Month" }
if (showWeek && distWeek < minDist) { minDist = distWeek; nearestOpen = val_w; nearestColor = weekColor; nearestLabel = "Week" }
if (showDay && distDay < minDist) { minDist = distDay; nearestOpen = val_d; nearestColor = dayColor; nearestLabel = "Day" }
if (showPrevDay && val_pd > 0 && distPrevDay < minDist) { minDist = distPrevDay; nearestOpen = val_pd; nearestColor = prevDayColor; nearestLabel = "PrevDay" }
// ------------------------------------------------------------------------------
// Regime Detection (Price above/below day open as primary directional filter)
// ------------------------------------------------------------------------------
var aboveDayOpen = close > val_d
var aboveWeekOpen = close > val_w
var aboveMonthOpen = close > val_m
// Composite regime: bullish when above majority of active opens
var aboveCount = 0
var totalActive = 0
if (showDay) { aboveCount = aboveDayOpen ? aboveCount + 1 : aboveCount; totalActive = totalActive + 1 }
if (showWeek) { aboveCount = aboveWeekOpen ? aboveCount + 1 : aboveCount; totalActive = totalActive + 1 }
if (showMonth) { aboveCount = aboveMonthOpen ? aboveCount + 1 : aboveCount; totalActive = totalActive + 1 }
var regime = totalActive > 0 && aboveCount > totalActive / 2 ? 1 : 0 // 1 = bullish, 0 = bearish
// ------------------------------------------------------------------------------
// Cross Detection — Shape markers when price crosses open levels
// ------------------------------------------------------------------------------
var crossYearUp = close > val_y && !isnan(close[1]) && close[1] <= val_y
var crossYearDn = close < val_y && !isnan(close[1]) && close[1] >= val_y
var crossMonthUp = close > val_m && !isnan(close[1]) && close[1] <= val_m
var crossMonthDn = close < val_m && !isnan(close[1]) && close[1] >= val_m
var crossWeekUp = close > val_w && !isnan(close[1]) && close[1] <= val_w
var crossWeekDn = close < val_w && !isnan(close[1]) && close[1] >= val_w
var crossDayUp = close > val_d && !isnan(close[1]) && close[1] <= val_d
var crossDayDn = close < val_d && !isnan(close[1]) && close[1] >= val_d
var crossPrevDayUp = val_pd > 0 && close > val_pd && !isnan(close[1]) && close[1] <= val_pd
var crossPrevDayDn = val_pd > 0 && close < val_pd && !isnan(close[1]) && close[1] >= val_pd
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks open level touches, crosses, and session statistics.
static yearTouchCount = 0
static monthTouchCount = 0
static weekTouchCount = 0
static dayTouchCount = 0
static prevDayTouchCount = 0
static lastBarIndex = 0
static sessionCrossCount = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
// Track touches (price within 0.1% of open level)
var touchTolerance = close * 0.001
if (math.abs(close - val_y) < touchTolerance) { yearTouchCount = yearTouchCount + 1 }
if (math.abs(close - val_m) < touchTolerance) { monthTouchCount = monthTouchCount + 1 }
if (math.abs(close - val_w) < touchTolerance) { weekTouchCount = weekTouchCount + 1 }
if (math.abs(close - val_d) < touchTolerance) { dayTouchCount = dayTouchCount + 1 }
if (val_pd > 0 && math.abs(close - val_pd) < touchTolerance) { prevDayTouchCount = prevDayTouchCount + 1 }
// Track crosses
if (crossYearUp || crossYearDn || crossMonthUp || crossMonthDn || crossWeekUp || crossWeekDn || crossDayUp || crossDayDn || crossPrevDayUp || crossPrevDayDn) {
sessionCrossCount = sessionCrossCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Open Level Lines with Regime Coding and Proximity Analysis
// ------------------------------------------------------------------------------
// --- Year Open ---
if (showYear) {
plotLine(
value=val_y,
width=lineWidth,
colors=[yearColor],
label=["Year Open"],
desc=["Year opening price — institutional annual benchmark"]
)
}
// --- Month Open ---
if (showMonth) {
plotLine(
value=val_m,
width=lineWidth,
colors=[monthColor],
label=["Month Open"],
desc=["Month opening price — monthly institutional pivot"]
)
}
// --- Week Open ---
if (showWeek) {
plotLine(
value=val_w,
width=lineWidth,
colors=[weekColor],
label=["Week Open"],
desc=["Week opening price — weekly session anchor (Monday)"]
)
}
// --- Day Open ---
if (showDay) {
plotLine(
value=val_d,
width=lineWidth,
colors=[dayColor],
label=["Day Open"],
desc=["Day opening price — daily session anchor (Harris 1986 initial balance)"]
)
}
// --- Prev Day Open ---
if (showPrevDay && val_pd > 0) {
plotLine(
value=val_pd,
width=lineWidth,
colors=[prevDayColor],
label=["Prev Day Open"],
desc=["Previous day's opening price — rolling reference"]
)
}
// --- Proximity Highlight (thicker line on nearest open) ---
if (showNearestOpen) {
plotLine(
value=nearestOpen,
width=lineWidth + 1,
colors=[nearestColor],
label=["Nearest Open"],
desc=["Nearest open level to current price: " + nearestLabel]
)
}
// --- Proximity Oscillator (offchart: deviation from opens) ---
if (showProximity) {
plotLine(
value=avgDev,
width=2,
colors=[aboveColor, belowColor, neutralColor],
colorIndex=avgDev > 0.5 ? 0 : (avgDev < -0.5 ? 1 : 2),
label=["Open Deviation (ATR)"],
desc=["Average deviation from all open levels in ATR units"]
)
hline(value=0, color="#ffffff30", width=1)
hline(value=1, color=opacity(aboveColor, 20), width=1)
hline(value=-1, color=opacity(belowColor, 20), width=1)
}
// --- Open Deviation Score (composite z-score from all opens) ---
if (showDeviation) {
var devScore = activeDevCount > 0 ? compositeDev / math.sqrt(activeDevCount) : 0.0
plotBar(
value=devScore,
colors=[aboveColor, belowColor],
width=1,
label=["Open Deviation Score"],
desc=["Composite deviation score from all tracked open levels"]
)
}
// --- Cross Shape Markers ---
if (showCrossShapes) {
if (crossYearUp) {
plotShape(
value=val_y,
shape="triangleup",
color=aboveColor,
width=3,
label=["Year Open Cross Up"],
desc=["Price crossed above year open"]
)
}
if (crossYearDn) {
plotShape(
value=val_y,
shape="triangledown",
color=belowColor,
width=3,
label=["Year Open Cross Down"],
desc=["Price crossed below year open"]
)
}
if (crossMonthUp) {
plotShape(
value=val_m,
shape="triangleup",
color=aboveColor,
width=3,
label=["Month Open Cross Up"],
desc=["Price crossed above month open"]
)
}
if (crossMonthDn) {
plotShape(
value=val_m,
shape="triangledown",
color=belowColor,
width=3,
label=["Month Open Cross Down"],
desc=["Price crossed below month open"]
)
}
if (crossWeekUp) {
plotShape(
value=val_w,
shape="triangleup",
color=aboveColor,
width=3,
label=["Week Open Cross Up"],
desc=["Price crossed above week open"]
)
}
if (crossWeekDn) {
plotShape(
value=val_w,
shape="triangledown",
color=belowColor,
width=3,
label=["Week Open Cross Down"],
desc=["Price crossed below week open"]
)
}
if (crossDayUp) {
plotShape(
value=val_d,
shape="triangleup",
color=aboveColor,
width=3,
label=["Day Open Cross Up"],
desc=["Price crossed above day open"]
)
}
if (crossDayDn) {
plotShape(
value=val_d,
shape="triangledown",
color=belowColor,
width=3,
label=["Day Open Cross Down"],
desc=["Price crossed below day open"]
)
}
if (crossPrevDayUp) {
plotShape(
value=val_pd,
shape="triangleup",
color=aboveColor,
width=2,
label=["Prev Day Cross Up"],
desc=["Price crossed above previous day open"]
)
}
if (crossPrevDayDn) {
plotShape(
value=val_pd,
shape="triangledown",
color=belowColor,
width=2,
label=["Prev Day Cross Down"],
desc=["Price crossed below previous day open"]
)
}
}