ZACS Market Toolkit, Sessions, PD PS, HTF EQ , EMA, MACD

zace · study · 3501 行 · 点赞 76 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// © Zac / TradingView source credits as included below
// HA-MACD module original attribution: © EliCobra
// This Pine Script code includes HA-MACD source originally published under
// CC BY-NC-SA 4.0: https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=6
indicator("ZACS Market Toolkit — Sessions + PD/PS + HTF EQ + EMA + MACD", shorttitle="ZACS Market Toolkit", overlay=false, max_bars_back=5000, max_labels_count=500, max_lines_count=500, max_boxes_count=350)
 
// One lower-pane HA-MACD with the four price-overlay engines routed onto the chart.
// No historical entry logic, zone dating, or ATR clustering changed in this merge.
// Shared New York/London/Asia input sessions drive both backgrounds and PD/PS.
// Optional MACD bar coloring takes priority over SMC candle colors when enabled.
 
 
// ============================================================================
// MODULE A — SIX SESSION BACKGROUNDS / SHARED NY-LONDON-ASIA CLOCKS
// The first three session definitions are shared with the PD/PS level engine.
// Turning off their shading does not turn off their PD/PS calculations.
// ============================================================================
const string G_DISPLAY = "Sessions — Display Options"
bool showSessionNames = input.bool(false, "Show Session Names at Opening", group=G_DISPLAY)
 
const string G_NY = "Sessions — New York Background"
bool showNY = input.bool(true, "Show New York Background", group=G_NY)
string nySession = input.session("0930-1700", "New York Session", group=G_NY)
string nyTimezone = input.string("America/New_York", "New York Session Time Zone", group=G_NY)
color nyBgColor = input.color(color.blue, "New York Background Color", group=G_NY)
int nyBgTransparency = input.int(93, "New York Background Transparency", minval=0, maxval=100, group=G_NY)
 
const string G_LONDON = "Sessions — London Background"
bool showLondon = input.bool(true, "Show London Background", group=G_LONDON)
string londonSession = input.session("0300-0930", "London Session", group=G_LONDON)
string londonTimezone = input.string("America/New_York", "London Session Time Zone", group=G_LONDON)
color londonBgColor = input.color(color.green, "London Background Color", group=G_LONDON)
int londonBgTransparency = input.int(93, "London Background Transparency", minval=0, maxval=100, group=G_LONDON)
 
const string G_ASIA = "Sessions — Asia Background"
bool showAsia = input.bool(true, "Show Asia Background", group=G_ASIA)
string asiaSession = input.session("1700-0300", "Asia Session", group=G_ASIA)
string asiaTimezone = input.string("America/New_York", "Asia Session Time Zone", group=G_ASIA)
color asiaBgColor = input.color(color.yellow, "Asia Background Color", group=G_ASIA)
int asiaBgTransparency = input.int(93, "Asia Background Transparency", minval=0, maxval=100, group=G_ASIA)
 
const string G_CUSTOM1 = "Sessions — Custom 1"
bool showCustom1 = input.bool(false, "Enable Custom Session 1", group=G_CUSTOM1)
string custom1Name = input.string("Australia / Sydney", "Custom Session Name", group=G_CUSTOM1)
string custom1Session = input.session("0900-1700", "Session Hours", group=G_CUSTOM1)
string custom1Timezone = input.string("Australia/Sydney", "Session Time Zone", group=G_CUSTOM1)
color custom1Color = input.color(color.purple, "Background Color", group=G_CUSTOM1)
int custom1Transparency = input.int(93, "Background Transparency", minval=0, maxval=100, group=G_CUSTOM1)
 
const string G_CUSTOM2 = "Sessions — Custom 2"
bool showCustom2 = input.bool(false, "Enable Custom Session 2", group=G_CUSTOM2)
string custom2Name = input.string("Custom Session 2", "Custom Session Name", group=G_CUSTOM2)
string custom2Session = input.session("0900-1700", "Session Hours", group=G_CUSTOM2)
string custom2Timezone = input.string("America/New_York", "Session Time Zone", group=G_CUSTOM2)
color custom2Color = input.color(color.teal, "Background Color", group=G_CUSTOM2)
int custom2Transparency = input.int(93, "Background Transparency", minval=0, maxval=100, group=G_CUSTOM2)
 
const string G_CUSTOM3 = "Sessions — Custom 3"
bool showCustom3 = input.bool(false, "Enable Custom Session 3", group=G_CUSTOM3)
string custom3Name = input.string("Custom Session 3", "Custom Session Name", group=G_CUSTOM3)
string custom3Session = input.session("0900-1700", "Session Hours", group=G_CUSTOM3)
string custom3Timezone = input.string("America/New_York", "Session Time Zone", group=G_CUSTOM3)
color custom3Color = input.color(color.orange, "Background Color", group=G_CUSTOM3)
int custom3Transparency = input.int(93, "Background Transparency", minval=0, maxval=100, group=G_CUSTOM3)
 
bool inNY = not na(time(timeframe.period, nySession, nyTimezone))
bool inLondon = not na(time(timeframe.period, londonSession, londonTimezone))
bool inAsia = not na(time(timeframe.period, asiaSession, asiaTimezone))
bool inCustom1 = not na(time(timeframe.period, custom1Session, custom1Timezone))
bool inCustom2 = not na(time(timeframe.period, custom2Session, custom2Timezone))
bool inCustom3 = not na(time(timeframe.period, custom3Session, custom3Timezone))
 
bgcolor(showNY and inNY ? color.new(nyBgColor, nyBgTransparency) : na, title="New York Session Background", force_overlay=true)
bgcolor(showLondon and inLondon ? color.new(londonBgColor, londonBgTransparency) : na, title="London Session Background", force_overlay=true)
bgcolor(showAsia and inAsia ? color.new(asiaBgColor, asiaBgTransparency) : na, title="Asia Session Background", force_overlay=true)
bgcolor(showCustom1 and inCustom1 ? color.new(custom1Color, custom1Transparency) : na, title="Custom Session 1 Background", force_overlay=true)
bgcolor(showCustom2 and inCustom2 ? color.new(custom2Color, custom2Transparency) : na, title="Custom Session 2 Background", force_overlay=true)
bgcolor(showCustom3 and inCustom3 ? color.new(custom3Color, custom3Transparency) : na, title="Custom Session 3 Background", force_overlay=true)
 
if showSessionNames
    if showNY and inNY and not inNY[1]
        label.new(bar_index, high, "New York", yloc=yloc.abovebar, style=label.style_label_down, color=nyBgColor, textcolor=color.white, size=size.tiny, force_overlay=true)
    if showLondon and inLondon and not inLondon[1]
        label.new(bar_index, high, "London", yloc=yloc.abovebar, style=label.style_label_down, color=londonBgColor, textcolor=color.white, size=size.tiny, force_overlay=true)
    if showAsia and inAsia and not inAsia[1]
        label.new(bar_index, high, "Asia", yloc=yloc.abovebar, style=label.style_label_down, color=asiaBgColor, textcolor=color.black, size=size.tiny, force_overlay=true)
    if showCustom1 and inCustom1 and not inCustom1[1]
        label.new(bar_index, high, custom1Name, yloc=yloc.abovebar, style=label.style_label_down, color=custom1Color, textcolor=color.white, size=size.tiny, force_overlay=true)
    if showCustom2 and inCustom2 and not inCustom2[1]
        label.new(bar_index, high, custom2Name, yloc=yloc.abovebar, style=label.style_label_down, color=custom2Color, textcolor=color.white, size=size.tiny, force_overlay=true)
    if showCustom3 and inCustom3 and not inCustom3[1]
        label.new(bar_index, high, custom3Name, yloc=yloc.abovebar, style=label.style_label_down, color=custom3Color, textcolor=color.white, size=size.tiny, force_overlay=true)
 
 
// MODULE B — PD/PS v89 level and cluster engine
 
// PREVIOUS DAY / PREVIOUS SESSION LEVEL SETTINGS (v89)
 
// ============================================================================
 
// PREVIOUS DAY / PREVIOUS SESSIONS — PD/PS CLUSTERS (OCT 24 MODULE)
 
// -----------------------------------------------------------------------------
 
// PD: prior completed broker/TradingView daily candle (not a custom NY day).
 
// PS: final high/low of each completed NY, London, or Asia session.
 
string G_LEVELS = "PD/PS Levels - General"
 
bool showPD = input.bool(true, "Show Previous Day High / Low", group=G_LEVELS)
 
bool showPrevNY = input.bool(true, "Show Previous New York High / Low", group=G_LEVELS)
 
bool showPrevLondon = input.bool(true, "Show Previous London High / Low", group=G_LEVELS)
 
bool showPrevAsia = input.bool(true, "Show Previous Asia High / Low", group=G_LEVELS)
 
int keepLevelSegments = input.int(20, "Keep Last N Segments Per Level", minval=1, maxval=45, group=G_LEVELS)
 
bool showLevelFlags = input.bool(true, "Show Price Flags at Latest Line Ends", group=G_LEVELS)
 
bool projectLevels = input.bool(true, "Extend Active Levels to Current Session End", group=G_LEVELS,
 
     tooltip="Uses the scheduled end of the active NY/London/Asia session; historical segments end at their actual rollover time.")
 
 
 
string G_MATCH = "PD/PS ATR Confluence"
 
bool onlyMatched = input.bool(true, "Only Show Qualifying Clusters", group=G_MATCH,
 
     tooltip="ON: Display only members of a qualifying cluster, apart from optional standalone PDH/PDL. OFF: Display every enabled PD/PS level.")
 
string clusterQualificationMode = input.string("Any Two Levels", "Cluster Qualification Mode",
 
     options=["PD + PS Only", "Any Two Levels", "PS Only"], group=G_MATCH,
 
     tooltip="PD + PS Only: each cluster needs at least one previous-day level and one previous-session level (original behaviour at minimum 2). Any Two Levels: any enabled PD/PS combination, including PS-only clusters. PS Only: only previous-session levels can qualify as a cluster. All members of a cluster must fit within the specified ATR price range.")
 
int minClusterLevels = input.int(2, "Minimum Levels in Cluster", minval=2, maxval=8, group=G_MATCH,
 
     tooltip="Minimum number of individual enabled highs/lows belonging to a single tight cluster. Default 2. Select 3 or more to demand stronger confluence. There are up to 8 levels total (2 PD, 6 PS).")
 
bool alwaysPD = input.bool(true, "Always Show PDH / PDL", group=G_MATCH,
 
     tooltip="When ON, eligible PDH and PDL remain visible even outside qualified clusters, including when Cluster Qualification Mode is PS Only.")
 
int matchATRLen = input.int(14, "ATR Length for Clusters", minval=1, maxval=200, group=G_MATCH)
 
int matchATRSessionCount = input.int(10, "Previous Same-Type Sessions to Average", minval=1, maxval=50, group=G_MATCH,
 
     tooltip="Each completed NY, London, and Asia session contributes its average chart-timeframe ATR across all available bars in that session. For a new session, use the mean of the last N completed sessions of that SAME type. The active session is never included. Uses available completed sessions during startup; never falls back to a single opening-candle ATR.")
 
float matchATRMult = input.float(0.5, "Max Cluster Price Spread in ATR", minval=0.0, maxval=10.0, step=0.1, group=G_MATCH,
 
     tooltip="A qualifying cluster must fit entirely inside a window of this many historical same-session ATRs, measured from its lowest to highest member. Default 0.5 ATR.")
 
 
 
string G_PD = "Previous Day Styles"
 
bool showPDH = input.bool(true, "PDH", group=G_PD, inline="pdh")
 
color pdhColor = input.color(color.orange, "Color", group=G_PD, inline="pdh")
 
int pdhWidth = input.int(3, "Width", minval=1, maxval=10, group=G_PD, inline="pdh")
 
string pdhStyle = input.string("Dashed", "Style", options=["Solid", "Dashed", "Dotted"], group=G_PD, inline="pdh")
 
bool showPDL = input.bool(true, "PDL", group=G_PD, inline="pdl")
 
color pdlColor = input.color(color.orange, "Color", group=G_PD, inline="pdl")
 
int pdlWidth = input.int(3, "Width", minval=1, maxval=10, group=G_PD, inline="pdl")
 
string pdlStyle = input.string("Dashed", "Style", options=["Solid", "Dashed", "Dotted"], group=G_PD, inline="pdl")
 
 
 
string G_NYLEVELS = "Previous New York Styles"
 
bool showNYH = input.bool(true, "NY High", group=G_NYLEVELS, inline="nyh")
 
color nyhColor = input.color(color.blue, "Color", group=G_NYLEVELS, inline="nyh")
 
int nyhWidth = input.int(2, "Width", minval=1, maxval=10, group=G_NYLEVELS, inline="nyh")
 
string nyhStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_NYLEVELS, inline="nyh")
 
bool showNYL = input.bool(true, "NY Low", group=G_NYLEVELS, inline="nyl")
 
color nylColor = input.color(color.blue, "Color", group=G_NYLEVELS, inline="nyl")
 
int nylWidth = input.int(2, "Width", minval=1, maxval=10, group=G_NYLEVELS, inline="nyl")
 
string nylStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_NYLEVELS, inline="nyl")
 
 
 
string G_LONLEVELS = "Previous London Styles"
 
bool showLONH = input.bool(true, "London High", group=G_LONLEVELS, inline="lh")
 
color lonhColor = input.color(color.green, "Color", group=G_LONLEVELS, inline="lh")
 
int lonhWidth = input.int(2, "Width", minval=1, maxval=10, group=G_LONLEVELS, inline="lh")
 
string lonhStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_LONLEVELS, inline="lh")
 
bool showLONL = input.bool(true, "London Low", group=G_LONLEVELS, inline="ll")
 
color lonlColor = input.color(color.green, "Color", group=G_LONLEVELS, inline="ll")
 
int lonlWidth = input.int(2, "Width", minval=1, maxval=10, group=G_LONLEVELS, inline="ll")
 
string lonlStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_LONLEVELS, inline="ll")
 
 
 
string G_ASIALEVELS = "Previous Asia Styles"
 
bool showASIAH = input.bool(true, "Asia High", group=G_ASIALEVELS, inline="ah")
 
color asiahColor = input.color(color.yellow, "Color", group=G_ASIALEVELS, inline="ah")
 
int asiahWidth = input.int(2, "Width", minval=1, maxval=10, group=G_ASIALEVELS, inline="ah")
 
string asiahStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_ASIALEVELS, inline="ah")
 
bool showASIAL = input.bool(true, "Asia Low", group=G_ASIALEVELS, inline="al")
 
color asialColor = input.color(color.yellow, "Color", group=G_ASIALEVELS, inline="al")
 
int asialWidth = input.int(2, "Width", minval=1, maxval=10, group=G_ASIALEVELS, inline="al")
 
string asialStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], group=G_ASIALEVELS, inline="al")
 
 
 
 
 
// ============================================================================
 
// PRIOR DAY / PRIOR SESSION LEVELS — ORIGINAL V89 CALCULATIONS + DRAWINGS
 
// ============================================================================
 
// Imported from the user's October 24 PD/PS module.
 
// ============================================================================
 
// Use the independently adjustable NY, London and Asia session windows
 
// and IANA time zones above (default America/New_York, DST-aware).
 
// No session background shading is drawn by this indicator.
 
string nyTZ = nyTimezone
 
string lonSession = londonSession
 
string lonTZ = londonTimezone
 
string asiaSessionSpec = asiaSession
 
string asiaTZ = asiaTimezone
 
bool nyStarted = inNY and not (inNY[1] == true)
 
bool lonStarted = inLondon and not (inLondon[1] == true)
 
bool asiaStarted = inAsia and not (inAsia[1] == true)
 
 
 
// -----------------------------------------------------------------------------
 
// PREVIOUS DAY AND COMPLETED PREVIOUS-SESSION LEVELS (PRICE CHART)
 
// -----------------------------------------------------------------------------
 
// Derive the actual clock-time endpoint for the active adjustable input.session.
 
// For an overnight window such as 17:00-03:00, choose the next 03:00.
 
// Construct local calendar dates rather than adding 24 hours to a scheduled
 
// endpoint, so IANA timezones continue to work through DST transitions.
 
f_sessionScheduledEnd(string sessionSpec, string sessionTZ) =>
 
    int endHour = int(str.tonumber(str.substring(sessionSpec, 5, 7)))
 
    int endMinute = int(str.tonumber(str.substring(sessionSpec, 7, 9)))
 
    int localYear = year(time, sessionTZ)
 
    int localMonth = month(time, sessionTZ)
 
    int localDay = dayofmonth(time, sessionTZ)
 
    int endToday = timestamp(sessionTZ, localYear, localMonth, localDay, endHour, endMinute)
 
    int tomorrowMarker = timestamp(sessionTZ, localYear, localMonth, localDay, 0, 0) + 36 * 60 * 60 * 1000
 
    int endTomorrow = timestamp(sessionTZ, year(tomorrowMarker, sessionTZ), month(tomorrowMarker, sessionTZ), dayofmonth(tomorrowMarker, sessionTZ), endHour, endMinute)
 
    endToday > time ? endToday : endTomorrow
 
 
 
int barEnd = nz(time_close, time + timeframe.in_seconds(timeframe.period) * 1000)
 
int activeSessionEnd = inNY ? f_sessionScheduledEnd(nySession, nyTZ) : inLondon ? f_sessionScheduledEnd(lonSession, lonTZ) : inAsia ? f_sessionScheduledEnd(asiaSessionSpec, asiaTZ) : barEnd
 
int activeLineEnd = projectLevels ? math.max(barEnd, activeSessionEnd) : barEnd
 
 
 
// PREVIOUS DAY H/L — STRICT BROKER DAILY ROLLOVER (NO FUTURE HTF VALUES)
 
// Use TradingView's own "D" day membership from the current instrument.
 
// Accumulate completed chart candles inside each broker day. On the FIRST bar
 
// of the next broker day, freeze the just-completed day's extremes, then start
 
// an entirely NEW PDH/PDL segment at that bar. No later day's high or low can
 
// appear on any earlier chart bar. This also respects weekend/holiday gaps:
 
// Friday's completed H/L is kept until the next real trading day begins.
 
// Unlike a bare calendar-date comparison, time("D") follows the instrument's
 
// TradingView daily-session rollover, including overnight trading sessions.
 
//
 
// Startup guard: Do not create a PD level from the first PARTIAL day in the
 
// chart history. Only use a day once its start and end have both been seen.
 
int brokerDayTime = time("D")
 
bool newDailyPeriod = not na(brokerDayTime) and not na(brokerDayTime[1]) and brokerDayTime != brokerDayTime[1]
 
var float dayBuildingHigh = na
 
var float dayBuildingLow = na
 
var bool buildingDayStartedAtBoundary = false
 
var float previousDayHigh = na
 
var float previousDayLow = na
 
 
 
if newDailyPeriod
 
    // The previous session's range was built exclusively from bars BEFORE
 
    // this rollover. It is now closed and is safe for today's PD/PS clusters.
 
    if buildingDayStartedAtBoundary and not na(dayBuildingHigh) and not na(dayBuildingLow)
 
        previousDayHigh := dayBuildingHigh
 
        previousDayLow := dayBuildingLow
 
    buildingDayStartedAtBoundary := true
 
    dayBuildingHigh := high
 
    dayBuildingLow := low
 
else if not na(brokerDayTime)
 
    dayBuildingHigh := na(dayBuildingHigh) ? high : math.max(dayBuildingHigh, high)
 
    dayBuildingLow := na(dayBuildingLow) ? low : math.min(dayBuildingLow, low)
 
 
 
// Each running session maintains an independent H/L. Its previous levels are
 
// replaced ONLY when that particular session finishes, not when another ends.
 
var float nyRunHigh = na
 
var float nyRunLow = na
 
var float lonRunHigh = na
 
var float lonRunLow = na
 
var float asiaRunHigh = na
 
var float asiaRunLow = na
 
var float previousNYHigh = na
 
var float previousNYLow = na
 
var float previousLondonHigh = na
 
var float previousLondonLow = na
 
var float previousAsiaHigh = na
 
var float previousAsiaLow = na
 
 
 
// The session start booleans above are reused here unchanged.
 
bool nyEnded = not inNY and (inNY[1] == true)
 
bool lonEnded = not inLondon and (inLondon[1] == true)
 
bool asiaEnded = not inAsia and (inAsia[1] == true)
 
 
 
if nyEnded and not na(nyRunHigh)
 
    previousNYHigh := nyRunHigh
 
    previousNYLow := nyRunLow
 
if lonEnded and not na(lonRunHigh)
 
    previousLondonHigh := lonRunHigh
 
    previousLondonLow := lonRunLow
 
if asiaEnded and not na(asiaRunHigh)
 
    previousAsiaHigh := asiaRunHigh
 
    previousAsiaLow := asiaRunLow
 
 
 
if inNY
 
    nyRunHigh := nyStarted ? high : math.max(nz(nyRunHigh, high), high)
 
    nyRunLow := nyStarted ? low : math.min(nz(nyRunLow, low), low)
 
if inLondon
 
    lonRunHigh := lonStarted ? high : math.max(nz(lonRunHigh, high), high)
 
    lonRunLow := lonStarted ? low : math.min(nz(lonRunLow, low), low)
 
if inAsia
 
    asiaRunHigh := asiaStarted ? high : math.max(nz(asiaRunHigh, high), high)
 
    asiaRunLow := asiaStarted ? low : math.min(nz(asiaRunLow, low), low)
 
 
 
// SAME-TYPE HISTORICAL SESSION ATR (no opening-candle ATR sampling)
 
// 1. Calculate ATR(14 by default) on the current chart timeframe.
 
// 2. Accumulate every CONFIRMED ATR observation inside each session separately.
 
// 3. Once that session has ended, save its per-bar average in that session's
 
//    own bounded history of completed session averages (NY / London / Asia).
 
// 4. When a new session STARTS, use the mean of the last N *completed sessions
 
//    of that same type*. Keep that reference constant for this entire session.
 
// This gives each historical session equal weight, regardless of missing bars.
 
// No data from the active/incomplete session affects its own tolerance.
 
float rawLevelATR = ta.atr(matchATRLen)
 
 
 
var array<float> nyATRHistory = array.new_float()
 
var array<float> londonATRHistory = array.new_float()
 
var array<float> asiaATRHistory = array.new_float()
 
var float nyATRTotal = 0.0
 
var float londonATRTotal = 0.0
 
var float asiaATRTotal = 0.0
 
var int nyATRBars = 0
 
var int londonATRBars = 0
 
var int asiaATRBars = 0
 
 
 
f_meanSessionATR(array<float> samples) =>
 
    float result = na
 
    int count = array.size(samples)
 
    if count > 0
 
        float total = 0.0
 
        for i = 0 to count - 1
 
            total += array.get(samples, i)
 
        result := total / count
 
    result
 
 
 
f_addCompletedSession(array<float> samples, float total, int bars, int keepCount) =>
 
    if bars > 0
 
        array.push(samples, total / bars)
 
        if array.size(samples) > keepCount
 
            array.shift(samples)
 
    0
 
 
 
// The three sessions retain separate buckets, even when user-defined
 
// session times overlap. Historical bars are only accumulated once, at close.
 
if barstate.isconfirmed
 
    // Flush fully observed previous sessions before processing the new bar.
 
    if nyEnded
 
        f_addCompletedSession(nyATRHistory, nyATRTotal, nyATRBars, matchATRSessionCount)
 
    if lonEnded
 
        f_addCompletedSession(londonATRHistory, londonATRTotal, londonATRBars, matchATRSessionCount)
 
    if asiaEnded
 
        f_addCompletedSession(asiaATRHistory, asiaATRTotal, asiaATRBars, matchATRSessionCount)
 
 
 
    if nyStarted
 
        nyATRTotal := 0.0
 
        nyATRBars := 0
 
    if lonStarted
 
        londonATRTotal := 0.0
 
        londonATRBars := 0
 
    if asiaStarted
 
        asiaATRTotal := 0.0
 
        asiaATRBars := 0
 
 
 
    if not na(rawLevelATR)
 
        if inNY
 
            nyATRTotal += rawLevelATR
 
            nyATRBars += 1
 
        if inLondon
 
            londonATRTotal += rawLevelATR
 
            londonATRBars += 1
 
        if inAsia
 
            asiaATRTotal += rawLevelATR
 
            asiaATRBars += 1
 
 
 
// The same priority as activeSessionEnd: NY, then London, then Asia.
 
// In an unusual no-session gap, retain the last session's locked tolerance.
 
// Before any completed comparable session exists, no ATR-based cluster can be
 
// decided; the "Always Show PDH / PDL" setting remains independent.
 
var float lockedLevelATR = na
 
if nyStarted or lonStarted or asiaStarted
 
    lockedLevelATR := inNY ? f_meanSessionATR(nyATRHistory) :
 
         inLondon ? f_meanSessionATR(londonATRHistory) :
 
         f_meanSessionATR(asiaATRHistory)
 
float maxLevelDistance = lockedLevelATR * matchATRMult
 
// Inspect the currently locked historical reference and tolerance in the
 
// TradingView Data Window; these do not create visible chart signals.
 
// Historical ATR reference is retained internally; no additional plot slots.
 
// Diagnostic Data Window plots omitted to keep the base chart uncluttered.
 
// plot(maxLevelDistance, "Cluster Maximum PD/PS Distance", display=display.data_window)
 
f_near(float a, float b, float distance) =>
 
    not na(a) and not na(b) and not na(distance) and math.abs(a - b) <= distance
 
 
 
bool eligiblePDH = showPD and showPDH and not na(previousDayHigh)
 
bool eligiblePDL = showPD and showPDL and not na(previousDayLow)
 
bool eligibleNYH = showPrevNY and showNYH and not na(previousNYHigh)
 
bool eligibleNYL = showPrevNY and showNYL and not na(previousNYLow)
 
bool eligibleLONH = showPrevLondon and showLONH and not na(previousLondonHigh)
 
bool eligibleLONL = showPrevLondon and showLONL and not na(previousLondonLow)
 
bool eligibleASIAH = showPrevAsia and showASIAH and not na(previousAsiaHigh)
 
bool eligibleASIAL = showPrevAsia and showASIAL and not na(previousAsiaLow)
 
 
 
// Cluster qualification is independent of the line-drawing code below.
 
// Evaluate all EIGHT original PD/PS levels without changing their values.
 
// Each valid group must fit inside one bounded price range (max-min <= ATR
 
// tolerance). Merely chaining A near B and B near C is NOT enough when
 
// A and C are farther apart than the permitted range.
 
//
 
// Use each eligible level as a potential window's LOWEST member. Every
 
// qualifying window marks all its constituent levels. This supports any
 
// count from 2 through 8, without lookahead or unconfirmed-session levels.
 
array<float> clusterPrices = array.from(previousDayHigh, previousDayLow,
 
     previousNYHigh, previousNYLow, previousLondonHigh, previousLondonLow,
 
     previousAsiaHigh, previousAsiaLow)
 
array<bool> clusterEligible = array.from(eligiblePDH, eligiblePDL,
 
     eligibleNYH, eligibleNYL, eligibleLONH, eligibleLONL,
 
     eligibleASIAH, eligibleASIAL)
 
array<bool> clusterQualified = array.new_bool(8, false)
 
array<bool> windowMembers = array.new_bool(8, false)
 
 
 
if onlyMatched and not na(maxLevelDistance) and maxLevelDistance >= 0
 
    for anchor = 0 to 7
 
        bool anchorEnabled = array.get(clusterEligible, anchor) and
 
             (clusterQualificationMode != "PS Only" or anchor >= 2)
 
        if anchorEnabled
 
            float windowLow = array.get(clusterPrices, anchor)
 
            int windowCount = 0
 
            bool hasPD = false
 
            bool hasPS = false
 
            array.fill(windowMembers, false)
 
            for candidate = 0 to 7
 
                bool candidateEnabled = array.get(clusterEligible, candidate) and
 
                     (clusterQualificationMode != "PS Only" or candidate >= 2)
 
                if candidateEnabled
 
                    float candidatePrice = array.get(clusterPrices, candidate)
 
                    bool inWindow = candidatePrice >= windowLow and candidatePrice - windowLow <= maxLevelDistance
 
                    if inWindow
 
                        array.set(windowMembers, candidate, true)
 
                        windowCount += 1
 
                        hasPD := hasPD or candidate < 2
 
                        hasPS := hasPS or candidate >= 2
 
            bool qualifiedWindow = windowCount >= minClusterLevels and
 
                 (clusterQualificationMode != "PD + PS Only" or (hasPD and hasPS))
 
            if qualifiedWindow
 
                for member = 0 to 7
 
                    if array.get(windowMembers, member)
 
                        array.set(clusterQualified, member, true)
 
 
 
// When cluster-only visibility is disabled, every enabled level is drawn.
 
// Always Show PDH/PDL remains an explicit override for those two levels.
 
bool drawPDH = eligiblePDH and (not onlyMatched or alwaysPD or array.get(clusterQualified, 0))
 
bool drawPDL = eligiblePDL and (not onlyMatched or alwaysPD or array.get(clusterQualified, 1))
 
bool drawNYH = eligibleNYH and (not onlyMatched or array.get(clusterQualified, 2))
 
bool drawNYL = eligibleNYL and (not onlyMatched or array.get(clusterQualified, 3))
 
bool drawLONH = eligibleLONH and (not onlyMatched or array.get(clusterQualified, 4))
 
bool drawLONL = eligibleLONL and (not onlyMatched or array.get(clusterQualified, 5))
 
bool drawASIAH = eligibleASIAH and (not onlyMatched or array.get(clusterQualified, 6))
 
bool drawASIAL = eligibleASIAL and (not onlyMatched or array.get(clusterQualified, 7))
 
 
 
f_priceLineStyle(string selected) =>
 
    selected == "Dashed" ? line.style_dashed : selected == "Dotted" ? line.style_dotted : line.style_solid
 
 
 
// Every completed level uses its own history, independent of others; the
 
// last level is projected forward only while it remains the active segment.
 
f_manageLevel(array<line> history, line active, float level, bool visible, bool changed, color lc, int lw, string ls) =>
 
    line result = active
 
    bool priceChanged = not na(result) and not na(level) and line.get_y1(result) != level
 
    if changed or priceChanged or not visible or na(level)
 
        if not na(result)
 
            line.set_x2(result, math.max(line.get_x1(result) + 1, time))
 
            result := na
 
    if visible and not na(level)
 
        if na(result)
 
            result := line.new(time, level, time + 1, level, xloc=xloc.bar_time, extend=extend.none,
 
                 color=lc, width=lw, style=f_priceLineStyle(ls), force_overlay=true)
 
            array.push(history, result)
 
            if array.size(history) > keepLevelSegments
 
                line.delete(array.shift(history))
 
        line.set_x2(result, math.max(line.get_x1(result) + 1, barstate.islast ? activeLineEnd : barEnd))
 
    result
 
 
 
var array<line> histPDH = array.new<line>()
 
var array<line> histPDL = array.new<line>()
 
var array<line> histNYH = array.new<line>()
 
var array<line> histNYL = array.new<line>()
 
var array<line> histLONH = array.new<line>()
 
var array<line> histLONL = array.new<line>()
 
var array<line> histASIAH = array.new<line>()
 
var array<line> histASIAL = array.new<line>()
 
var line linePDH = na
 
var line linePDL = na
 
var line lineNYH = na
 
var line lineNYL = na
 
var line lineLONH = na
 
var line lineLONL = na
 
var line lineASIAH = na
 
var line lineASIAL = na
 
 
 
linePDH := f_manageLevel(histPDH, linePDH, previousDayHigh, drawPDH, newDailyPeriod, pdhColor, pdhWidth, pdhStyle)
 
linePDL := f_manageLevel(histPDL, linePDL, previousDayLow, drawPDL, newDailyPeriod, pdlColor, pdlWidth, pdlStyle)
 
lineNYH := f_manageLevel(histNYH, lineNYH, previousNYHigh, drawNYH, nyEnded, nyhColor, nyhWidth, nyhStyle)
 
lineNYL := f_manageLevel(histNYL, lineNYL, previousNYLow, drawNYL, nyEnded, nylColor, nylWidth, nylStyle)
 
lineLONH := f_manageLevel(histLONH, lineLONH, previousLondonHigh, drawLONH, lonEnded, lonhColor, lonhWidth, lonhStyle)
 
lineLONL := f_manageLevel(histLONL, lineLONL, previousLondonLow, drawLONL, lonEnded, lonlColor, lonlWidth, lonlStyle)
 
lineASIAH := f_manageLevel(histASIAH, lineASIAH, previousAsiaHigh, drawASIAH, asiaEnded, asiahColor, asiahWidth, asiahStyle)
 
lineASIAL := f_manageLevel(histASIAL, lineASIAL, previousAsiaLow, drawASIAL, asiaEnded, asialColor, asialWidth, asialStyle)
 
 
 
f_latestFlag(label old, bool visible, float price, string name, color flagColor) =>
 
    label result = old
 
    if visible and not na(price)
 
        if na(result)
 
            result := label.new(activeLineEnd, price, name, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_left,
 
                 color=flagColor, textcolor=color.white, size=size.tiny, force_overlay=true)
 
        else
 
            label.set_xy(result, activeLineEnd, price)
 
            label.set_color(result, flagColor)
 
    else
 
        if not na(result)
 
            label.delete(result)
 
        result := na
 
    result
 
 
 
var label flagPDH = na
 
var label flagPDL = na
 
var label flagNYH = na
 
var label flagNYL = na
 
var label flagLONH = na
 
var label flagLONL = na
 
var label flagASIAH = na
 
var label flagASIAL = na
 
if barstate.islast
 
    flagPDH := f_latestFlag(flagPDH, showLevelFlags and drawPDH, previousDayHigh, "PDH", pdhColor)
 
    flagPDL := f_latestFlag(flagPDL, showLevelFlags and drawPDL, previousDayLow, "PDL", pdlColor)
 
    flagNYH := f_latestFlag(flagNYH, showLevelFlags and drawNYH, previousNYHigh, "PNYH", nyhColor)
 
    flagNYL := f_latestFlag(flagNYL, showLevelFlags and drawNYL, previousNYLow, "PNYL", nylColor)
 
    flagLONH := f_latestFlag(flagLONH, showLevelFlags and drawLONH, previousLondonHigh, "PLH", lonhColor)
 
    flagLONL := f_latestFlag(flagLONL, showLevelFlags and drawLONL, previousLondonLow, "PLL", lonlColor)
 
    flagASIAH := f_latestFlag(flagASIAH, showLevelFlags and drawASIAH, previousAsiaHigh, "PAH", asiahColor)
 
    flagASIAL := f_latestFlag(flagASIAL, showLevelFlags and drawASIAL, previousAsiaLow, "PAL", asialColor)
 
 
 
 
// MODULE C — ZACS EMA seven-state slope engine
 
// ─────────────────────────────────────────────────────────────────────────────
 
// EMA AND SLOPE ENGINE
 
// ─────────────────────────────────────────────────────────────────────────────
 
const string G_EMA = "01 — EMA & Slope Engine"
 
showEMA       = input.bool(true, "Show EMA", group=G_EMA)
 
emaLength     = input.int(200, "EMA Length", minval=1, group=G_EMA)
 
emaSource     = input.source(close, "EMA Source", group=G_EMA)
 
slopeLookback = input.int(5, "Slope Lookback (Bars)", minval=1, group=G_EMA)
 
atrLength     = input.int(14, "Slope ATR Length", minval=1, group=G_EMA)
 
flatThreshold = input.float(0.020, "Neutral / Directional Threshold (ATR)", minval=0.0, step=0.005, group=G_EMA)
 
strongThreshold = input.float(0.080, "Strong Threshold (ATR)", minval=0.0, step=0.005, group=G_EMA)
 
strongestThreshold = input.float(0.160, "Strongest Threshold (ATR)", minval=0.0, step=0.005, group=G_EMA)
 
lockColors = input.bool(false, "Lock Slope Colors Until Candle Close", group=G_EMA,
 
     tooltip="OFF preserves the live color behavior of our newer combined indicator. ON holds the last confirmed slope color while the current candle is forming. The EMA value itself still updates live.")
 
 
 
// ─────────────────────────────────────────────────────────────────────────────
 
// CUSTOM STYLE FOR EACH OF THE SEVEN SLOPE STATES
 
// ─────────────────────────────────────────────────────────────────────────────
 
const string G_B3 = "02 — Strongest Bullish"
 
b3Color = input.color(color.rgb(0, 120, 255), "Color", group=G_B3)
 
b3Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_B3)
 
b3Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_B3)
 
 
 
const string G_B2 = "03 — Strong Bullish"
 
b2Color = input.color(color.rgb(0, 175, 65), "Color", group=G_B2)
 
b2Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_B2)
 
b2Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_B2)
 
 
 
const string G_B1 = "04 — Weak Bullish"
 
b1Color = input.color(color.rgb(145, 230, 145), "Color", group=G_B1)
 
b1Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_B1)
 
b1Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_B1)
 
 
 
const string G_FLAT = "05 — Neutral"
 
fColor = input.color(color.gray, "Color", group=G_FLAT)
 
fWidth = input.int(3, "Line Width", minval=1, maxval=10, group=G_FLAT)
 
fStyle = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_FLAT)
 
 
 
const string G_S1 = "06 — Weak Bearish"
 
s1Color = input.color(color.yellow, "Color", group=G_S1)
 
s1Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_S1)
 
s1Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_S1)
 
 
 
const string G_S2 = "07 — Strong Bearish"
 
s2Color = input.color(color.orange, "Color", group=G_S2)
 
s2Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_S2)
 
s2Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_S2)
 
 
 
const string G_S3 = "08 — Strongest Bearish"
 
s3Color = input.color(color.red, "Color", group=G_S3)
 
s3Width = input.int(3, "Line Width", minval=1, maxval=10, group=G_S3)
 
s3Style = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_S3)
 
 
 
// ─────────────────────────────────────────────────────────────────────────────
 
// OPTIONAL DIRECTIONAL / SLOPE FILTER AND ALERT CONTROLS
 
// These settings DO NOT hide or recolor the EMA. They qualify the optional
 
// signal markers, alerts and dashboard, for use in future strategies.
 
// ─────────────────────────────────────────────────────────────────────────────
 
const string G_FILTER = "09 — Direction & Strength Filter"
 
minimumStrength = input.string("Weak+", "Minimum Slope Strength", options=["Weak+", "Strong+", "Strongest Only"], group=G_FILTER)
 
priceSideFilter = input.string("Off", "EMA Price-Side Filter", options=["Off", "Close on Correct Side", "Entire Body on Correct Side"], group=G_FILTER,
 
     tooltip="For bullish qualification, close must be above the EMA; for bearish, below. The entire-body option also requires open on the correct side. Price filters affect only signals/alerts, never the EMA line.")
 
confirmBars = input.int(1, "Consecutive Qualified Closed Candles", minval=1, maxval=50, group=G_FILTER,
 
     tooltip="Required consecutive candles meeting slope strength, direction, and optional price-side criteria before a qualification alert.")
 
 
 
const string G_SIGNAL = "10 — Optional Signals & Display"
 
showQualificationDots = input.bool(false, "Show New Qualified Direction Dots", group=G_SIGNAL)
 
showResumeDots = input.bool(false, "Show Neutral-Pause Trend Resumption Dots", group=G_SIGNAL)
 
maxNeutralPause = input.int(3, "Max Neutral Pause Bars", minval=1, maxval=100, group=G_SIGNAL)
 
showDashboard = input.bool(false, "Show Compact Slope Dashboard", group=G_SIGNAL)
 
 
 
// ─────────────────────────────────────────────────────────────────────────────
 
// CORE ENGINE: EXACT SAME NORMALIZATION AS THE NEWER COMBINED INDICATOR
 
// ─────────────────────────────────────────────────────────────────────────────
 
float emaValue = ta.ema(emaSource, emaLength)
 
float atrValue = ta.atr(atrLength)
 
float slopeATR = not na(emaValue[slopeLookback]) and not na(atrValue) and atrValue > 0.0 ?
 
     (emaValue - emaValue[slopeLookback]) / atrValue : na
 
 
 
// Prevent overlapping/out-of-order thresholds.
 
float strongCut = math.max(strongThreshold, flatThreshold)
 
float strongestCut = math.max(strongestThreshold, strongCut)
 
 
 
// +3 / +2 / +1 / 0 / -1 / -2 / -3.
 
int rawState = 0
 
if not na(slopeATR)
 
    if slopeATR > flatThreshold
 
        rawState := slopeATR >= strongestCut ? 3 : slopeATR >= strongCut ? 2 : 1
 
    else if slopeATR < -flatThreshold
 
        rawState := slopeATR <= -strongestCut ? -3 : slopeATR <= -strongCut ? -2 : -1
 
 
 
int state = lockColors and not barstate.isconfirmed ? nz(rawState[1], 0) : rawState
 
 
 
color stateColor = switch state
 
    3  => b3Color
 
    2  => b2Color
 
    1  => b1Color
 
    -1 => s1Color
 
    -2 => s2Color
 
    -3 => s3Color
 
    => fColor
 
 
 
// Each plot always receives the same EMA value. Using conditional colors rather
 
// than conditional EMA values keeps changes between colors continuous.
 
b3LS = b3Style == "Dashed" ? plot.linestyle_dashed : b3Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
b2LS = b2Style == "Dashed" ? plot.linestyle_dashed : b2Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
b1LS = b1Style == "Dashed" ? plot.linestyle_dashed : b1Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
fLS  = fStyle  == "Dashed" ? plot.linestyle_dashed : fStyle  == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
s1LS = s1Style == "Dashed" ? plot.linestyle_dashed : s1Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
s2LS = s2Style == "Dashed" ? plot.linestyle_dashed : s2Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
s3LS = s3Style == "Dashed" ? plot.linestyle_dashed : s3Style == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
 
 
 
plot(showEMA ? emaValue : na, title="EMA — Strongest Bullish", color=state ==  3 ? b3Color : na, linewidth=b3Width, style=plot.style_line, linestyle=b3LS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Strong Bullish",   color=state ==  2 ? b2Color : na, linewidth=b2Width, style=plot.style_line, linestyle=b2LS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Weak Bullish",     color=state ==  1 ? b1Color : na, linewidth=b1Width, style=plot.style_line, linestyle=b1LS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Neutral",          color=state ==  0 ? fColor  : na, linewidth=fWidth,  style=plot.style_line, linestyle=fLS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Weak Bearish",     color=state == -1 ? s1Color : na, linewidth=s1Width, style=plot.style_line, linestyle=s1LS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Strong Bearish",   color=state == -2 ? s2Color : na, linewidth=s2Width, style=plot.style_line, linestyle=s2LS, force_overlay=true)
 
plot(showEMA ? emaValue : na, title="EMA — Strongest Bearish",color=state == -3 ? s3Color : na, linewidth=s3Width, style=plot.style_line, linestyle=s3LS, force_overlay=true)
 
 
 
// ─────────────────────────────────────────────────────────────────────────────
 
// QUALIFIED DIRECTION / OPTIONAL ENTRY-STYLE SIGNALS
 
// ─────────────────────────────────────────────────────────────────────────────
 
int minLevel = minimumStrength == "Strongest Only" ? 3 : minimumStrength == "Strong+" ? 2 : 1
 
bool bullishPriceOK = priceSideFilter == "Off" or (priceSideFilter == "Close on Correct Side" ? close > emaValue : math.min(open, close) > emaValue)
 
bool bearishPriceOK = priceSideFilter == "Off" or (priceSideFilter == "Close on Correct Side" ? close < emaValue : math.max(open, close) < emaValue)
 
bool bullishQualified = state >= minLevel and bullishPriceOK
 
bool bearishQualified = state <= -minLevel and bearishPriceOK
 
 
 
// A qualifying run is based on all bars meeting the selected filter.
 
var int bullRun = 0
 
var int bearRun = 0
 
bullRun := bullishQualified ? nz(bullRun[1], 0) + 1 : 0
 
bearRun := bearishQualified ? nz(bearRun[1], 0) + 1 : 0
 
bool bullStart = barstate.isconfirmed and bullRun == confirmBars
 
bool bearStart = barstate.isconfirmed and bearRun == confirmBars
 
 
 
// A resumption means bullish -> 1..N neutral bars -> bullish, or the reverse.
 
// Use only closed bars for this sequence to avoid intrabar false signals.
 
var int previousNonNeutralDirection = 0
 
var int neutralRun = 0
 
bool bullResume = false
 
bool bearResume = false
 
if barstate.isconfirmed
 
    if state == 0
 
        neutralRun += 1
 
    else
 
        bullResume := state > 0 and previousNonNeutralDirection == 1 and neutralRun >= 1 and neutralRun <= maxNeutralPause and bullishQualified
 
        bearResume := state < 0 and previousNonNeutralDirection == -1 and neutralRun >= 1 and neutralRun <= maxNeutralPause and bearishQualified
 
        previousNonNeutralDirection := state > 0 ? 1 : -1
 
        neutralRun := 0
 
 
 
plotshape(showQualificationDots and bullStart, title="New Qualified Bullish Slope", style=shape.circle, location=location.belowbar, color=b2Color, size=size.tiny, force_overlay=true)
 
plotshape(showQualificationDots and bearStart, title="New Qualified Bearish Slope", style=shape.circle, location=location.abovebar, color=s2Color, size=size.tiny, force_overlay=true)
 
plotshape(showResumeDots and bullResume, title="Bullish Trend Resumption", style=shape.triangleup, location=location.belowbar, color=b3Color, size=size.tiny, force_overlay=true)
 
plotshape(showResumeDots and bearResume, title="Bearish Trend Resumption", style=shape.triangledown, location=location.abovebar, color=s3Color, size=size.tiny, force_overlay=true)
 
 
 
alertcondition(bullStart, title="ZACS EMA — Bullish Slope Qualified", message="ZACS EMA: Bullish slope qualification confirmed on {{ticker}} ({{interval}}).")
 
alertcondition(bearStart, title="ZACS EMA — Bearish Slope Qualified", message="ZACS EMA: Bearish slope qualification confirmed on {{ticker}} ({{interval}}).")
 
alertcondition(bullResume, title="ZACS EMA — Bullish Neutral-Pause Resumption", message="ZACS EMA: Bullish trend resumed after neutral pause on {{ticker}} ({{interval}}).")
 
alertcondition(bearResume, title="ZACS EMA — Bearish Neutral-Pause Resumption", message="ZACS EMA: Bearish trend resumed after neutral pause on {{ticker}} ({{interval}}).")
 
 
 
// Readouts for TradingView's Data Window. All units reflect our newer formula.
 
 
plot(slopeATR, title="Slope (EMA Change / ATR) [Data Window]", display=display.data_window, force_overlay=true)
 
plot(state, title="Slope State (+3 to -3) [Data Window]", display=display.data_window, force_overlay=true)
 
 
 
 
 
// Optional compact dashboard; does not alter any line or alert logic.
 
var table dash = table.new(position.top_right, 2, 4, border_width=1, force_overlay=true)
 
if showDashboard and barstate.islast
 
    string stateLabel = switch state
 
        3  => "Strongest bullish"
 
        2  => "Strong bullish"
 
        1  => "Weak bullish"
 
        -1 => "Weak bearish"
 
        -2 => "Strong bearish"
 
        -3 => "Strongest bearish"
 
        => "Neutral"
 
    string qualifiedLabel = bullishQualified ? "BULL" : bearishQualified ? "BEAR" : "NONE"
 
    table.cell(dash, 0, 0, "ZACS EMA", bgcolor=color.new(color.black, 15), text_color=color.white)
 
    table.cell(dash, 1, 0, str.tostring(emaLength), bgcolor=color.new(color.black, 15), text_color=color.white)
 
    table.cell(dash, 0, 1, "Slope state", text_color=color.white, bgcolor=color.new(color.black, 45))
 
    table.cell(dash, 1, 1, stateLabel, text_color=stateColor, bgcolor=color.new(color.black, 45))
 
    table.cell(dash, 0, 2, "Slope / ATR", text_color=color.white, bgcolor=color.new(color.black, 45))
 
    table.cell(dash, 1, 2, na(slopeATR) ? "n/a" : str.tostring(slopeATR, "#.####"), text_color=color.white, bgcolor=color.new(color.black, 45))
 
    table.cell(dash, 0, 3, "Filter passed", text_color=color.white, bgcolor=color.new(color.black, 45))
 
    table.cell(dash, 1, 3, qualifiedLabel, text_color=bullishQualified ? b2Color : bearishQualified ? s2Color : color.gray, bgcolor=color.new(color.black, 45))
 
 
// MODULE D — CHOCH/BOS and confirmed HTF EQ swing zones
 
// Historical buffer needed for close-through scans and pivot anchor verification.
 
max_bars_back(close, 5000)
 
max_bars_back(high, 5000)
 
max_bars_back(low, 5000)
 
max_bars_back(time, 5000)
 
max_bars_back(time_close, 5000)
 
 
 
//==============================================================
 
// INPUTS — SMC structure display & candle colors
 
//==============================================================
 
groupSMC        = "SMC Structure (Internal & Swing)"
 
showInternal    = input.bool(false,  "Show Internal Structure (dotted)", group=groupSMC)
 
showSwing       = input.bool(false, "Show Swing Structure (solid)",     group=groupSMC)
 
hideInternalVis = input.bool(false, "Hide Internal Lines & Labels",     group=groupSMC)
 
hideSwingVis    = input.bool(false, "Hide Swing Lines & Labels",        group=groupSMC)
 
internalLen     = input.int(3,   "Internal size", minval=3,  maxval=100, group=groupSMC, inline="il")
 
swingLen        = input.int(10,  "Swing size",    minval=10, maxval=500, group=groupSMC, inline="sl")
 
colSMCBull      = input.color(color.rgb(0, 230, 118), "Bull", group=groupSMC, inline="c")
 
colSMCBear      = input.color(color.rgb(242, 54, 69),  "Bear", group=groupSMC, inline="c")
 
groupSwingPts       = "Swing Point Labels"
 
showSwingPointLabs  = input.bool(true, "Show Swing Point Labels (HH/HL/LH/LL)", group=groupSwingPts)
 
swingPointLabelCol  = input.color(color.rgb(0, 188, 212), "Label Color", group=groupSwingPts)
 
groupInternalPts        = "Internal Pivot Labels"
 
showInternalPivotLabs  = input.bool(false, "Show Internal Pivot Labels (I HH/I HL/I LH/I LL)", group=groupInternalPts)
 
internalPivotLabelCol  = input.color(color.rgb(253, 216, 53), "Label Color", group=groupInternalPts)
 
groupSMCStyle   = "SMC Candle Colors"
 
swingColorOn    = input.bool(false, "Color candles by SWING trend (overrides internal)", group=groupSMCStyle)
 
internalColorOn = input.bool(true,  "Color candles by INTERNAL trend",                   group=groupSMCStyle)
 
useConfColoring = input.bool(false, "Color candles by SWING & INTERNAL Confluence", group=groupSMCStyle)
 
confLongColor   = input.color(color.rgb(41, 98, 255), "Confluence Long Color (Both Bull)",   group=groupSMCStyle)
 
confShortColor  = input.color(color.rgb(255, 152, 0), "Confluence Short Color (Both Bear)",  group=groupSMCStyle)
 
confNoneColor   = input.color(color.rgb(156, 39, 176), "No Confluence Color (Disagreement)",  group=groupSMCStyle)
 
//==============================================================
 
// INPUTS — CHOCH/BOS Label Overlap Fix
 
//==============================================================
 
groupLabelFix = "CHoCH/BOS Label Overlap Fix"
 
staggerStructureLabels = input.bool(true, "Auto-Stagger CHoCH/BOS Labels", group=groupLabelFix)
 
labelOffsetAtrLen      = input.int(14, "Label Offset ATR Length", minval=1, group=groupLabelFix)
 
internalLabelOffsetAtr = input.float(0.10, "Internal Label Vertical Offset ATR", minval=0.0, step=0.01, group=groupLabelFix)
 
swingLabelOffsetAtr    = input.float(0.25, "Swing Label Vertical Offset ATR",    minval=0.0, step=0.01, group=groupLabelFix)
 
internalLabelXOffset   = input.int(-2, "Internal Label Horizontal Offset Bars", group=groupLabelFix)
 
swingLabelXOffset      = input.int(2,  "Swing Label Horizontal Offset Bars",    group=groupLabelFix)
 
showStructurePrefix    = input.bool(true, "Prefix Labels With I/S", group=groupLabelFix)
 
//==============================================================
 
// INPUTS - EQUAL / NEAR-EQUAL SWING PIVOT ZONES
 
//==============================================================
 
groupEqual = "Equal Swing Zone Detection & Management"
 
showEqualHighZones = input.bool(false, "Also show CHART-TF HIGH zones", group=groupEqual)
 
showEqualLowZones  = input.bool(false, "Also show CHART-TF LOW zones", group=groupEqual)
 
equalAtrLen        = input.int(14, "ATR length for zone detection", minval=1, group=groupEqual)
 
equalToleranceATR  = input.float(0.75, "Max high/low difference (ATR)", minval=0.05, step=0.05, group=groupEqual, tooltip="Two or more confirmed SWING highs (or lows) count as near-equal when their entire price spread is no larger than this many ATRs.")
 
equalPaddingATR    = input.float(0.10, "Zone padding above and below (ATR)", minval=0, step=0.05, group=groupEqual)
 
equalMaxGap        = input.int(240, "Max bars between matching swing points", minval=2, maxval=2000, group=groupEqual)
 
shadeAfterSecondConfirm = input.bool(true, "Shade zones only AFTER second swing confirmation", group=groupEqual,
 
     tooltip="ON (realistic history): only shade the part of an EQ zone that could exist AFTER its second matching swing is confirmed. HTF zones begin on the first available lower-timeframe bar after HTF confirmation; chart-TF zones begin at their confirmation candle's close. OFF restores the original back-painted zone from the first swing pivot. Does not change swing detection or pivot verification.")
 
equalExtend        = input.bool(true, "Extend zones right after last pivot", group=groupEqual, tooltip="ON projects confirmed zones forward for lower-timeframe trading. OFF retains pivot-bounded zones in historical mode, or a minimal confirmation-time segment in realistic mode.")
 
equalStopOnBreak   = input.bool(true, "Stop extended zone on close-through", group=groupEqual, tooltip="Only applies when Extend is ON. Resistance stops on a close ABOVE its top, support on a close BELOW its bottom. Wicks are okay. Includes close-throughs during swing confirmation, before a zone first becomes visible.")
 
mtfBreakSource    = input.string("Chart", "MTF invalidation candle closes", options=["Chart", "Source HTF"], group=groupEqual, tooltip="Chart: inspect every confirmed trading-chart close. Source HTF: inspect only confirmed source-HTF closes.")
 
mtfBreakRule      = input.string("Either direction through full zone", "MTF zone close-through rule", options=["Either direction through full zone", "Original HIGH above / LOW below"], group=groupEqual, tooltip="DEFAULT: a zone expires after a confirmed close traverses its entire width in either direction, using the last confirmed outside-side (closes within the band do not reset it). ORIGINAL: EQH breaks only above, EQL only below.")
 
mtfMarkBreak      = input.bool(false, "Mark invalidated MTF zone endpoints (X)", group=groupEqual, tooltip="Shows an X at the frozen right endpoint of MTF zones to help audit their historical and live invalidation. OFF by default.")
 
mtfVerifyAnchors  = input.bool(true, "Verify BOTH swing pivot wicks on chart", group=groupEqual, tooltip="ON (recommended): an HTF zone is drawn only when the source timeframe's first and latest pivot candles can be located on the chart and their actual wick extremes fall inside its price band. Prevents unanchored/floating boxes. Older clusters outside the available 4999 chart-bar lookback are skipped.")
 
mtfShowAnchorDots = input.bool(false, "Show verified MTF swing touch dots", group=groupEqual, tooltip="Adds small dots at both pivot candle wicks when a new zone passes the chart-based anchor verification. Useful when auditing the indicator.")
 
equalMaxZones      = input.int(10, "Max displayed zones per side", minval=1, maxval=100, group=groupEqual)
 
equalHighColor     = input.color(color.new(color.rgb(53, 100, 244), 80), "High zone fill", group=groupEqual)
 
equalLowColor      = input.color(color.new(color.rgb(53, 100, 244), 80), "Low zone fill", group=groupEqual)
 
 
 
//==============================================================
 
// THREE INDEPENDENT HIGHER-TIMEFRAME SOURCES
 
// Each source uses the ORIGINAL swing-leg pivot detector in its HTF.
 
// Swing size is measured in the selected SOURCE timeframe bars.
 
//==============================================================
 
groupHTF = "MTF Equal Swing Zones - Global"
 
showHTFHighs = input.bool(true, "Show HTF equal HIGH zones", group=groupHTF)
 
showHTFLows  = input.bool(true, "Show HTF equal LOW zones", group=groupHTF)
 
showHTFText  = input.bool(true, "Show TF and EQH/EQL text inside boxes", group=groupHTF)
 
 
 
groupHTF1 = "MTF Source 1 (default 15m)"
 
htf1On    = input.bool(true, "Enabled", group=groupHTF1)
 
htf1TF    = input.timeframe("15", "Zone timeframe", group=groupHTF1)
 
htf1Swing = input.int(3, "Swing size (source bars)", minval=3, maxval=500, group=groupHTF1)
 
htf1Col   = input.color(color.new(color.rgb(45, 110, 245), 84), "Zone color", group=groupHTF1)
 
 
 
groupHTF2 = "MTF Source 2 (default 30m)"
 
htf2On    = input.bool(true, "Enabled", group=groupHTF2)
 
htf2TF    = input.timeframe("30", "Zone timeframe", group=groupHTF2)
 
htf2Swing = input.int(3, "Swing size (source bars)", minval=3, maxval=500, group=groupHTF2)
 
htf2Col   = input.color(color.new(color.rgb(150, 82, 217), 84), "Zone color", group=groupHTF2)
 
 
 
groupHTF3 = "MTF Source 3 (default 1H)"
 
htf3On    = input.bool(true, "Enabled", group=groupHTF3)
 
htf3TF    = input.timeframe("60", "Zone timeframe", group=groupHTF3)
 
htf3Swing = input.int(3, "Swing size (source bars)", minval=3, maxval=500, group=groupHTF3)
 
htf3Col   = input.color(color.new(color.rgb(244, 151, 46), 84), "Zone color", group=groupHTF3)
 
 
 
// Only higher-timeframe requests are supported by this version.
 
if barstate.isfirst
 
    float chartSec = timeframe.in_seconds(timeframe.period)
 
    if (htf1On and timeframe.in_seconds(htf1TF) <= chartSec) or (htf2On and timeframe.in_seconds(htf2TF) <= chartSec) or (htf3On and timeframe.in_seconds(htf3TF) <= chartSec)
 
        runtime.error("Each enabled zone timeframe must be HIGHER than the chart timeframe. Default 15/30/60 works on 1m, 3m and 5m charts.")
 
 
 
//==============================================================
 
// CONSTANTS
 
//==============================================================
 
BULLISH = +1
 
BEARISH = -1
 
//==============================================================
 
// TYPES
 
//==============================================================
 
type pivot
 
    float currentLevel
 
    float lastLevel
 
    bool  crossed
 
    int   barIndex
 
type trend
 
    int bias
 
type equalSwingZone
 
    box shape
 
    float coreTop
 
    float coreBottom
 
    int lastTouchBar
 
    bool active
 
    int firstPivotBar
 
 
 
//==============================================================
 
// STATE
 
//==============================================================
 
var pivot swingHigh     = pivot.new(na, na, false, na)
 
var pivot swingLow      = pivot.new(na, na, false, na)
 
var pivot internalHigh  = pivot.new(na, na, false, na)
 
var pivot internalLow   = pivot.new(na, na, false, na)
 
var trend swingTrend    = trend.new(0)
 
var trend internalTrend = trend.new(0)
 
//==============================================================
 
// EQUAL SWING ZONES - use the SAME confirmed pivots as the labels
 
//==============================================================
 
var array<float> equalHighLevels = array.new<float>()
 
var array<int> equalHighBars = array.new<int>()
 
var array<float> equalLowLevels = array.new<float>()
 
var array<int> equalLowBars = array.new<int>()
 
var array<equalSwingZone> equalHighZones = array.new<equalSwingZone>()
 
var array<equalSwingZone> equalLowZones = array.new<equalSwingZone>()
 
 
 
equalATR = ta.atr(equalAtrLen)
 
 
 
// A new confirmed swing can (1) join an earlier zone, (2) match an
 
// earlier same-side swing and create a zone, or (3) stay unpaired.
 
// The drawing begins at the original swing's bar and ends at the latest
 
// matching swing's bar. Detection itself occurs ONLY upon confirmation.
 
// Catch historical close-throughs since the first matched swing pivot.
 
// Scan in time order and return the first confirmed breach bar.
 
f_chart_past_break(int fromPivotBar, float top, float bottom, bool isHigh) =>
 
    int firstBreakBar = na
 
    if equalExtend and equalStopOnBreak and barstate.isconfirmed
 
        int maxAge = math.min(4999, math.max(0, bar_index - fromPivotBar))
 
        for age = maxAge to 0
 
            if not na(close[age]) and (isHigh ? close[age] > top : close[age] < bottom)
 
                firstBreakBar := bar_index - age
 
                break
 
    firstBreakBar
 
 
 
f_registerEqualSwing(float newPrice, int newBar, float pivotATR, bool isHigh, array<float> levels, array<int> bars, array<equalSwingZone> zones) =>
 
    float tolerance = math.max(syminfo.mintick, pivotATR * equalToleranceATR)
 
    float padding = pivotATR * equalPaddingATR
 
    int matchZoneIndex = na
 
    float bestDistance = 1e20
 
 
 
    // Try an existing cluster first, allowing a 3rd, 4th, ... touch.
 
    if array.size(zones) > 0
 
        for zIndex = 0 to array.size(zones) - 1
 
            equalSwingZone z = array.get(zones, zIndex)
 
            float nextTop = math.max(z.coreTop, newPrice)
 
            float nextBottom = math.min(z.coreBottom, newPrice)
 
            float center = (z.coreTop + z.coreBottom) / 2.0
 
            float distance = math.abs(newPrice - center)
 
            if z.active and newBar > z.lastTouchBar and newBar - z.lastTouchBar <= equalMaxGap and nextTop - nextBottom <= tolerance and distance < bestDistance
 
                matchZoneIndex := zIndex
 
                bestDistance := distance
 
 
 
    if not na(matchZoneIndex)
 
        equalSwingZone z = array.get(zones, matchZoneIndex)
 
        z.coreTop := math.max(z.coreTop, newPrice)
 
        z.coreBottom := math.min(z.coreBottom, newPrice)
 
        z.lastTouchBar := newBar
 
        box.set_top(z.shape, z.coreTop + padding)
 
        box.set_bottom(z.shape, z.coreBottom - padding)
 
        if not equalExtend
 
            // The original pivot time may precede the confirmation-time left edge.
 
            box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(newBar, box.get_left(z.shape) + 1) : newBar)
 
        else
 
            // Keep the true first-pivot date for historical validation, even
 
            // though the visual left edge may now be later.
 
            int priorBreak = f_chart_past_break(z.firstPivotBar, box.get_top(z.shape), box.get_bottom(z.shape), isHigh)
 
            if not na(priorBreak)
 
                box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(priorBreak, box.get_left(z.shape)) : priorBreak)
 
                z.active := false
 
    else
 
        // No existing zone: locate the nearest eligible earlier swing.
 
        int matchPivotIndex = na
 
        float nearest = 1e20
 
        if array.size(levels) > 0
 
            for pIndex = 0 to array.size(levels) - 1
 
                float oldPrice = array.get(levels, pIndex)
 
                int oldBar = array.get(bars, pIndex)
 
                float distance = math.abs(newPrice - oldPrice)
 
                if newBar > oldBar and newBar - oldBar <= equalMaxGap and distance <= tolerance and distance < nearest
 
                    matchPivotIndex := pIndex
 
                    nearest := distance
 
 
 
        if not na(matchPivotIndex)
 
            float oldPrice = array.get(levels, matchPivotIndex)
 
            int oldBar = array.get(bars, matchPivotIndex)
 
            float coreTop = math.max(oldPrice, newPrice)
 
            float coreBottom = math.min(oldPrice, newPrice)
 
            color zoneColor = isHigh ? equalHighColor : equalLowColor
 
            float zoneTop = coreTop + padding
 
            float zoneBottom = coreBottom - padding
 
            int priorBreak = f_chart_past_break(oldBar, zoneTop, zoneBottom, isHigh)
 
            // The second chart-TF swing is only known NOW (at this bar's close).
 
            // A zone already broken by then was never usable in live trading.
 
            bool alreadyExpired = shadeAfterSecondConfirm and not na(priorBreak) and priorBreak <= bar_index
 
            if not alreadyExpired
 
                int leftDrawBar = shadeAfterSecondConfirm ? bar_index : oldBar
 
                int rightDrawBar = shadeAfterSecondConfirm ? bar_index + 1 : newBar
 
                box newBox = box.new(left=leftDrawBar, top=zoneTop, right=rightDrawBar, bottom=zoneBottom,
 
                     xloc=xloc.bar_index, bgcolor=zoneColor, border_color=color.new(zoneColor, 40), border_width=1, force_overlay=true)
 
                equalSwingZone newZone = equalSwingZone.new(newBox, coreTop, coreBottom, newBar, true, oldBar)
 
                if not na(priorBreak)
 
                    box.set_right(newBox, priorBreak)
 
                    newZone.active := false
 
                array.push(zones, newZone)
 
                if array.size(zones) > equalMaxZones
 
                    equalSwingZone oldest = array.shift(zones)
 
                    box.delete(oldest.shape)
 
 
 
    // Keep prior SWING pivots available for subsequent matches.
 
    array.push(levels, newPrice)
 
    array.push(bars, newBar)
 
    if array.size(levels) > 300
 
        array.shift(levels)
 
        array.shift(bars)
 
 
 
// Optional: extend a still-valid box until a candle CLOSES beyond it.
 
f_updateEqualExtensions(array<equalSwingZone> zones, bool isHigh) =>
 
    if equalExtend and array.size(zones) > 0
 
        for zIndex = 0 to array.size(zones) - 1
 
            equalSwingZone z = array.get(zones, zIndex)
 
            if z.active
 
                // Do not shrink the realistic one-candle confirmation span
 
                // back to zero width on the same bar as zone creation.
 
                box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(bar_index, box.get_left(z.shape) + 1) : bar_index)
 
                if equalStopOnBreak and barstate.isconfirmed
 
                    bool broke = isHigh ? close > box.get_top(z.shape) : close < box.get_bottom(z.shape)
 
                    if broke
 
                        z.active := false
 
 
 
//==============================================================
 
// INTERNAL — strict fractal pivots (uses internalLen)
 
//==============================================================
 
updateInternalFromFractals() =>
 
    ph = ta.pivothigh(high, internalLen, internalLen)
 
    pl = ta.pivotlow(low, internalLen, internalLen)
 
    if not na(ph)
 
        internalHigh.lastLevel    := internalHigh.currentLevel
 
        internalHigh.currentLevel := ph
 
        internalHigh.crossed      := false
 
        internalHigh.barIndex     := bar_index - internalLen
 
        if showInternalPivotLabs and not na(internalHigh.lastLevel)
 
            internalHighTag = internalHigh.currentLevel > internalHigh.lastLevel ? "I HH" : "I LH"
 
            label.new(internalHigh.barIndex, internalHigh.currentLevel, internalHighTag, xloc=xloc.bar_index, style=label.style_label_down, textcolor=internalPivotLabelCol, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
    if not na(pl)
 
        internalLow.lastLevel    := internalLow.currentLevel
 
        internalLow.currentLevel := pl
 
        internalLow.crossed      := false
 
        internalLow.barIndex     := bar_index - internalLen
 
        if showInternalPivotLabs and not na(internalLow.lastLevel)
 
            internalLowTag = internalLow.currentLevel < internalLow.lastLevel ? "I LL" : "I HL"
 
            label.new(internalLow.barIndex, internalLow.currentLevel, internalLowTag, xloc=xloc.bar_index, style=label.style_label_up, textcolor=internalPivotLabelCol, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
updateInternalFromFractals()
 
//==============================================================
 
// SWING — leg-style turns (uses swingLen)
 
//==============================================================
 
var int swingLeg = 0
 
calcSwingLeg(int size, int prevLeg) =>
 
    newLegHigh = high[size] > ta.highest(high, size)
 
    newLegLow  = low[size]  < ta.lowest(low, size)
 
    newLegHigh ? 0 : newLegLow ? 1 : prevLeg
 
swingPrev   = nz(swingLeg[1], 0)
 
swingNew    = calcSwingLeg(swingLen, swingPrev)
 
legChanged  = swingNew != swingPrev
 
if legChanged
 
    if swingNew == 1
 
        swingLow.lastLevel    := swingLow.currentLevel
 
        swingLow.currentLevel := low[swingLen]
 
        swingLow.crossed      := false
 
        swingLow.barIndex     := bar_index - swingLen
 
        if showSwingPointLabs and not na(swingLow.lastLevel)
 
            swingLowTag = swingLow.currentLevel < swingLow.lastLevel ? "LL" : "HL"
 
            label.new(swingLow.barIndex, swingLow.currentLevel, swingLowTag, xloc=xloc.bar_index, style=label.style_label_up, textcolor=swingPointLabelCol, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
        if showEqualLowZones and barstate.isconfirmed and not na(equalATR[swingLen])
 
            f_registerEqualSwing(swingLow.currentLevel, swingLow.barIndex, equalATR[swingLen], false, equalLowLevels, equalLowBars, equalLowZones)
 
    else
 
        swingHigh.lastLevel    := swingHigh.currentLevel
 
        swingHigh.currentLevel := high[swingLen]
 
        swingHigh.crossed      := false
 
        swingHigh.barIndex     := bar_index - swingLen
 
        if showSwingPointLabs and not na(swingHigh.lastLevel)
 
            swingHighTag = swingHigh.currentLevel > swingHigh.lastLevel ? "HH" : "LH"
 
            label.new(swingHigh.barIndex, swingHigh.currentLevel, swingHighTag, xloc=xloc.bar_index, style=label.style_label_down, textcolor=swingPointLabelCol, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
        if showEqualHighZones and barstate.isconfirmed and not na(equalATR[swingLen])
 
            f_registerEqualSwing(swingHigh.currentLevel, swingHigh.barIndex, equalATR[swingLen], true, equalHighLevels, equalHighBars, equalHighZones)
 
swingLeg := swingNew
 
// Update confirmed zones once per candle; boxes end at the last touch
 
// unless the optional rightward extension is enabled.
 
f_updateEqualExtensions(equalHighZones, true)
 
f_updateEqualExtensions(equalLowZones, false)
 
//==============================================================
 
// DRAW HELPERS
 
//==============================================================
 
labelOffsetAtr = ta.atr(labelOffsetAtrLen)
 
f_draw_structure(int xLeft, int xRight, float y, string tag, color col, bool internal, bool bullish) =>
 
    line.new(xLeft, y, xRight, y, xloc=xloc.bar_index, color=col, style=internal ? line.style_dotted : line.style_solid, force_overlay=true)
 
    baseX = math.round((xLeft + xRight) * 0.5)
 
    xOffset = staggerStructureLabels ? (internal ? internalLabelXOffset : swingLabelXOffset) : 0
 
    yOffset = staggerStructureLabels ? labelOffsetAtr * (internal ? internalLabelOffsetAtr : swingLabelOffsetAtr) : 0.0
 
    labelX = baseX + xOffset
 
    labelY = bullish ? y + yOffset : y - yOffset
 
    labelStyle = bullish ? label.style_label_down : label.style_label_up
 
    labelPrefix = showStructurePrefix ? (internal ? "I " : "S ") : ""
 
    labelText   = labelPrefix + tag
 
    label.new(labelX, labelY, labelText, xloc=xloc.bar_index, style=labelStyle, textcolor=col, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
//==============================================================
 
// VISUAL TOGGLES
 
// NOTE:
 
// Structure logic now always updates so candle coloring works even
 
// when internal/swing lines and labels are hidden.
 
//==============================================================
 
showInternalDrawings = showInternal and not hideInternalVis
 
showSwingDrawings    = showSwing and not hideSwingVis
 
//==============================================================
 
// DISPLAY + BIAS UPDATES — Internal
 
//==============================================================
 
internalCrossUp = ta.crossover(close, internalHigh.currentLevel)
 
internalCrossDn = ta.crossunder(close, internalLow.currentLevel)
 
if not na(internalHigh.currentLevel) and not internalHigh.crossed and internalCrossUp
 
    tagIntH = internalTrend.bias == BEARISH ? "CHoCH" : "BOS"
 
    if showInternalDrawings
 
        f_draw_structure(internalHigh.barIndex, bar_index, internalHigh.currentLevel, tagIntH, colSMCBull, true, true)
 
    internalHigh.crossed := true
 
    internalTrend.bias := BULLISH
 
if not na(internalLow.currentLevel) and not internalLow.crossed and internalCrossDn
 
    tagIntL = internalTrend.bias == BULLISH ? "CHoCH" : "BOS"
 
    if showInternalDrawings
 
        f_draw_structure(internalLow.barIndex, bar_index, internalLow.currentLevel, tagIntL, colSMCBear, true, false)
 
    internalLow.crossed := true
 
    internalTrend.bias := BEARISH
 
//==============================================================
 
// DISPLAY + BIAS UPDATES — Swing
 
//==============================================================
 
swingCrossUp = ta.crossover(close, swingHigh.currentLevel)
 
swingCrossDn = ta.crossunder(close, swingLow.currentLevel)
 
if not na(swingHigh.currentLevel) and not swingHigh.crossed and swingCrossUp
 
    tagSwH = swingTrend.bias == BEARISH ? "CHoCH" : "BOS"
 
    if showSwingDrawings
 
        f_draw_structure(swingHigh.barIndex, bar_index, swingHigh.currentLevel, tagSwH, colSMCBull, false, true)
 
    swingHigh.crossed := true
 
    swingTrend.bias := BULLISH
 
if not na(swingLow.currentLevel) and not swingLow.crossed and swingCrossDn
 
    tagSwL = swingTrend.bias == BULLISH ? "CHoCH" : "BOS"
 
    if showSwingDrawings
 
        f_draw_structure(swingLow.barIndex, bar_index, swingLow.currentLevel, tagSwL, colSMCBear, false, false)
 
    swingLow.crossed := true
 
    swingTrend.bias := BEARISH
 
//==============================================================
 
// CANDLE COLORING
 
//==============================================================
 
var color smcBarCol = na
 
smcBarCol := na
 
if useConfColoring
 
    conflLong  = swingTrend.bias == BULLISH and internalTrend.bias == BULLISH
 
    conflShort = swingTrend.bias == BEARISH and internalTrend.bias == BEARISH
 
    smcBarCol  := conflLong ? confLongColor : conflShort ? confShortColor : confNoneColor
 
else
 
    if swingColorOn and swingTrend.bias != 0
 
        smcBarCol := swingTrend.bias == BULLISH ? colSMCBull : colSMCBear
 
    else if internalColorOn and internalTrend.bias != 0
 
        smcBarCol := internalTrend.bias == BULLISH ? colSMCBull : colSMCBear
 
// Final combined barcolor() is called once after all modules.
 
 
 
 
 
//==============================================================
 
// MTF ZONE ENGINE
 
//==============================================================
 
// Events are calculated in the real source TF, using the same
 
// calcSwingLeg() algorithm as the chart's native swing pivots.
 
// We return only the previous completed HTF bar's event via [1]
 
// + lookahead_on, to prevent HTF lookahead / developing-bar repaint.
 
// Times use xloc.bar_time; HTF bar indexes NEVER mix with chart bars.
 
//==============================================================
 
 
 
// A full traversal needs the last confirmed outside side, not just
 
// the previous candle: prices can spend multiple closes INSIDE the box.
 
// -1 = most recent close below the box; +1 = above; 0 = inside.
 
f_mtf_zone_side(float c, float top, float bottom) =>
 
    int side = na(c) ? 0 : c > top ? 1 : c < bottom ? -1 : 0
 
    side
 
 
 
f_mtf_zone_broken(int side, bool isHigh, int priorOutsideSide) =>
 
    bool broken = mtfBreakRule == "Original HIGH above / LOW below" ? (isHigh ? side == 1 : side == -1) : (side != 0 and side != priorOutsideSide)
 
    broken
 
 
 
f_mtf_mark_break(int breakTime, float top, float bottom, bool isHigh, color col) =>
 
    bool marked = false
 
    if mtfMarkBreak and not na(breakTime)
 
        label.new(x=breakTime, y=isHigh ? top : bottom, text="×", xloc=xloc.bar_time, style=label.style_label_center, color=color.new(col, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
 
        marked := true
 
    marked
 
 
 
// One HTF-side state group uses arrays to accumulate pivots & zones.
 
// A zone is created by two near-equal confirmed same-side swings.
 
// Additional matching swings update the SAME zone identifier (left time).
 
f_htf_register(float price, int pTime, int pBar, float pivotATR,
 
      array<float> levels, array<int> pTimes, array<int> pBars, array<bool> paired,
 
      array<int> zIDs, array<float> zHighs, array<float> zLows,
 
      array<int> zLastBars, array<bool> zAlive, array<int> zOutside) =>
 
    int eID = na
 
    float eTop = na
 
    float eBottom = na
 
    int eRight = na
 
    float tolerance = math.max(syminfo.mintick, pivotATR * equalToleranceATR)
 
    float pad = pivotATR * equalPaddingATR
 
    int matchZone = na
 
    float bestZoneDist = 1e20
 
 
 
    if array.size(zIDs) > 0
 
        for i = 0 to array.size(zIDs) - 1
 
            float zTop = array.get(zHighs, i)
 
            float zBottom = array.get(zLows, i)
 
            float extent = math.max(zTop, price) - math.min(zBottom, price)
 
            float distance = math.abs(price - (zTop + zBottom) * 0.5)
 
            int lastBar = array.get(zLastBars, i)
 
            if array.get(zAlive, i) and pBar > lastBar and pBar - lastBar <= equalMaxGap and extent <= tolerance and distance < bestZoneDist
 
                matchZone := i
 
                bestZoneDist := distance
 
 
 
    bool joinedExisting = not na(matchZone)
 
    bool pairedNow = joinedExisting
 
    if joinedExisting
 
        int i = matchZone
 
        float zTop = math.max(array.get(zHighs, i), price)
 
        float zBottom = math.min(array.get(zLows, i), price)
 
        array.set(zHighs, i, zTop)
 
        array.set(zLows, i, zBottom)
 
        array.set(zLastBars, i, pBar)
 
        eID := array.get(zIDs, i)
 
        eTop := zTop + pad
 
        eBottom := zBottom - pad
 
        eRight := pTime
 
    else
 
        int matchPivot = na
 
        float nearest = 1e20
 
        if array.size(levels) > 0
 
            for i = 0 to array.size(levels) - 1
 
                float prevPrice = array.get(levels, i)
 
                int prevBar = array.get(pBars, i)
 
                float distance = math.abs(price - prevPrice)
 
                if not array.get(paired, i) and pBar > prevBar and pBar - prevBar <= equalMaxGap and distance <= tolerance and distance < nearest
 
                    matchPivot := i
 
                    nearest := distance
 
        if not na(matchPivot)
 
            pairedNow := true
 
            array.set(paired, matchPivot, true)
 
            float oldPrice = array.get(levels, matchPivot)
 
            int originalTime = array.get(pTimes, matchPivot)
 
            float newTop = math.max(oldPrice, price)
 
            float newBottom = math.min(oldPrice, price)
 
            array.push(zIDs, originalTime)
 
            array.push(zHighs, newTop)
 
            array.push(zLows, newBottom)
 
            array.push(zLastBars, pBar)
 
            array.push(zAlive, true)
 
            array.push(zOutside, 0)
 
            eID := originalTime
 
            eTop := newTop + pad
 
            eBottom := newBottom - pad
 
            eRight := pTime
 
            // Bound the HTF-side computational state independently.
 
            if array.size(zIDs) > 80
 
                array.shift(zIDs)
 
                array.shift(zHighs)
 
                array.shift(zLows)
 
                array.shift(zLastBars)
 
                array.shift(zAlive)
 
                array.shift(zOutside)
 
 
 
    array.push(levels, price)
 
    array.push(pTimes, pTime)
 
    array.push(pBars, pBar)
 
    array.push(paired, pairedNow)
 
    if array.size(levels) > 300
 
        array.shift(levels)
 
        array.shift(pTimes)
 
        array.shift(pBars)
 
        array.shift(paired)
 
    [eID, eTop, eBottom, eRight]
 
 
 
// Source HTF closes also invalidate matching groups in HTF state.
 
// This keeps closed-through historical groups from attracting new pivots.
 
f_htf_break_zones(array<float> tops, array<float> bottoms, array<bool> alive, array<int> outside, bool isHigh, float htfAtr) =>
 
    bool changed = false
 
    if equalExtend and equalStopOnBreak and array.size(alive) > 0
 
        float pad = htfAtr * equalPaddingATR
 
        for i = 0 to array.size(alive) - 1
 
            if array.get(alive, i)
 
                int side = f_mtf_zone_side(close, array.get(tops, i) + pad, array.get(bottoms, i) - pad)
 
                int priorOutside = array.get(outside, i)
 
                if priorOutside == 0
 
                    priorOutside := isHigh ? -1 : 1
 
                if f_mtf_zone_broken(side, isHigh, priorOutside)
 
                    array.set(alive, i, false)
 
                    changed := true
 
                else if side != 0
 
                    array.set(outside, i, side)
 
    changed
 
 
 
// Called when the later equal-swing pivot is confirmed. Find the FIRST
 
// source-timeframe CLOSE beyond the new zone since its first swing pivot.
 
// A zone cannot stay active if it was broken during pivot confirmation.
 
f_htf_past_break(int fromFirstPivotTime, int zoneSwingSize, float top, float bottom, bool isHigh) =>
 
    int firstBreakTime = na
 
    if equalExtend and equalStopOnBreak
 
        int maxAge = math.min(4999, equalMaxGap + zoneSwingSize + 2)
 
        int lastOutside = isHigh ? -1 : 1
 
        for age = maxAge to 0
 
            if not na(time[age]) and time[age] >= fromFirstPivotTime and not na(close[age])
 
                int side = f_mtf_zone_side(close[age], top, bottom)
 
                if f_mtf_zone_broken(side, isHigh, lastOutside)
 
                    firstBreakTime := time_close[age]
 
                    break
 
                if side != 0
 
                    lastOutside := side
 
    firstBreakTime
 
 
 
f_htf_events(int zoneSwingSize) =>
 
    var int leg = 0
 
    var array<float> hiLevels = array.new_float()
 
    var array<int> hiTimes = array.new_int()
 
    var array<int> hiBars = array.new_int()
 
    var array<bool> hiPaired = array.new_bool()
 
    var array<int> hiZoneIDs = array.new_int()
 
    var array<float> hiZoneTops = array.new_float()
 
    var array<float> hiZoneBottoms = array.new_float()
 
    var array<int> hiZoneLast = array.new_int()
 
    var array<bool> hiZoneAlive = array.new_bool()
 
    var array<int> hiZoneOutside = array.new_int()
 
    var array<float> loLevels = array.new_float()
 
    var array<int> loTimes = array.new_int()
 
    var array<int> loBars = array.new_int()
 
    var array<bool> loPaired = array.new_bool()
 
    var array<int> loZoneIDs = array.new_int()
 
    var array<float> loZoneTops = array.new_float()
 
    var array<float> loZoneBottoms = array.new_float()
 
    var array<int> loZoneLast = array.new_int()
 
    var array<bool> loZoneAlive = array.new_bool()
 
    var array<int> loZoneOutside = array.new_int()
 
 
 
    int hID = na
 
    float hTop = na
 
    float hBottom = na
 
    int hRight = na
 
    int hBreakTime = na
 
    int lID = na
 
    float lTop = na
 
    float lBottom = na
 
    int lRight = na
 
    int lBreakTime = na
 
 
 
    // This call runs on EVERY source-TF bar, not each lower chart bar.
 
    float htfAtr = ta.atr(equalAtrLen)
 
    int prevLeg = nz(leg[1], 0)
 
    int nextLeg = calcSwingLeg(zoneSwingSize, prevLeg)
 
    bool changed = nextLeg != prevLeg
 
    if changed and not na(htfAtr[zoneSwingSize])
 
        float pivotAtr = htfAtr[zoneSwingSize]
 
        if nextLeg == 0
 
            [eventID, eventTop, eventBottom, eventRight] = f_htf_register(high[zoneSwingSize], time[zoneSwingSize], bar_index - zoneSwingSize, pivotAtr, hiLevels, hiTimes, hiBars, hiPaired, hiZoneIDs, hiZoneTops, hiZoneBottoms, hiZoneLast, hiZoneAlive, hiZoneOutside)
 
            hID := eventID
 
            hTop := eventTop
 
            hBottom := eventBottom
 
            hRight := eventRight
 
            if not na(eventID)
 
                hBreakTime := f_htf_past_break(eventID, zoneSwingSize, eventTop, eventBottom, true)
 
                if not na(hBreakTime) and array.size(hiZoneIDs) > 0
 
                    for i = 0 to array.size(hiZoneIDs) - 1
 
                        if array.get(hiZoneIDs, i) == eventID
 
                            array.set(hiZoneAlive, i, false)
 
                // If broken before latest matched swing, the two-pivot
 
                // resistance zone never existed as a valid cluster.
 
                if not na(hBreakTime) and hBreakTime <= eventRight
 
                    hID := na
 
                    hTop := na
 
                    hBottom := na
 
                    hRight := na
 
        else
 
            [eventID, eventTop, eventBottom, eventRight] = f_htf_register(low[zoneSwingSize], time[zoneSwingSize], bar_index - zoneSwingSize, pivotAtr, loLevels, loTimes, loBars, loPaired, loZoneIDs, loZoneTops, loZoneBottoms, loZoneLast, loZoneAlive, loZoneOutside)
 
            lID := eventID
 
            lTop := eventTop
 
            lBottom := eventBottom
 
            lRight := eventRight
 
            if not na(eventID)
 
                lBreakTime := f_htf_past_break(eventID, zoneSwingSize, eventTop, eventBottom, false)
 
                if not na(lBreakTime) and array.size(loZoneIDs) > 0
 
                    for i = 0 to array.size(loZoneIDs) - 1
 
                        if array.get(loZoneIDs, i) == eventID
 
                            array.set(loZoneAlive, i, false)
 
                // Never create a support box that was already invalidated
 
                // before its second matching swing low occurred.
 
                if not na(lBreakTime) and lBreakTime <= eventRight
 
                    lID := na
 
                    lTop := na
 
                    lBottom := na
 
                    lRight := na
 
    leg := nextLeg
 
    f_htf_break_zones(hiZoneTops, hiZoneBottoms, hiZoneAlive, hiZoneOutside, true, htfAtr)
 
    f_htf_break_zones(loZoneTops, loZoneBottoms, loZoneAlive, loZoneOutside, false, htfAtr)
 
    [hID, hTop, hBottom, hRight, hBreakTime, lID, lTop, lBottom, lRight, lBreakTime]
 
 
 
// In the context of request.security the outer [1] offsets ALL
 
// output events to the last COMPLETED candle of the requested HTF.
 
f_htf_confirmed(int zoneSwingSize) =>
 
    [hID, hTop, hBottom, hRight, hBreakTime, lID, lTop, lBottom, lRight, lBreakTime] = f_htf_events(zoneSwingSize)
 
    [hID[1], hTop[1], hBottom[1], hRight[1], hBreakTime[1], lID[1], lTop[1], lBottom[1], lRight[1], lBreakTime[1], close[1]]
 
 
 
// Drawing objects exist on the lower chart, one independent group per
 
// selected TF & side. The cluster's earliest swing TIME is its identity.
 
type mtfDrawZone
 
    box shape
 
    int clusterID
 
    bool active
 
    int lastOutsideSide
 
    int invalidationTime
 
 
 
// Chart-timeframe backfill: find the first lower-TF candle that already
 
// CLOSED beyond the zone between its first pivot and HTF confirmation.
 
// The chart audit scans up to 4999 loaded LTF bars. Older anchors may be skipped.
 
f_mtf_past_chart_break(int fromPivotTime, float top, float bottom, bool isHigh) =>
 
    int firstBreakTime = na
 
    if equalExtend and equalStopOnBreak
 
        // Time gaps (weekends/session breaks) are handled by checking actual
 
        // bar timestamps.  The 4999 cap is the TradingView history budget.
 
        int msPerBar = timeframe.in_seconds(timeframe.period) * 1000
 
        int maxAge = math.min(4999, math.min(bar_index, math.max(1, int(math.ceil((time - fromPivotTime) / msPerBar)) + 2)))
 
        int lastOutside = isHigh ? -1 : 1
 
        for age = maxAge to 1
 
            if not na(time[age]) and time[age] >= fromPivotTime and not na(close[age])
 
                int side = f_mtf_zone_side(close[age], top, bottom)
 
                if f_mtf_zone_broken(side, isHigh, lastOutside)
 
                    firstBreakTime := time_close[age]
 
                    break
 
                if side != 0
 
                    lastOutside := side
 
        // Guard against a zone born on a close that breaks the boundary.
 
        if na(firstBreakTime) and time >= fromPivotTime and barstate.isconfirmed
 
            int thisSide = f_mtf_zone_side(close, top, bottom)
 
            if f_mtf_zone_broken(thisSide, isHigh, lastOutside)
 
                firstBreakTime := time_close
 
    firstBreakTime
 
 
 
// Cross-check a SOURCE-TF pivot against actual candles on the CHART.
 
// A legitimate HTF high/low must equal the extreme of its constituent
 
// lower-timeframe bars, to within rounding/tick tolerance.
 
// This avoids drawing price zones with timestamps that do not align
 
// with the displayed market data (the "floating zone" problem).
 
// Return na if the pivot source interval is not in loaded chart history.
 
f_mtf_anchor_extreme(int pivotOpenTime, int sourceMs, bool isHigh) =>
 
    float extreme = na
 
    if not na(pivotOpenTime) and sourceMs > 0
 
        for age = 0 to 4999
 
            int t = time[age]
 
            if na(t) or t < pivotOpenTime
 
                break
 
            if t >= pivotOpenTime and t < pivotOpenTime + sourceMs
 
                float v = isHigh ? high[age] : low[age]
 
                extreme := na(extreme) ? v : isHigh ? math.max(extreme, v) : math.min(extreme, v)
 
    extreme
 
 
 
f_mtf_anchor_matches(float extreme, float top, float bottom) =>
 
    float eps = syminfo.mintick * 2.0
 
    bool matches = not na(extreme) and extreme >= bottom - eps and extreme <= top + eps
 
    matches
 
 
 
f_mtf_show_anchors(int leftTime, float leftExtreme, int rightTime, float rightExtreme, color fillColor) =>
 
    bool shown = false
 
    if mtfShowAnchorDots and not na(leftExtreme) and not na(rightExtreme)
 
        label.new(x=leftTime, y=leftExtreme, xloc=xloc.bar_time, text="•", style=label.style_none, textcolor=color.new(fillColor, 0), size=size.small, force_overlay=true)
 
        label.new(x=rightTime, y=rightExtreme, xloc=xloc.bar_time, text="•", style=label.style_none, textcolor=color.new(fillColor, 0), size=size.small, force_overlay=true)
 
        shown := true
 
    shown
 
 
 
// Each drawing helper has a consistent, explicit BOOL return type.
 
// Pine v6 otherwise infers different types from box setters (void)
 
// and state assignments (series bool) in terminal if/else branches.
 
f_mtf_upsert(int clusterID, float top, float bottom, int rightTime, int sourceBreakTime,
 
      int zoneAvailableTime, string tfLabel, int sourceMs, color fillColor, bool isHigh, array<mtfDrawZone> drawings) =>
 
    bool processed = false
 
    if not na(clusterID) and not na(top) and not na(bottom) and not na(rightTime)
 
        int found = na
 
        if array.size(drawings) > 0
 
            for i = 0 to array.size(drawings) - 1
 
                mtfDrawZone candidate = array.get(drawings, i)
 
                if candidate.clusterID == clusterID
 
                    found := i
 
                    break
 
 
 
        // Require the FIRST and LAST confirmed HTF swing wick to
 
        // correspond to actual lower-timeframe candles at these timestamps.
 
        // If chart data is insufficient to check both, conservatively skip.
 
        bool firstOK = true
 
        bool lastOK = true
 
        float firstExtreme = na
 
        float lastExtreme = na
 
        if mtfVerifyAnchors
 
            if na(found)
 
                firstExtreme := f_mtf_anchor_extreme(clusterID, sourceMs, isHigh)
 
                firstOK := f_mtf_anchor_matches(firstExtreme, top, bottom)
 
            lastExtreme := f_mtf_anchor_extreme(rightTime, sourceMs, isHigh)
 
            lastOK := f_mtf_anchor_matches(lastExtreme, top, bottom)
 
 
 
        // A break can happen before the delayed second swing confirmation.
 
        // A zone that closes through BEFORE its second pivot is not a valid
 
        // two-touch zone and MUST NOT be displayed as a floating rectangle.
 
        int caughtBreak = na
 
        if equalExtend and equalStopOnBreak
 
            caughtBreak := mtfBreakSource == "Chart" ? f_mtf_past_chart_break(clusterID, top, bottom, isHigh) : sourceBreakTime
 
            if mtfBreakSource == "Chart" and na(caughtBreak) and not na(sourceBreakTime)
 
                caughtBreak := sourceBreakTime
 
        bool brokenBeforeSecond = not na(caughtBreak) and caughtBreak <= rightTime
 
        // In realistic display mode, do not back-paint a zone that was
 
        // completely invalidated BEFORE traders could know of its second swing.
 
        bool brokenBeforeAvailable = shadeAfterSecondConfirm and not na(caughtBreak) and caughtBreak <= zoneAvailableTime
 
 
 
        if not na(found)
 
            mtfDrawZone z = array.get(drawings, found)
 
            if z.active
 
                // On an attempted third/fourth touch, preserve the original
 
                // zone if it expired before this new matching pivot.
 
                if brokenBeforeSecond
 
                    if not na(caughtBreak)
 
                        box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(caughtBreak, box.get_left(z.shape)) : caughtBreak)
 
                        z.invalidationTime := caughtBreak
 
                        z.active := false
 
                        f_mtf_mark_break(caughtBreak, box.get_top(z.shape), box.get_bottom(z.shape), isHigh, fillColor)
 
                else if lastOK
 
                    box.set_top(z.shape, top)
 
                    box.set_bottom(z.shape, bottom)
 
                    if not equalExtend
 
                        // Later matching pivots can extend this historical
 
                        // zone, but never before its original confirmation.
 
                        int priorRight = box.get_right(z.shape)
 
                        int nextRight = zoneAvailableTime + timeframe.in_seconds(timeframe.period) * 1000
 
                        box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(priorRight, nextRight) : rightTime)
 
                    if equalExtend and equalStopOnBreak and not na(caughtBreak)
 
                        box.set_right(z.shape, shadeAfterSecondConfirm ? math.max(caughtBreak, box.get_left(z.shape)) : caughtBreak)
 
                        z.invalidationTime := caughtBreak
 
                        z.active := false
 
                        f_mtf_mark_break(caughtBreak, top, bottom, isHigh, fillColor)
 
            processed := true
 
        else
 
            // Both anchors must be real AND the second matching pivot must
 
            // have occurred before any full close-through invalidation.
 
            if firstOK and lastOK and not brokenBeforeSecond and not brokenBeforeAvailable
 
                string titleText = showHTFText ? tfLabel + (isHigh ? " EQH" : " EQL") : ""
 
                // Zone becomes known only after the later HTF swing is
 
                // confirmed. request.security's [1] event arrives at the
 
                // first lower-chart candle of the FOLLOWING HTF bar.
 
                int drawLeft = shadeAfterSecondConfirm ? zoneAvailableTime : clusterID
 
                int drawRight = equalExtend ? time : shadeAfterSecondConfirm ? zoneAvailableTime + timeframe.in_seconds(timeframe.period) * 1000 : rightTime
 
                box b = box.new(left=drawLeft, top=top, right=drawRight, bottom=bottom,
 
                      xloc=xloc.bar_time, bgcolor=fillColor, border_color=color.new(fillColor, 24), border_width=1,
 
                      text=titleText, text_color=color.new(color.black, 15), text_size=size.tiny,
 
                      text_halign=text.align_right, text_valign=text.align_center, force_overlay=true)
 
                mtfDrawZone fresh = mtfDrawZone.new(b, clusterID, true, isHigh ? -1 : 1, na)
 
                if equalExtend and equalStopOnBreak and not na(caughtBreak)
 
                    box.set_right(fresh.shape, caughtBreak)
 
                    fresh.invalidationTime := caughtBreak
 
                    fresh.active := false
 
                    f_mtf_mark_break(caughtBreak, top, bottom, isHigh, fillColor)
 
                array.push(drawings, fresh)
 
                if mtfVerifyAnchors
 
                    f_mtf_show_anchors(clusterID, firstExtreme, rightTime, lastExtreme, fillColor)
 
                if array.size(drawings) > equalMaxZones
 
                    mtfDrawZone oldest = array.shift(drawings)
 
                    box.delete(oldest.shape)
 
                processed := true
 
    processed
 
 
 
f_mtf_extend(array<mtfDrawZone> drawings, bool isHigh, bool evaluateBreak, float breakPrice, int stopAt) =>
 
    bool extended = false
 
    if equalExtend and array.size(drawings) > 0
 
        for i = 0 to array.size(drawings) - 1
 
            mtfDrawZone z = array.get(drawings, i)
 
            // Once invalidated, no new candle or repeated HTF event can
 
            // extend its endpoint into the future.
 
            if z.active
 
                box.set_right(z.shape, time_close)
 
                if equalStopOnBreak and evaluateBreak and not na(breakPrice)
 
                    float top = box.get_top(z.shape)
 
                    float bottom = box.get_bottom(z.shape)
 
                    int side = f_mtf_zone_side(breakPrice, top, bottom)
 
                    bool broken = f_mtf_zone_broken(side, isHigh, z.lastOutsideSide)
 
                    if broken
 
                        z.active := false
 
                        z.invalidationTime := stopAt
 
                        box.set_right(z.shape, stopAt)
 
                        f_mtf_mark_break(stopAt, top, bottom, isHigh, color.red)
 
                    else if side != 0
 
                        z.lastOutsideSide := side
 
                extended := true
 
    extended
 
 
 
var array<mtfDrawZone> htf1HiBoxes = array.new<mtfDrawZone>()
 
var array<mtfDrawZone> htf1LoBoxes = array.new<mtfDrawZone>()
 
var array<mtfDrawZone> htf2HiBoxes = array.new<mtfDrawZone>()
 
var array<mtfDrawZone> htf2LoBoxes = array.new<mtfDrawZone>()
 
var array<mtfDrawZone> htf3HiBoxes = array.new<mtfDrawZone>()
 
var array<mtfDrawZone> htf3LoBoxes = array.new<mtfDrawZone>()
 
 
 
// 3 independent non-repainting requests (11 tuple values each).
 
[h1ID, h1Top, h1Bot, h1Right, h1BreakTime, l1ID, l1Top, l1Bot, l1Right, l1BreakTime, htf1Close] = request.security(syminfo.tickerid, htf1TF, f_htf_confirmed(htf1Swing), lookahead=barmerge.lookahead_on)
 
[h2ID, h2Top, h2Bot, h2Right, h2BreakTime, l2ID, l2Top, l2Bot, l2Right, l2BreakTime, htf2Close] = request.security(syminfo.tickerid, htf2TF, f_htf_confirmed(htf2Swing), lookahead=barmerge.lookahead_on)
 
[h3ID, h3Top, h3Bot, h3Right, h3BreakTime, l3ID, l3Top, l3Bot, l3Right, l3BreakTime, htf3Close] = request.security(syminfo.tickerid, htf3TF, f_htf_confirmed(htf3Swing), lookahead=barmerge.lookahead_on)
 
 
 
bool newHtf1 = timeframe.change(htf1TF)
 
bool newHtf2 = timeframe.change(htf2TF)
 
bool newHtf3 = timeframe.change(htf3TF)
 
 
 
// Process each event only ONCE at the opening of the next HTF bar.
 
if htf1On and newHtf1
 
    if showHTFHighs
 
        f_mtf_upsert(h1ID, h1Top, h1Bot, h1Right, h1BreakTime, time, timeframe.in_seconds(htf1TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf1TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf1TF) / 60)) + "m", timeframe.in_seconds(htf1TF) * 1000, htf1Col, true, htf1HiBoxes)
 
    if showHTFLows
 
        f_mtf_upsert(l1ID, l1Top, l1Bot, l1Right, l1BreakTime, time, timeframe.in_seconds(htf1TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf1TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf1TF) / 60)) + "m", timeframe.in_seconds(htf1TF) * 1000, htf1Col, false, htf1LoBoxes)
 
if htf2On and newHtf2
 
    if showHTFHighs
 
        f_mtf_upsert(h2ID, h2Top, h2Bot, h2Right, h2BreakTime, time, (timeframe.in_seconds(htf2TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf2TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf2TF) / 60)) + "m"), timeframe.in_seconds(htf2TF) * 1000, htf2Col, true, htf2HiBoxes)
 
    if showHTFLows
 
        f_mtf_upsert(l2ID, l2Top, l2Bot, l2Right, l2BreakTime, time, (timeframe.in_seconds(htf2TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf2TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf2TF) / 60)) + "m"), timeframe.in_seconds(htf2TF) * 1000, htf2Col, false, htf2LoBoxes)
 
if htf3On and newHtf3
 
    if showHTFHighs
 
        f_mtf_upsert(h3ID, h3Top, h3Bot, h3Right, h3BreakTime, time, (timeframe.in_seconds(htf3TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf3TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf3TF) / 60)) + "m"), timeframe.in_seconds(htf3TF) * 1000, htf3Col, true, htf3HiBoxes)
 
    if showHTFLows
 
        f_mtf_upsert(l3ID, l3Top, l3Bot, l3Right, l3BreakTime, time, (timeframe.in_seconds(htf3TF) >= 3600 ? str.tostring(int(timeframe.in_seconds(htf3TF) / 3600)) + "H" : str.tostring(int(timeframe.in_seconds(htf3TF) / 60)) + "m"), timeframe.in_seconds(htf3TF) * 1000, htf3Col, false, htf3LoBoxes)
 
 
 
// Chart-close break source catches early LTF invalidation. HTF-close
 
// source waits for a fully finished candle from the zone's timeframe.
 
bool useChartBreak = mtfBreakSource == "Chart"
 
if htf1On
 
    bool checkBreak1 = barstate.isconfirmed and (useChartBreak or newHtf1)
 
    float price1 = useChartBreak ? close : htf1Close
 
    if showHTFHighs
 
        f_mtf_extend(htf1HiBoxes, true, checkBreak1, price1, useChartBreak ? time_close : time)
 
    if showHTFLows
 
        f_mtf_extend(htf1LoBoxes, false, checkBreak1, price1, useChartBreak ? time_close : time)
 
if htf2On
 
    bool checkBreak2 = barstate.isconfirmed and (useChartBreak or newHtf2)
 
    float price2 = useChartBreak ? close : htf2Close
 
    if showHTFHighs
 
        f_mtf_extend(htf2HiBoxes, true, checkBreak2, price2, useChartBreak ? time_close : time)
 
    if showHTFLows
 
        f_mtf_extend(htf2LoBoxes, false, checkBreak2, price2, useChartBreak ? time_close : time)
 
if htf3On
 
    bool checkBreak3 = barstate.isconfirmed and (useChartBreak or newHtf3)
 
    float price3 = useChartBreak ? close : htf3Close
 
    if showHTFHighs
 
        f_mtf_extend(htf3HiBoxes, true, checkBreak3, price3, useChartBreak ? time_close : time)
 
    if showHTFLows
 
        f_mtf_extend(htf3LoBoxes, false, checkBreak3, price3, useChartBreak ? time_close : time)
 
 
// MODULE E — Heikin-Ashi MACD OB/OS oscillator (original © EliCobra)
 
type bar
 
    float o = na
 
    float h = na
 
    float l = na
 
    float c = na
 
type osc
 
    bar   b = na
 
    float s = na
 
    float h = na
 
type alerts
 
    bool  s = false
 
    bool  b = false
 
    bool  u = false
 
    bool  d = false
 
    bool  p = false
 
    bool  n = false
 
    bool  x = false
 
    bool  y = false
 
method src(bar b, simple string src) =>
 
    float x = switch src
 
        'open'  =>          b.o
 
        'high'  =>          b.h
 
        'low'   =>          b.l
 
        'close' =>          b.c
 
        'oc2'   => math.avg(b.o, b.c          )
 
        'hl2'   => math.avg(b.h, b.l          )
 
        'hlc3'  => math.avg(b.h, b.l, b.c     )
 
        'ohlc4' => math.avg(b.o, b.h, b.l, b.c)
 
        'hlcc4' => math.avg(b.h, b.l, b.c, b.c)
 
    x
 
// Pine v6: calculate HA candle history using numeric series, not mutable UDT
 
// references. This also handles the first bar, where no previous HA candle exists.
 
method ha(bar b, simple bool p = true) =>
 
    float haClose = b.src('ohlc4')
 
    var float haOpen = na
 
    haOpen := na(haOpen[1]) ? b.src('oc2') : math.avg(haOpen[1], haClose[1])
 
    float haHigh = math.max(b.h, math.max(haOpen, haClose))
 
    float haLow  = math.min(b.l, math.min(haOpen, haClose))
 
    bar x = bar.new(haOpen, haHigh, haLow, haClose)
 
    p ? x : b
 
method stmc(bar b, simple string src, simple int flen, simple int slen, simple string sig, simple int clen) =>
 
    float x = (ta.ema(b.src(src), flen)  -
 
               ta.ema(b.src(src), slen)) /
 
              (ta.ema(b.h - b.l , slen)) * 100
 
    bar   z = bar.new(
 
             x[1]             ,
 
             math.max(x, x[1]),
 
             math.min(x, x[1]),
 
             x                ).ha()
 
    float s = ta.ema(z.src(sig), clen)
 
    osc.new(z, s, z.c - s)
 
const string gm = "MACD Settings", const string gu = "UI Options"
 
src  = input.string('close' , "Source"             , ['open',  'high',  'low',  'close',  'hl2',  'hlc3',  'ohlc4',  'hlcc4'],               group = gm)
 
fast = input.int   (12      , "Fast Length"        ,                                                                                         group = gm)
 
slow = input.int   (26      , "Slow Length"        ,                                                                                         group = gm)
 
sigb = input.bool  (true    , "Signal"             ,                                                                           inline = '1', group = gm)
 
sigs = input.string('close' , "Source"             , ['open',  'high',  'low',  'close',  'hl2',  'hlc3',  'ohlc4',  'hlcc4'], inline = '1', group = gm)
 
sigl = input.int   (9       , "Length"             ,                                                                           inline = '1', group = gm)
 
mode = input.string('Hybrid', "Display Mode"       , ['Hybrid',                       'MACD',                    'Histogram'],               group = gu)
 
revs = input.bool(true, "Show OB/OS Signals in Lower Pane", group = gu)
 
// Independent OB/OS levels: use any desired positive/negative oscillator values.
 
// These levels govern setups, zone shading, and extremity candle coloring.
 
const string gz = "OB/OS Zones"
 
obLevel = input.float(100.0, "Overbought Level (+)", minval = 0.0, step = 1.0, group = gz,
 
     tooltip = "Overbought extreme for short setups (e.g., 75, 100, 125, 200).")
 
osLevel = input.float(-100.0, "Oversold Level (-)", maxval = 0.0, step = 1.0, group = gz,
 
     tooltip = "Oversold extreme for long setups (e.g., -75, -100, -125, -200).")
 
chartRevs = input.bool(true, "Show OB/OS Signals on Price Chart", group = gu)
 
 
 
// OB/OS reversions are setups. When enabled, a later MACD/signal-line crossover
 
// confirms the entry, using the window below. Both marker locations and alerts
 
// use the SAME final confirmed OB/OS signals.
 
const string gc = "OB/OS Entry Confirmation"
 
useSignalConfirmation = input.bool(true, "Require Signal-Line Confirmation", group = gc)
 
confirmWindow = input.int(6, "Confirmation Window (candles)", minval = 1, maxval = 50, group = gc,
 
     tooltip = "Number of candles AFTER the OB/OS setup allowed for a signal-line crossover. A crossover on the setup candle also qualifies.")
 
requireBarClose = input.bool(true, "Require Confirmed Candle Close", group = gc,
 
     tooltip = "ON: OB/OS signals only form on completed chart candles. OFF: live-bar signals can change before the candle closes.")
 
colb = input.string('None'  , "Bar Coloring"       , ['None', 'MidLine', 'Candles', 'Sig Cross', 'Extremities', 'Reversions'],               group = gu)
 
hol  = input.bool  (true    , "Hollow Candles"     ,                                                                                         group = gu)
 
bar   b = bar.new (open, high, low , close      )
 
osc   o = b  .stmc(src , fast, slow, sigs , sigl)
 
const color colup = #00bcd4
 
const color coldn = #fc1f1f
 
const color colhu = #8ac3f5
 
const color colhd = #ffa7b6
 
var   color colnt = chart.fg_color
 
// A primitive float history is safe on bar 0 and avoids an undefined UDT.
 
float histValue = o.h
 
bool histRising = histValue > histValue[1]
 
color colh = histValue > 0 ?
 
     (histRising ? color.new(colhu, 20) : color.new(colhu, 30)) :
 
     (histRising ? color.new(colhd, 20) : color.new(colhd, 30))
 
color haColor = switch
 
    o.b.c > o.b.o => colup
 
    o.b.c < o.b.o => coldn
 
m   = hline(0                                      , "Mid Line", chart.fg_color,    hline.style_solid )
 
// Move the OB/OS shaded bands together with the user-selected thresholds.
 
// Keep the original fixed histogram-mode reference bands, since those represent
 
// different (histogram) values rather than the HA-MACD OB/OS reversal thresholds.
 
min = hline(mode != 'Histogram' ? osLevel - 100.0 : -100.0, display = display.none)
 
ll  = hline(mode != 'Histogram' ? osLevel -  50.0 :  -75.0, display = display.none)
 
hl  = hline(mode != 'Histogram' ? osLevel         :  -50.0, display = display.none)
 
max = hline(mode != 'Histogram' ? obLevel + 100.0 : +100.0, display = display.none)
 
hh  = hline(mode != 'Histogram' ? obLevel +  50.0 :  +75.0, display = display.none)
 
lh  = hline(mode != 'Histogram' ? obLevel         :  +50.0, display = display.none)
 
h   = plot (mode != 'Histogram' and sigb ? o.s : na, "Signal"  , colnt                                )
 
mc  = plot (mode != 'MACD'               ? o.h : na, "H"       , colh          , 1, plot.style_columns)
 
fill(lh, hh , color.new(coldn, 90))
 
fill(hh, max, color.new(coldn, 80))
 
fill(ll, hl , color.new(colup, 80))
 
fill(ll, min, color.new(colup, 80))
 
plotcandle(mode != 'Histogram' ? o.b.o  : na                                                    ,
 
           mode != 'Histogram' ? o.b.h  : na                                                    ,
 
           mode != 'Histogram' ? o.b.l  : na                                                    ,
 
           mode != 'Histogram' ? o.b.c  : na                                                    ,
 
           "𝗠𝗔𝗖𝗗", hol ? o.b.c > o.b.o ? na : haColor : haColor, haColor, bordercolor = haColor)
 
// Original OB/OS setup logic (unchanged).
 
rawOB = ta.crossunder(o.b.c, o.b.o) and o.b.h >  obLevel
 
rawOS = ta.crossover(o.b.c, o.b.o)  and o.b.l < osLevel
 
 
 
// Calculate signal-line crosses on EVERY bar, independent of selected mode.
 
macdBullCross = ta.crossover(o.b.c, o.s)
 
macdBearCross = ta.crossunder(o.b.c, o.s)
 
validBar = not requireBarClose or barstate.isconfirmed
 
 
 
var int pendingOBBar = na
 
var int pendingOSBar = na
 
bool sellSignal = false
 
bool buySignal = false
 
 
 
if validBar
 
    if useSignalConfirmation
 
        // New opposite setups cancel older pending setups.
 
        if rawOB
 
            pendingOBBar := bar_index
 
            pendingOSBar := na
 
        if rawOS
 
            pendingOSBar := bar_index
 
            pendingOBBar := na
 
 
 
        // Bar 0 is the setup itself; bars 1..N are the confirmation window.
 
        if not na(pendingOBBar) and bar_index - pendingOBBar > confirmWindow
 
            pendingOBBar := na
 
        if not na(pendingOSBar) and bar_index - pendingOSBar > confirmWindow
 
            pendingOSBar := na
 
 
 
        sellSignal := not na(pendingOBBar) and macdBearCross
 
        buySignal  := not na(pendingOSBar) and macdBullCross
 
 
 
        // Each setup can generate at most one confirmed signal.
 
        if sellSignal
 
            pendingOBBar := na
 
        if buySignal
 
            pendingOSBar := na
 
    else
 
        // Filter OFF = original OB/OS reversal timing (subject to close toggle).
 
        sellSignal := rawOB
 
        buySignal  := rawOS
 
        pendingOBBar := na
 
        pendingOSBar := na
 
 
 
// All pre-existing named alert conditions stay available. Their OB/OS fields
 
// now use the final (delayed or original) signal, just like the chart triangles.
 
alerts a = alerts.new(
 
                      sellSignal,
 
                      buySignal,
 
                      ta.crossover (o.b.c,     0),
 
                      ta.crossunder(o.b.c,     0),
 
                      ta.crossunder(o.b.c, o.b.o) and not (o.b.h >  obLevel),
 
                      ta.crossover (o.b.c, o.b.o) and not (o.b.l < osLevel),
 
                      macdBullCross,
 
                      macdBearCross)
 
// Lower-pane markers use final entry signals and oscillator coordinates.
 
plotshape(mode != 'Histogram' ? revs ? a.s ? o.b.h + 40 : na : na : na, "OB", shape.triangledown, location.absolute, coldn, size = size.tiny)
 
plotshape(mode != 'Histogram' ? revs ? a.b ? o.b.l - 40 : na : na : na, "OS", shape.triangleup, location.absolute, colup, size = size.tiny)
 
 
 
// Matching markers on main price chart; EXACT same confirmed a.s and a.b signals.
 
// force_overlay keeps the indicator itself in the lower pane.
 
plotshape(series = chartRevs and a.s, title = "OB (Price Chart)", style = shape.triangledown, location = location.abovebar, color = coldn, size = size.tiny, force_overlay = true)
 
plotshape(series = chartRevs and a.b, title = "OS (Price Chart)", style = shape.triangleup, location = location.belowbar, color = colup, size = size.tiny, force_overlay = true)
 
// One combined alertcondition, triggerable as a single named TradingView alert.
 
// Its direction placeholder is 1 (BUY) or -1 (SELL).
 
plot(buySignal ? 1 : sellSignal ? -1 : na, "OB/OS Direction Code", display = display.none, editable = false)
 
alertcondition(buySignal or sellSignal, "OB/OS Buy/Sell (Unified)",
 
     'Zacs MACD HA OB/OS | {{ticker}} {{interval}} | Direction {{plot("OB/OS Direction Code")}} (1=BUY, -1=SELL) | Close {{close}}')
 
alertcondition(a.s, "Overbought"          , 'OB Signal'            )
 
alertcondition(a.b, "Oversold  "          , 'OS Signal'            )
 
alertcondition(a.u, "Midline Crossover "  , 'Bullish Trend'        )
 
alertcondition(a.d, "Midline Crossunder"  , 'Bearish Trend'        )
 
alertcondition(a.p, "Positive Heikin-Ashi", 'Heikin-Ashi Uptrend  ')
 
alertcondition(a.n, "Negative Heikin-Ashi", 'Heikin-Ashi Downtrend')
 
alertcondition(a.x, "MACD Bull Cross"     , 'MACD Bullish Cross'   )
 
alertcondition(a.y, "MACD Bear Cross"     , 'MACD Bearish Cross'   )
 
// A SINGLE TradingView alert using "Any alert() function call" also handles
 
// both directions and provides BUY/SELL as words, not numeric codes.
 
// Other pre-existing signal alertcondition() choices remain available above.
 
if sellSignal
 
    alert("Zacs MACD HA OB/OS SELL | " + syminfo.ticker + " | TF " + timeframe.period + " | Close " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
 
if buySignal
 
    alert("Zacs MACD HA OB/OS BUY | " + syminfo.ticker + " | TF " + timeframe.period + " | Close " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
 
 
 
color col = switch colb
 
    'MidLine'     => o.b.c > 0     ? colup                         : coldn
 
    'Candles'     => o.b.c > o.b.o ? colup                         : coldn
 
    'Sig Cross'   => o.s   > o.b.c ? coldn                         : colup
 
    'Extremities' => o.b.c > obLevel ? coldn : o.b.c < osLevel ? colup : color.new(colnt, 25)
 
    'Reversions'  => a.b           ? coldn : a.s           ? colup : color.new(colnt, 25)
 
    'None'        => na
 
// MACD candle colors are blended with SMC colors at end of combined script.
 
 
 
// ============================================================================
// SINGLE PRICE-CANDLE COLOR OUTPUT
// Barcolor always affects main candles regardless of indicator pane.
// MACD defaults to "None", so the original SMC coloring wins by default.
// ============================================================================
barcolor(not na(col) ? col : smcBarCol, title="ZACS Combined Candle Colors")

← 返回列表