ICT Killzones Minimal - Liquidity Map

shazumax · study · 1040 行 · 点赞 43 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © shazumax
// ─────────────────────────────────────────────────────────────────────────────
//  ICT Killzones Minimal - Liquidity Map
//  A quiet, low-noise session tool for ICT / SMC traders.
//.
//  ICT Killzones (New York local time, DST aware):
//    Asia ................ 20:00 – 00:00
//    London .............. 02:00 – 05:00
//    New York ............ 07:00 – 10:00
//    London Close ........ 10:00 – 12:00
//    New York PM ......... 13:30 – 16:00  (off by default)
//
//  ICT Time Anchors (Opening Prices):
//    00:00 NYMO (True Day Open) · 08:30 Open · 09:30 RTH Open · 13:30 PM Open
//    Weekly Open (WO) · Monthly Open (MO)
//
//  Previous Period Liquidity:
//    PDH / PDL · PWH / PWL · PMH / PML
//
//  Line length encodes importance: reference prices are short, liquidity is long.
//  Line style encodes the level type: Solid = liquidity (killzone and previous-period
//  highs / lows), Dotted = opening reference prices. Swept liquidity fades.
//
//  Realtime / Bar Replay safe: all drawings are anchored by time (not bar_index) and
//  all state lives in series `var` variables or is guarded against per-tick duplication.
// ─────────────────────────────────────────────────────────────────────────────
//@version=6
indicator("ICT Killzones Minimal - Liquidity Map", shorttitle = "KZ Minimal", overlay = true,
     behind_chart = false, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// ═════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ═════════════════════════════════════════════════════════════════════════════
const string S_SOLID  = "Solid"
const string S_DASHED = "Dashed"
const string S_DOTTED = "Dotted"
 
const string G_GEN = "General"
const string G_KZD = "Killzone Style"
const string G_KZS = "Killzone Sessions"
const string G_LVL = "Previous Levels"
const string G_OPN = "Daily Opens"
const string G_OPH = "Weekly & Monthly Opens"
const string G_DAY = "Days"
const string G_ALR = "Alerts"
 
const string F_DAY  = "Current Day"
const string F_WEEK = "Current Week"
 
const color C_MAIN = #787B86
const color C_SOFT = #5D606B
const int   MAXLV  = 12
// Line length of the Daily Opens (bars). Intraday reference prices: shortest tier, fixed.
const int   OFF_OPEN = 20
// Base horizontal step (bars) used to stagger labels of nearby levels.
const int   LBL_GAP  = 12
// Highest timeframe (minutes) for killzones and opening prices. Above it a single candle
// spans several sessions, so session highs / lows and times would be drawn incorrectly.
const int   MAX_TF_MIN = 60
// Vertical distance (× ATR 14) under which two labels are treated as overlapping.
// Used for staggering only — never for merging.
const float OVERLAP_ATR = 0.5
// Number of past days covered by the Focus Mode overlay.
const int   DIM_DAYS = 60
 
const string TT_FOCUS = "Dims everything before the current day or week with the chart background color, " +
     "so only the price action that matters now stays in view.\n\n" +
     "Current Day — focus on today's sessions and the High / Low of Day. Only today's separator and day label are shown.\n" +
     "Current Week — focus on this week's trading days.\n\n" +
     "Killzones inside the dimmed area fade with it. Separators stay on top of the overlay.\n\n" +
     "Note: to dim past candles, the overlay has to be drawn above the chart. TradingView's own price line belongs to the chart, " +
     "so it is dimmed too where it crosses past days. This is by design, not an error — today's area and the price label on the scale stay fully visible.\n\n" +
     "Gradient backgrounds: Pine only reads a single background color (the middle of the gradient), " +
     "so the overlay shows as a flat band. Use a solid background in Chart Settings → Canvas for a seamless look."
 
const string TT_TZ = "All killzone and opening price times are New York local time (the ICT standard).\n\n" +
     "Whatever time zone your chart uses, everything is placed at the correct time automatically. " +
     "To change the chart time zone, click the clock in the bottom-right corner of the chart.\n\n" +
     "Daylight saving: New York switches to UTC−4 (EDT) on the 2nd Sunday of March and to UTC−5 (EST) on the 1st Sunday of November. " +
     "Killzones then move by one hour in your local time. This is expected under ICT rules and handled automatically — no manual change is needed."
 
const string TT_SES = "Each killzone: on / off · name shown on the chart · start and end time (New York).\n\n" +
     "Asia — Asian Killzone · 20:00–00:00\n" +
     "LO — London Open Killzone · 02:00–05:00\n" +
     "NY — New York AM Killzone · 07:00–10:00\n" +
     "LC — London Close Killzone · 10:00–12:00\n" +
     "PM — New York PM Session · 13:30–16:00"
 
const string TT_ALR = "To use: Create Alert → Condition: KZ Minimal → \"Any alert() function call\". One alert covers every enabled condition.\n\n" +
     "Desktop notifications show the Alert name, not the message, so give the alert a short name (e.g. \"KZ Gold\"). " +
     "The full message appears on mobile, in the popup and in the Alerts log."
 
// All ICT times are New York. The IANA name handles daylight saving automatically.
const string tz = "America/New_York"
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · General
// ═════════════════════════════════════════════════════════════════════════════
bool   dimOn   = input.bool(false, "Focus Mode", inline = "dim", display = display.none, group = G_GEN)
string dimMode = input.string(F_DAY, "", options = [F_DAY, F_WEEK], inline = "dim", display = display.none, group = G_GEN, tooltip = TT_FOCUS)
int    dimOpac = input.int(80, "Opacity %", minval = 0, maxval = 100, display = display.none, group = G_GEN,
     tooltip = "Strength of the Focus Mode overlay. It uses your chart background color, so it works on dark and light themes.")
bool   fadeSw  = input.bool(true, "Fade Swept Liquidity", inline = "fsw", display = display.none, group = G_GEN)
int    fadePct = input.int(80, "", minval = 0, maxval = 100, inline = "fsw", display = display.none, group = G_GEN,
     tooltip = "Once price trades beyond a killzone High / Low or a previous-period level (PDH / PDL, PWH / PWL, PMH / PML), " +
     "that liquidity has been taken, so its line and label fade into the background.\n\n" +
     "Only untapped liquidity stays bright — the levels price may still be drawn to. The line count shrinks through the day instead of growing.\n" +
     "Opening prices are reference prices, not liquidity, so they never fade.\n\n" +
     "The number sets how strongly swept liquidity fades: 0 = no fade, 100 = hidden (line and label). " +
     "Below 100, labels fade less than lines so the name stays readable.")
// Fade strength (%) for swept liquidity. Labels fade less than lines so the
// session name (and where each killzone ended) stays readable after its liquidity is taken.
int    swFade    = fadePct
// Up to 80 the label keeps ~5/8 of the line's fade (80 → 50). From 80 to 100 it catches up
// linearly (100 → 100), so at 100 swept liquidity disappears completely — no orphan labels.
int    swLblFade = fadePct <= 80 ? math.round(fadePct * 5 / 8) : math.round(50 + (fadePct - 80) * 2.5)
string txtSzIn = input.string("Small", "Text", options = ["Tiny", "Small", "Normal"], display = display.none, group = G_GEN)
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Killzone Style
// ═════════════════════════════════════════════════════════════════════════════
string kzType   = input.string("High / Low", "Display", options = ["Box", "High / Low", "Background", "Start / End"], display = display.none, group = G_KZD,
     tooltip = "Box — border + fill\nHigh / Low — session high and low lines\nBackground — fill only, from high to low\nStart / End — vertical lines at session start and end, from high to low")
int    kzLnW    = input.int(1, "Line", minval = 1, maxval = 4, inline = "kzl", display = display.none, group = G_KZD)
string kzLnSt   = input.string(S_SOLID, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "kzl", display = display.none, group = G_KZD)
color  kzLnCl   = input.color(C_MAIN, "", inline = "kzl", display = display.none, group = G_KZD,
     tooltip = "Width, style and color of the box border, High / Low lines and Start / End lines. Killzone labels use this color too.")
color  kzFill   = input.color(color.new(C_MAIN, 94), "Fill", display = display.none, group = G_KZD,
     tooltip = "Fill color for Box and Background. Set transparency with the Opacity slider in the color picker.")
string kzLblPos = input.string("Top Left", "Label",
     options = ["Top Left", "Top Center", "Top Right", "Bottom Left", "Bottom Center", "Bottom Right", "Hidden"], display = display.none, group = G_KZD)
string kzLblTx  = input.string("Name", "Label Text", options = ["Name", "Range", "Name + Range"], inline = "lt", display = display.none, group = G_KZD)
string kzUnit   = input.string("Pips", "", options = ["Pips", "Ticks", "Price"], inline = "lt", display = display.none, group = G_KZD,
     tooltip = "What the killzone label shows:\n" +
     "Name — NY\nRange — 65.2\nName + Range — NY · 65.2\n\n" +
     "Range = session High − Low in the unit picked in the second box (Pips / Ticks / Price). Only the number is shown.\n" +
     "To hide labels completely, set Label to Hidden.")
bool   kzShowNm = kzLblTx != "Range"
bool   kzShowRg = kzLblTx != "Name"
float  pipIn    = input.float(0.0, "Pip Size", minval = 0.0, step = 0.0001, display = display.none, group = G_KZD,
     tooltip = "0 = Auto (most users never need to change this):\n" +
     "Forex → 0.0001 (JPY pairs → 0.01)\nXAU → 0.1 · XAG → 0.01 · Oil → 0.01\nStocks → 0.01\n" +
     "Indices, Crypto, Futures → 1.0 (point)\n\n" +
     "If your broker defines a pip differently (e.g. XAU 0.01), enter it here.")
int    kzHist   = input.int(1, "History", minval = 1, maxval = 20, display = display.none, group = G_KZD,
     tooltip = "How many past occurrences of each killzone to keep on the chart. 1 = latest only.")
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Killzone Sessions
// ═════════════════════════════════════════════════════════════════════════════
// Informational only: tells the user which time zone the session times below are read in.
string tzSel    = input.string("New York (ICT)", "Timezone", options = ["New York (ICT)"], display = display.none, group = G_KZS, tooltip = TT_TZ)
 
// Row 1: [✓ Killzone] [label name]   Row 2: [start — end]. The time input sits on its own
// row so it is not squeezed or wrapped on the mobile app.
bool   k1On = input.bool(true, "Asia", inline = "k1", display = display.none, group = G_KZS)
string k1Nm = input.string("Asia", "", inline = "k1", display = display.none, group = G_KZS, tooltip = TT_SES)
string k1Tm = input.session("2000-0000", "", display = display.none, group = G_KZS)
 
bool   k2On = input.bool(true, "London", inline = "k2", display = display.none, group = G_KZS)
string k2Nm = input.string("LO", "", inline = "k2", display = display.none, group = G_KZS)
string k2Tm = input.session("0200-0500", "", display = display.none, group = G_KZS)
 
bool   k3On = input.bool(true, "New York", inline = "k3", display = display.none, group = G_KZS)
string k3Nm = input.string("NY", "", inline = "k3", display = display.none, group = G_KZS)
string k3Tm = input.session("0700-1000", "", display = display.none, group = G_KZS)
 
bool   k4On = input.bool(true, "London Close", inline = "k4", display = display.none, group = G_KZS)
string k4Nm = input.string("LC", "", inline = "k4", display = display.none, group = G_KZS)
string k4Tm = input.session("1000-1200", "", display = display.none, group = G_KZS)
 
bool   k5On = input.bool(false, "New York PM", inline = "k5", display = display.none, group = G_KZS)
string k5Nm = input.string("PM", "", inline = "k5", display = display.none, group = G_KZS)
string k5Tm = input.session("1330-1600", "", display = display.none, group = G_KZS)
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Previous Levels
// ═════════════════════════════════════════════════════════════════════════════
bool   pdOn = input.bool(true, "PDH · PDL", inline = "pd", display = display.none, group = G_LVL)
int    pdW  = input.int(1, "", minval = 1, maxval = 4, inline = "pd", display = display.none, group = G_LVL)
string pdSt = input.string(S_SOLID, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "pd", display = display.none, group = G_LVL)
color  pdCl = input.color(C_MAIN, "", inline = "pd", display = display.none, group = G_LVL,
     tooltip = "Previous Day High · Low")
 
bool   pwOn = input.bool(false, "PWH · PWL", inline = "pw", display = display.none, group = G_LVL)
int    pwW  = input.int(1, "", minval = 1, maxval = 4, inline = "pw", display = display.none, group = G_LVL)
string pwSt = input.string(S_SOLID, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "pw", display = display.none, group = G_LVL)
color  pwCl = input.color(C_MAIN, "", inline = "pw", display = display.none, group = G_LVL,
     tooltip = "Previous Week High · Low")
 
bool   pmOn = input.bool(false, "PMH · PML", inline = "pm", display = display.none, group = G_LVL)
int    pmW  = input.int(1, "", minval = 1, maxval = 4, inline = "pm", display = display.none, group = G_LVL)
string pmSt = input.string(S_SOLID, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "pm", display = display.none, group = G_LVL)
color  pmCl = input.color(C_MAIN, "", inline = "pm", display = display.none, group = G_LVL,
     tooltip = "Previous Month High · Low")
 
int    offLq = input.int(80, "Line Offset", minval = 0, maxval = 300, display = display.none, group = G_LVL,
     tooltip = "How many bars past the last candle the PDH / PDL, PWH / PWL and PMH / PML lines extend.\n\n" +
     "Line length encodes importance: short = reference price, long = liquidity.\n" +
     "Daily Opens (20 bars) < WO / MO < Previous Levels. Keep this value above the WO / MO offset to preserve that order.\n\n" +
     "Levels at exactly the same price from different tiers (e.g. PDL = PWL) share one label in the longest column.\n\n" +
     "If a distant level (usually PMH / PML) squeezes the chart, right-click the price scale and choose " +
     "\"Scale price chart only\". The chart then fits the candles only and distant levels stay off-screen.")
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Daily Opens (ICT time anchors)
// ═════════════════════════════════════════════════════════════════════════════
bool   o1On = input.bool(true, "NYMO", inline = "o1", display = display.none, group = G_OPN)
string o1Tm = input.string("00:00", "", inline = "o1", display = display.none, group = G_OPN,
     tooltip = "New York Midnight Open · True Day Open. Time in HH:MM (New York); this text is also the label.")
bool   o2On = input.bool(false, "8:30 Open", inline = "o2", display = display.none, group = G_OPN)
string o2Tm = input.string("08:30", "", inline = "o2", display = display.none, group = G_OPN,
     tooltip = "New York 8:30 Open · release time of high-impact US data (CPI, NFP).")
bool   o3On = input.bool(false, "RTH Open", inline = "o3", display = display.none, group = G_OPN)
string o3Tm = input.string("09:30", "", inline = "o3", display = display.none, group = G_OPN,
     tooltip = "Regular Trading Hours Open · New York equities open. Most relevant for index futures.")
bool   o4On = input.bool(false, "PM Open", inline = "o4", display = display.none, group = G_OPN)
string o4Tm = input.string("13:30", "", inline = "o4", display = display.none, group = G_OPN,
     tooltip = "New York PM Session Open.")
int    oW   = input.int(1, "Style", minval = 1, maxval = 4, inline = "os", display = display.none, group = G_OPN)
string oSt  = input.string(S_DOTTED, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "os", display = display.none, group = G_OPN)
color  oCl  = input.color(C_SOFT, "", inline = "os", display = display.none, group = G_OPN,
     tooltip = "Each opening price stays in view, with its label, until the same time comes again the next day.")
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Weekly & Monthly Opens
// ═════════════════════════════════════════════════════════════════════════════
bool   woOn = input.bool(true, "Weekly Open", inline = "wo", display = display.none, group = G_OPH)
int    woW  = input.int(1, "", minval = 1, maxval = 4, inline = "wo", display = display.none, group = G_OPH)
string woSt = input.string(S_DOTTED, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "wo", display = display.none, group = G_OPH)
color  woCl = input.color(C_SOFT, "", inline = "wo", display = display.none, group = G_OPH,
     tooltip = "Weekly Open (WO): open of the first candle of the week (broker week start; Sunday evening open for Forex).\n" +
     "Price above WO reads as premium, below as discount.")
bool   moOn = input.bool(true, "Monthly Open", inline = "mo", display = display.none, group = G_OPH)
int    moW  = input.int(1, "", minval = 1, maxval = 4, inline = "mo", display = display.none, group = G_OPH)
string moSt = input.string(S_DOTTED, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "mo", display = display.none, group = G_OPH)
color  moCl = input.color(C_SOFT, "", inline = "mo", display = display.none, group = G_OPH,
     tooltip = "Monthly Open (MO): open of the first candle of the month.")
int    offWM = input.int(40, "Line Offset", minval = 0, maxval = 300, display = display.none, group = G_OPH,
     tooltip = "How many bars past the last candle the WO / MO lines extend.\n" +
     "Keep it longer than the Daily Opens (20 bars) and shorter than the Previous Levels.")
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Days
// ═════════════════════════════════════════════════════════════════════════════
bool   sepLbl = input.bool(false, "Day Label", inline = "sepl", display = display.none, group = G_DAY)
string sepLH  = input.string("Center", "", options = ["Left", "Center", "Right"], inline = "sepl", display = display.none, group = G_DAY)
string sepLV  = input.string("Top", "", options = ["Top", "Bottom"], inline = "sepl", display = display.none, group = G_DAY)
color  sepLCl = input.color(C_SOFT, "", inline = "sepl", display = display.none, group = G_DAY,
     tooltip = "Shows the trading day name (MON, TUE, WED, THU, FRI) pinned to the top or bottom edge of the chart. " +
     "Independent of the Separator.\n\n" +
     "Left — start of the day\nCenter — around the middle of the day\nRight — around the end of the day\n" +
     "Center / Right use an average day length (Forex, Indices: 23 h, Crypto: 24 h), so days with breaks may be slightly off.\n\n" +
     "Only the current trading week is labeled; with Focus Mode · Current Day, only today. " +
     "Day names follow the broker trading day (e.g. the Sunday evening open = MON).\n\n" +
     "The distance from the edge is set by Chart Settings → Scales and lines → Margins (Top / Bottom %). Lower them to move labels closer.\n" +
     "In Bar Replay, labels from earlier days may remain when the day or week changes; restarting the replay refreshes them.")
bool   sepOn = input.bool(false, "Separator", inline = "sep", display = display.none, group = G_DAY)
int    sepW  = input.int(1, "", minval = 1, maxval = 4, inline = "sep", display = display.none, group = G_DAY)
string sepSt = input.string(S_DOTTED, "", options = [S_SOLID, S_DASHED, S_DOTTED], inline = "sep", display = display.none, group = G_DAY)
color  sepCl = input.color(color.new(C_SOFT, 50), "", inline = "sep", display = display.none, group = G_DAY,
     tooltip = "Vertical line at the start of each trading day (broker daily candle) for the current week. " +
     "With Focus Mode · Current Day, only today's separator is shown.")
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS · Alerts
// ═════════════════════════════════════════════════════════════════════════════
bool   alKzRaid = input.bool(true,  "Killzone Raid", display = display.none, group = G_ALR,
     tooltip = "Fires when price first trades beyond a finished killzone's High or Low (liquidity raid), " +
     "e.g. \"Asia High raided\". Watched until the same killzone starts again.\n\n" + TT_ALR)
bool   alLvRaid = input.bool(true,  "Level Raid", display = display.none, group = G_ALR,
     tooltip = "Fires when price first trades beyond PDH / PDL, PWH / PWL or PMH / PML. Enabled levels only.\n\n" + TT_ALR)
bool   alKzOpen = input.bool(false, "Killzone Start / End", display = display.none, group = G_ALR,
     tooltip = "Fires when a killzone starts and ends.\n\n" + TT_ALR)
 
// ═════════════════════════════════════════════════════════════════════════════
// HELPERS
// ═════════════════════════════════════════════════════════════════════════════
f_style(string s) =>
    s == S_SOLID ? line.style_solid : s == S_DASHED ? line.style_dashed : line.style_dotted
 
f_size(string s) =>
    s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
 
f_autoPip() =>
    string tk = syminfo.ticker
    float  p  = syminfo.mintick
    if str.contains(tk, "XAU")
        p := 0.1
    else if str.contains(tk, "XAG")
        p := 0.01
    else if syminfo.type == "forex"
        p := syminfo.mintick * 10
    else if str.contains(tk, "OIL") or str.contains(tk, "WTI") or str.contains(tk, "BRENT") or str.startswith(tk, "CL") or str.startswith(tk, "BZ")
        p := 0.01
    else if syminfo.type == "stock" or syminfo.type == "fund"
        p := 0.01
    else if syminfo.type == "index" or syminfo.type == "crypto" or syminfo.type == "futures" or syminfo.type == "cfd"
        p := 1.0
    p
 
string txtSz   = f_size(txtSzIn)
float  pipSize = pipIn > 0 ? pipIn : f_autoPip()
bool   tfIntra = timeframe.isintraday and timeframe.in_seconds() <= MAX_TF_MIN * 60
color  C_NONE  = color.new(color.black, 100)
string kzLs    = f_style(kzLnSt)
 
// Fades a drawing by the Focus Mode opacity. Killzone boxes, lines and labels sit above the
// overlay in Pine's z-order (linefill < line < box < label), so they are dimmed by color instead.
f_fade(color c, bool faded) =>
    faded ? color.new(c, 100 - (100 - color.t(c)) * (100 - dimOpac) / 100) : c
 
// Fades a color by an arbitrary percentage (used for swept liquidity).
f_fadeBy(color c, int pct) =>
    color.new(c, 100 - (100 - color.t(c)) * (100 - pct) / 100)
 
f_rangeTxt(float r) =>
    switch kzUnit
        "Pips"  => str.tostring(r / pipSize, "#,##0.0")
        "Ticks" => str.tostring(math.round(r / syminfo.mintick), "#,##0")
        => str.tostring(r, format.mintick)
 
// Exact start / end timestamps of the session window that contains time t.
f_window(string sess, int t) =>
    int sh = int(str.tonumber(str.substring(sess, 0, 2)))
    int sm = int(str.tonumber(str.substring(sess, 2, 4)))
    int eh = int(str.tonumber(str.substring(sess, 5, 7)))
    int em = int(str.tonumber(str.substring(sess, 7, 9)))
    int t1 = timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz), sh, sm)
    if t1 > t
        t1 := timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz) - 1, sh, sm)
    int t2 = timestamp(tz, year(t1, tz), month(t1, tz), dayofmonth(t1, tz), eh, em)
    if t2 <= t1
        t2 := timestamp(tz, year(t1, tz), month(t1, tz), dayofmonth(t1, tz) + 1, eh, em)
    [t1, t2]
 
// True on the bar that crosses the "HH:MM" New York time (called on every bar).
f_hit(string hhmm) =>
    int h = int(str.tonumber(str.substring(hhmm, 0, 2)))
    int m = int(str.tonumber(str.substring(hhmm, 3, 5)))
    int t = timestamp(tz, year(time, tz), month(time, tz), dayofmonth(time, tz), h, m)
    // The bar must open at (or within one bar of) that time, so the first bar after a weekend
    // or session break does not capture several opening times at once.
    time >= t and nz(time[1]) < t and time - t < timeframe.in_seconds() * 1000
 
// ═════════════════════════════════════════════════════════════════════════════
// TYPES
// ═════════════════════════════════════════════════════════════════════════════
type Drawing
    box   bx
    line  a
    line  b
    label lb
    int   t2
    float hi
    float lo
    bool  hiSw = false
    bool  loSw = false
 
type Killzone
    bool   on
    string name
    string sess
    float  hi
    float  lo
    int    t1
    int    t2
    Drawing        cur
    array<Drawing> hist
 
type Period
    float h
    float l
    int   hT
    int   lT
    int   startBar
    int   startT
    float ph
    float pl
    int   phT
    int   plT
    int   pStartT
 
type Level
    float  price
    string name
    color  col
    int    anchor
    int    width
    string lstyle
    int    prio
    bool   swept = false
 
// ═════════════════════════════════════════════════════════════════════════════
// METHODS
// ═════════════════════════════════════════════════════════════════════════════
method wipe(Drawing d) =>
    if not na(d)
        d.bx.delete()
        d.a.delete()
        d.b.delete()
        d.lb.delete()
 
// Re-applies colors to a killzone drawing (faded or normal).
method restyle(Drawing d, bool faded) =>
    // Swept: High / Low mode fades each side on its own; other modes fade once both sides are taken.
    bool  bothSw = fadeSw and d.hiSw and d.loSw
    color lc  = f_fade(kzLnCl, faded)
    color fc  = f_fade(kzFill, faded)
    color lcA = fadeSw and d.hiSw and kzType == "High / Low" ? f_fadeBy(lc, swFade) : bothSw ? f_fadeBy(lc, swFade) : lc
    color lcB = fadeSw and d.loSw and kzType == "High / Low" ? f_fadeBy(lc, swFade) : bothSw ? f_fadeBy(lc, swFade) : lc
    color lcL = bothSw ? f_fadeBy(lc, swLblFade) : lc
    if not na(d.bx)
        d.bx.set_bgcolor(bothSw ? f_fadeBy(fc, swFade) : fc)
        if kzType == "Box"
            d.bx.set_border_color(bothSw ? f_fadeBy(lc, swFade) : lc)
    if not na(d.a)
        d.a.set_color(lcA)
    if not na(d.b)
        d.b.set_color(lcB)
    if not na(d.lb)
        d.lb.set_textcolor(lcL)
    d
 
f_kzText(Killzone k) =>
    string s = kzShowNm ? k.name : ""
    if kzShowRg
        string r = f_rangeTxt(k.hi - k.lo)
        s := s == "" ? r : s + " · " + r
    s
 
f_lblXY(Killzone k) =>
    int x = switch kzLblPos
        "Top Left"     => k.t1
        "Bottom Left"  => k.t1
        "Top Right"    => k.t2
        "Bottom Right" => k.t2
        => int(math.avg(k.t1, k.t2))
    float y = str.startswith(kzLblPos, "Top") ? k.hi : k.lo
    string st = switch kzLblPos
        "Top Left"      => label.style_label_lower_left
        "Top Center"    => label.style_label_down
        "Top Right"     => label.style_label_lower_right
        "Bottom Left"   => label.style_label_upper_left
        "Bottom Center" => label.style_label_up
        => label.style_label_upper_right
    [x, y, st]
 
method render(Killzone k) =>
    Drawing d = k.cur
    if kzType == "Box" or kzType == "Background"
        bool isBox = kzType == "Box"
        if na(d.bx)
            d.bx := box.new(k.t1, k.hi, k.t2, k.lo, xloc = xloc.bar_time,
                 border_color = isBox ? kzLnCl : C_NONE, border_width = isBox ? kzLnW : 0,
                 border_style = kzLs, bgcolor = kzFill)
        else
            d.bx.set_top(k.hi)
            d.bx.set_bottom(k.lo)
    else if kzType == "High / Low"
        if na(d.a)
            d.a := line.new(k.t1, k.hi, k.t2, k.hi, xloc = xloc.bar_time, color = kzLnCl, style = kzLs, width = kzLnW)
            d.b := line.new(k.t1, k.lo, k.t2, k.lo, xloc = xloc.bar_time, color = kzLnCl, style = kzLs, width = kzLnW)
        else
            d.a.set_y1(k.hi)
            d.a.set_y2(k.hi)
            d.b.set_y1(k.lo)
            d.b.set_y2(k.lo)
    else if kzType == "Start / End"
        if na(d.a)
            d.a := line.new(k.t1, k.hi, k.t1, k.lo, xloc = xloc.bar_time, color = kzLnCl, style = kzLs, width = kzLnW)
            d.b := line.new(k.t2, k.hi, k.t2, k.lo, xloc = xloc.bar_time, color = kzLnCl, style = kzLs, width = kzLnW)
        else
            d.a.set_y1(k.hi)
            d.a.set_y2(k.lo)
            d.b.set_y1(k.hi)
            d.b.set_y2(k.lo)
    if kzLblPos != "Hidden" and (kzShowNm or kzShowRg)
        [x, y, st] = f_lblXY(k)
        string txt = f_kzText(k)
        if na(d.lb)
            d.lb := label.new(x, y, txt, xloc = xloc.bar_time, style = st, color = C_NONE, textcolor = kzLnCl, size = txtSz)
        else
            d.lb.set_xy(x, y)
            d.lb.set_text(txt)
    d
 
// Session start is detected with a series condition (inS and not inS[1]); one drawing per
// session (guarded by t1), so realtime ticks never create duplicates.
method update(Killzone k) =>
    bool inS   = k.on and tfIntra and not na(time(timeframe.period, k.sess + ":1234567", tz))
    bool start = inS and not inS[1]
    if start
        [t1, t2] = f_window(k.sess, time)
        k.hi := high
        k.lo := low
        if na(k.t1) or t1 != k.t1
            k.t1 := t1
            // Right edge = session end time, so adjacent killzones (NY 10:00 → LC 10:00)
            // join on one line and the ICT sequence reads continuously.
            k.t2 := t2
            Drawing d = Drawing.new(t2 = t2)
            k.cur := d
            k.hist.push(d)
            if k.hist.size() > kzHist
                k.hist.shift().wipe()
    else if inS
        k.hi := math.max(k.hi, high)
        k.lo := math.min(k.lo, low)
    if inS and not na(k.cur)
        k.cur.hi := k.hi
        k.cur.lo := k.lo
        k.render()
    // Sweep detection for finished killzones: price trading beyond their High / Low.
    for d in k.hist
        if not na(d.hi) and time >= d.t2
            if not d.hiSw and high > d.hi
                d.hiSw := true
            if not d.loSw and low < d.lo
                d.loSw := true
    inS
 
// With Focus Mode on, fades drawings that ended before the focus boundary.
method fade(Killzone k, bool fOn, int rightT) =>
    for d in k.hist
        d.restyle(fOn and d.t2 <= rightT)
    k
 
// Tracks a period's High / Low and when they printed. The startBar guard stops the
// rotation from repeating on realtime ticks.
method track(Period p, bool isNew) =>
    if isNew and not na(p.h) and p.startBar != bar_index
        p.ph       := p.h
        p.pl       := p.l
        p.phT      := p.hT
        p.plT      := p.lT
        p.pStartT  := p.startT
        p.h        := high
        p.l        := low
        p.hT       := time
        p.lT       := time
        p.startBar := bar_index
        p.startT   := time
    else
        if na(p.startBar)
            p.startBar := bar_index
            p.startT   := time
        if na(p.h) or high > p.h
            p.h  := high
            p.hT := time
        if na(p.l) or low < p.l
            p.l  := low
            p.lT := time
    p
 
// Tier: 0 = Daily Opens, 1 = WO / MO, 2 = PDH / PDL, 3 = PWH / PWL · PMH / PML
f_tier(int prio) =>
    prio <= 1 ? 2 : prio <= 5 ? 3 : prio <= 9 ? 0 : 1
 
// Start TIME of a level line: the candle that printed the previous period's high / low
// (or the period start). Time, not bar_index, avoids history-buffer limits (Replay-safe).
f_anchor(float secV, float trackV, int trackT, int pStartT, int fallbackT) =>
    bool match = not na(trackV) and not na(secV) and math.abs(trackV - secV) <= syminfo.mintick * 2
    match ? trackT : not na(pStartT) ? pStartT : fallbackT
 
// Replaces an opening price when the same time comes again (no old line is kept).
// The `t != time` guard prevents duplicates on realtime ticks.
f_roll(bool on, bool hit, float p, int t) =>
    float np = p
    int   nt = t
    if tfIntra and on and hit and (na(t) or t != time)
        np := open
        nt := time
    [np, nt]
 
// Killzone alerts. Local `var` state per call site, so it survives realtime / Replay rollback.
f_kzAlerts(bool inS, float hi, float lo, string nm) =>
    var float rH = na
    var float rL = na
    var bool  hDone = false
    var bool  lDone = false
    bool started = inS and not inS[1]
    bool ended   = not inS and inS[1]
    if ended
        rH    := hi
        rL    := lo
        hDone := false
        lDone := false
    if started
        rH := na
        rL := na
        if alKzOpen
            alert(syminfo.ticker + " · " + nm + " killzone started", alert.freq_once_per_bar)
    if ended and alKzOpen
        alert(syminfo.ticker + " · " + nm + " killzone ended", alert.freq_once_per_bar)
    if alKzRaid and not inS
        if not na(rH) and not hDone and high > rH
            hDone := true
            alert(syminfo.ticker + " · " + nm + " High raided @ " + str.tostring(rH, format.mintick), alert.freq_once_per_bar)
        if not na(rL) and not lDone and low < rL
            lDone := true
            alert(syminfo.ticker + " · " + nm + " Low raided @ " + str.tostring(rL, format.mintick), alert.freq_once_per_bar)
    inS
 
// Previous-level raid alert. Re-arms when the level changes.
f_lvlAlert(bool on, float lvl, bool isHigh, string nm) =>
    var bool done = false
    if lvl != lvl[1]
        done := false
    if alLvRaid and on and not na(lvl) and not done
        bool hit = isHigh ? high > lvl : low < lvl
        if hit
            done := true
            alert(syminfo.ticker + " · " + nm + " raided @ " + str.tostring(lvl, format.mintick), alert.freq_once_per_bar)
    done
 
// ═════════════════════════════════════════════════════════════════════════════
// SCALE ANCHOR — invisible plots that tie this drawing-based script to the price scale
// ═════════════════════════════════════════════════════════════════════════════
plot(high, "Scale Anchor High", color = color.new(color.black, 100), display = display.pane, editable = false)
plot(low,  "Scale Anchor Low",  color = color.new(color.black, 100), display = display.pane, editable = false)
 
// ═════════════════════════════════════════════════════════════════════════════
// CORE · Killzones
// ═════════════════════════════════════════════════════════════════════════════
var Killzone kz1 = Killzone.new(k1On, k1Nm, k1Tm, hist = array.new<Drawing>())
var Killzone kz2 = Killzone.new(k2On, k2Nm, k2Tm, hist = array.new<Drawing>())
var Killzone kz3 = Killzone.new(k3On, k3Nm, k3Tm, hist = array.new<Drawing>())
var Killzone kz4 = Killzone.new(k4On, k4Nm, k4Tm, hist = array.new<Drawing>())
var Killzone kz5 = Killzone.new(k5On, k5Nm, k5Tm, hist = array.new<Drawing>())
 
bool in1 = kz1.update()
bool in2 = kz2.update()
bool in3 = kz3.update()
bool in4 = kz4.update()
bool in5 = kz5.update()
 
f_kzAlerts(in1, kz1.hi, kz1.lo, k1Nm)
f_kzAlerts(in2, kz2.hi, kz2.lo, k2Nm)
f_kzAlerts(in3, kz3.hi, kz3.lo, k3Nm)
f_kzAlerts(in4, kz4.hi, kz4.lo, k4Nm)
f_kzAlerts(in5, kz5.hi, kz5.lo, k5Nm)
 
// ═════════════════════════════════════════════════════════════════════════════
// CORE · Periods
// ═════════════════════════════════════════════════════════════════════════════
bool newDay   = timeframe.change("D")
bool newWeek  = timeframe.change("W")
bool newMonth = timeframe.change("M")
 
var Period pD = Period.new()
var Period pW = Period.new()
var Period pM = Period.new()
pD.track(newDay)
pW.track(newWeek)
pM.track(newMonth)
 
[dH, dL] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[wH, wL] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[mH, mL] = request.security(syminfo.tickerid, "M", [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
// ═════════════════════════════════════════════════════════════════════════════
// CORE · Opening Prices — series `var` state (realtime / Replay rollback-safe)
// ═════════════════════════════════════════════════════════════════════════════
bool hit1 = f_hit(o1Tm)
bool hit2 = f_hit(o2Tm)
bool hit3 = f_hit(o3Tm)
bool hit4 = f_hit(o4Tm)
 
var float o1P = na
var int   o1B = na
var float o2P = na
var int   o2B = na
var float o3P = na
var int   o3B = na
var float o4P = na
var int   o4B = na
 
 
// Weekly / Monthly Open come straight from the HTF bar, so they appear even when the week or
// month start is outside the loaded history (1m charts, Replay). The open is fixed when the
// bar starts, so lookahead_on does not repaint.
[woP, woT0] = request.security(syminfo.tickerid, "W", [open, time], lookahead = barmerge.lookahead_on)
[moP, moT0] = request.security(syminfo.tickerid, "M", [open, time], lookahead = barmerge.lookahead_on)
var int firstT = time
// If the line would start before the first loaded candle, start it there instead.
int woT = na(woT0) ? na : math.max(woT0, firstT)
int moT = na(moT0) ? na : math.max(moT0, firstT)
 
// Daily opens are not reset at the new day: each stays valid until its time comes again.
 
[r1p, r1t] = f_roll(o1On, hit1, o1P, o1B)
[r2p, r2t] = f_roll(o2On, hit2, o2P, o2B)
[r3p, r3t] = f_roll(o3On, hit3, o3P, o3B)
[r4p, r4t] = f_roll(o4On, hit4, o4P, o4B)
o1P := r1p
o1B := r1t
o2P := r2p
o2B := r2t
o3P := r3p
o3B := r3t
o4P := r4p
o4B := r4t
 
float atr = ta.atr(14)
 
bool tfD = timeframe.in_seconds() < timeframe.in_seconds("D")
bool tfW = timeframe.in_seconds() < timeframe.in_seconds("W")
bool tfM = timeframe.in_seconds() < timeframe.in_seconds("M")
f_lvlAlert(pdOn and tfD, dH, true,  "PDH")
f_lvlAlert(pdOn and tfD, dL, false, "PDL")
f_lvlAlert(pwOn and tfW, wH, true,  "PWH")
f_lvlAlert(pwOn and tfW, wL, false, "PWL")
f_lvlAlert(pmOn and tfM, mH, true,  "PMH")
f_lvlAlert(pmOn and tfM, mL, false, "PML")
 
// ═════════════════════════════════════════════════════════════════════════════
// CORE · Day Separator & Focus Mode state
// ═════════════════════════════════════════════════════════════════════════════
var array<line> seps    = array.new<line>()
var int         lastSep = na
if newWeek and seps.size() > 0 and (na(lastSep) or lastSep != bar_index)
    for l in seps
        l.delete()
    seps.clear()
// Focus Mode overlay: one fill (linefill) per day, sized to that day's High–Low.
// • It never exceeds the candle range, so it does not affect the chart's auto scale.
// • Pine z-order is linefill < line < box < label, so separators (lines) always sit on top.
var array<linefill> dimFills = array.new<linefill>()
// Each day's own High / Low; on the last bar every fill is stretched to include the current
// price, so TradingView's price line is dimmed evenly (no broken pieces) across past days.
var array<float>    dimHis   = array.new<float>()
var array<float>    dimLos   = array.new<float>()
var int   dimDayT  = na
var float dimHi    = na
var float dimLo    = na
var int   lastDimB = na
if timeframe.isintraday and newDay and (na(lastDimB) or lastDimB != bar_index)
    lastDimB := bar_index
    if not na(dimDayT)
        // The fill ends at the centre of the new day's first candle, so the left half of that
        // candle lies inside this fill. Include its High / Low too, otherwise on higher
        // timeframes (3H, 4H) half of a taller candle pokes out above or below the fill.
        float fHi = math.max(dimHi, high)
        float fLo = math.min(dimLo, low)
        line l1 = line.new(dimDayT, fHi, time, fHi, xloc = xloc.bar_time, color = C_NONE)
        line l2 = line.new(dimDayT, fLo, time, fLo, xloc = xloc.bar_time, color = C_NONE)
        dimFills.push(linefill.new(l1, l2, C_NONE))
        dimHis.push(fHi)
        dimLos.push(fLo)
        if dimFills.size() > DIM_DAYS
            linefill old = dimFills.shift()
            old.get_line1().delete()
            old.get_line2().delete()
            old.delete()
            dimHis.shift()
            dimLos.shift()
    dimDayT := time
    dimHi   := high
    dimLo   := low
else if not na(dimDayT)
    dimHi := math.max(dimHi, high)
    dimLo := math.min(dimLo, low)
 
if sepOn and timeframe.isintraday and newDay and (na(lastSep) or lastSep != bar_index)
    lastSep := bar_index
    seps.push(line.new(time, high, time, low, xloc = xloc.bar_time, extend = extend.both, color = sepCl, style = f_style(sepSt), width = sepW))
 
 
// ── Day Labels — pinned to the pane edge with plotshape(location.top / bottom).
// plotshape text must be const, hence one plot per weekday.
// The series is a price (high), not a bool (0/1): otherwise TradingView treats the script's
// values as a different range, moves it to "No scale" and the drawings detach from price.
int    dayBars = int(math.round((syminfo.type == "crypto" ? 86400 : 82800) / timeframe.in_seconds()))
int    dOff    = sepLH == "Left" ? 0 : sepLH == "Center" ? int(dayBars / 2) : math.max(dayBars - 1, 0)
string dLoc    = sepLV == "Top" ? location.top : location.bottom
// location.top / bottom sit on the chart's scale-margin boundary. labeldown keeps the bubble
// above that point: at the top it moves into the margin (closer to the edge); at the bottom it
// stays inside the pane (a bubble below the bottom boundary would be clipped).
string dShape  = shape.labeldown
// Current trading week only (Forex: MON–FRI); with Focus Mode · Current Day, today only.
bool   dToday  = not (dimOn and dimMode == F_DAY) or time_close("D") > last_bar_time
bool   dOn     = sepLbl and timeframe.isintraday and newDay and time_close("W") > last_bar_time and dToday
int    dDow    = dayofweek(time_tradingday, "UTC")
bool   dLblL   = dOn and sepLH == "Left"
bool   dLblC   = dOn and sepLH == "Center"
bool   dLblR   = dOn and sepLH == "Right"
 
// plotshape text is always centered on its bar and must be const, so alignment is done with
// figure-space padding (U+2007): Left pads before the name (text starts just right of the
// separator), Right pads after it (text ends just left of the next separator). Padding is
// measured in characters, so it holds at any zoom level. One plot per weekday × alignment.
// Left
plotshape(dLblL and dDow == dayofweek.monday ? high : na, title = "MON L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     MON", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.tuesday ? high : na, title = "TUE L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     TUE", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.wednesday ? high : na, title = "WED L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     WED", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.thursday ? high : na, title = "THU L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     THU", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.friday ? high : na, title = "FRI L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     FRI", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.saturday ? high : na, title = "SAT L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     SAT", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblL and dDow == dayofweek.sunday ? high : na, title = "SUN L", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "     SUN", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
// Center
plotshape(dLblC and dDow == dayofweek.monday ? high : na, title = "MON C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "MON", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.tuesday ? high : na, title = "TUE C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "TUE", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.wednesday ? high : na, title = "WED C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "WED", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.thursday ? high : na, title = "THU C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "THU", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.friday ? high : na, title = "FRI C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "FRI", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.saturday ? high : na, title = "SAT C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "SAT", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblC and dDow == dayofweek.sunday ? high : na, title = "SUN C", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "SUN", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
// Right
plotshape(dLblR and dDow == dayofweek.monday ? high : na, title = "MON R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "MON     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.tuesday ? high : na, title = "TUE R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "TUE     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.wednesday ? high : na, title = "WED R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "WED     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.thursday ? high : na, title = "THU R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "THU     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.friday ? high : na, title = "FRI R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "FRI     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.saturday ? high : na, title = "SAT R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "SAT     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
plotshape(dLblR and dDow == dayofweek.sunday ? high : na, title = "SUN R", style = dShape, location = dLoc, color = C_NONE, offset = dOff,
     text = "SUN     ", textcolor = sepLCl, editable = false, size = size.tiny, display = display.pane)
 
var int   dayStartT  = na
var int   weekStartT = na
 
if newDay
    dayStartT := time
if newWeek
    weekStartT := time
 
// ═════════════════════════════════════════════════════════════════════════════
// RENDER · Key Levels & Focus
// A pre-built line / label pool is updated with setters (never deleted and recreated).
// Runs on the last bar and on every realtime / Replay bar.
// ═════════════════════════════════════════════════════════════════════════════
var array<line>  lvLines  = array.new<line>()
var array<label> lvLabels = array.new<label>()
 
if barstate.isfirst
    for i = 0 to MAXLV - 1
        lvLines.push(line.new(na, na, na, na, xloc = xloc.bar_time, color = C_NONE))
        lvLabels.push(label.new(na, na, "", xloc = xloc.bar_time, style = label.style_label_left, color = C_NONE, textcolor = C_NONE, size = txtSz))
 
if barstate.islast or barstate.isrealtime
    int tfs = timeframe.in_seconds()
    array<Level> lv = array.new<Level>()
 
    if pdOn and tfs < timeframe.in_seconds("D") and not na(dH)
        lv.push(Level.new(dH, "PDH", pdCl, f_anchor(dH, pD.ph, pD.phT, pD.pStartT, firstT), pdW, pdSt, 0, pD.h > dH))
        lv.push(Level.new(dL, "PDL", pdCl, f_anchor(dL, pD.pl, pD.plT, pD.pStartT, firstT), pdW, pdSt, 1, pD.l < dL))
    if pwOn and tfs < timeframe.in_seconds("W") and not na(wH)
        lv.push(Level.new(wH, "PWH", pwCl, f_anchor(wH, pW.ph, pW.phT, pW.pStartT, firstT), pwW, pwSt, 2, pW.h > wH))
        lv.push(Level.new(wL, "PWL", pwCl, f_anchor(wL, pW.pl, pW.plT, pW.pStartT, firstT), pwW, pwSt, 3, pW.l < wL))
    if pmOn and tfs < timeframe.in_seconds("M") and not na(mH)
        lv.push(Level.new(mH, "PMH", pmCl, f_anchor(mH, pM.ph, pM.phT, pM.pStartT, firstT), pmW, pmSt, 4, pM.h > mH))
        lv.push(Level.new(mL, "PML", pmCl, f_anchor(mL, pM.pl, pM.plT, pM.pStartT, firstT), pmW, pmSt, 5, pM.l < mL))
    if o1On and tfIntra and not na(o1P)
        lv.push(Level.new(o1P, o1Tm, oCl, o1B, oW, oSt, 6))
    if o2On and tfIntra and not na(o2P)
        lv.push(Level.new(o2P, o2Tm, oCl, o2B, oW, oSt, 7))
    if o3On and tfIntra and not na(o3P)
        lv.push(Level.new(o3P, o3Tm, oCl, o3B, oW, oSt, 8))
    if o4On and tfIntra and not na(o4P)
        lv.push(Level.new(o4P, o4Tm, oCl, o4B, oW, oSt, 9))
    if woOn and tfs < timeframe.in_seconds("W") and not na(woP)
        lv.push(Level.new(woP, "WO", woCl, woT, woW, woSt, 10))
    if moOn and tfs < timeframe.in_seconds("M") and not na(moP)
        lv.push(Level.new(moP, "MO", moCl, moT, moW, moSt, 11))
 
    int   tfMs = timeframe.in_seconds() * 1000
    array<int> tierX = array.from(time + OFF_OPEN * tfMs, time + offWM * tfMs, time + offLq * tfMs, time + offLq * tfMs)
    int   n    = math.min(lv.size(), MAXLV)
    float mult = txtSzIn == "Tiny" ? 0.8 : txtSzIn == "Normal" ? 1.4 : 1.0
 
    // ── Step 1: levels at EXACTLY the same price become one item → "PWL = PML"
    //    (order: Day → Week → Month → opening prices by time)
    array<int>    lvItem = array.new<int>(n, 0)
    array<float>  itP    = array.new<float>()
    array<string> itTx   = array.new<string>()
    array<color>  itCl   = array.new<color>()
    array<int>    itPr   = array.new<int>()
    array<int>    itTr   = array.new<int>()
    array<bool>   itSw   = array.new<bool>()
    if n > 0
        array<float> px = array.new<float>()
        for i = 0 to n - 1
            px.push(lv.get(i).price)
        array<int> ord   = px.sort_indices(order.descending)
        float      eqTol = syminfo.mintick * 0.5
        int a = 0
        while a < n
            float bp = lv.get(ord.get(a)).price
            array<int> mem = array.new<int>()
            int b = a
            while b < n and math.abs(lv.get(ord.get(b)).price - bp) < eqTol
                mem.push(ord.get(b))
                b += 1
            array<int> mp = array.new<int>()
            for m in mem
                mp.push(lv.get(m).prio)
            array<int> mi = mp.sort_indices(order.ascending)
            string tx = ""
            for k = 0 to mi.size() - 1
                Level mv = lv.get(mem.get(mi.get(k)))
                tx := k == 0 ? mv.name : tx + " = " + mv.name
            Level lead = lv.get(mem.get(mi.get(0)))
            int   tr   = 0
            bool  sw   = true
            for m in mem
                tr := math.max(tr, f_tier(lv.get(m).prio))
                sw := sw and lv.get(m).swept
            int itIdx = itP.size()
            itP.push(bp)
            itTx.push(tx)
            itCl.push(lead.col)
            itPr.push(lead.prio)
            itTr.push(tr)
            itSw.push(fadeSw and sw)
            for m in mem
                lvItem.set(m, itIdx)
            a := b
 
    // ── Step 2: within each column (same x), labels of nearby levels are staggered to the right.
    int           nIt     = itP.size()
    array<int>    itLineX = array.new<int>(nIt, 0)
    // Every label is vertically centered on its line.
    array<string> itSt    = array.new<string>(nIt, label.style_label_left)
    float         zone    = nz(atr) * OVERLAP_ATR
    array<int>    cols    = array.new<int>()
    if nIt > 0
        for q = 0 to nIt - 1
            int cx = tierX.get(itTr.get(q))
            if not cols.includes(cx)
                cols.push(cx)
    for cx in cols
        array<int> sub = array.new<int>()
        for q = 0 to nIt - 1
            if tierX.get(itTr.get(q)) == cx
                sub.push(q)
        int ns = sub.size()
        int c0 = 0
        while c0 < ns
            int c1 = c0 + 1
            while c1 < ns and math.abs(itP.get(sub.get(c1)) - itP.get(sub.get(c1 - 1))) <= zone
                c1 += 1
            // Cluster: sorted by priority (Day → Week → Month → Opens); the first stays in
            // the column, the rest step to the right.
            array<int> cp = array.new<int>()
            for q = c0 to c1 - 1
                cp.push(itPr.get(sub.get(q)))
            array<int> co = cp.sort_indices(order.ascending)
            int lineX = cx
            for q = 0 to co.size() - 1
                int ix = sub.get(c0 + co.get(q))
                itLineX.set(ix, lineX)
                int chars = math.max(4, str.length(itTx.get(ix)) + 1)
                int step  = math.max(LBL_GAP, int(math.ceil(chars * LBL_GAP / 4.0 * mult)))
                lineX += step * tfMs
            c0 := c1
 
    // ── Step 3: lines
    for i = 0 to MAXLV - 1
        line ln = lvLines.get(i)
        if i < n
            Level v = lv.get(i)
            ln.set_xy1(v.anchor, v.price)
            ln.set_xy2(itLineX.get(lvItem.get(i)), v.price)
            ln.set_color(fadeSw and v.swept ? f_fadeBy(v.col, swFade) : v.col)
            ln.set_width(v.width)
            ln.set_style(f_style(v.lstyle))
        else
            ln.set_color(C_NONE)
 
    // ── Step 4: labels
    for i = 0 to MAXLV - 1
        label lb = lvLabels.get(i)
        if i < nIt
            lb.set_xy(itLineX.get(i), itP.get(i))
            lb.set_text(itTx.get(i))
            lb.set_textcolor(itSw.get(i) ? f_fadeBy(itCl.get(i), swLblFade) : itCl.get(i))
            lb.set_style(itSt.get(i))
            lb.set_color(C_NONE)
        else
            lb.set_text("")
            lb.set_textcolor(C_NONE)
            lb.set_color(C_NONE)
 
    // Focus overlay
    int  rightT = dimMode == F_DAY ? dayStartT : weekStartT
    bool fOn    = dimOn and timeframe.isintraday and not na(rightT)
    color dc = color.new(chart.bg_color, 100 - dimOpac)
    // Margin around the current price so the 1 px price line sits fully inside the fill
    // (a fill edge exactly at the price leaves part of the line uncovered). The margin follows
    // the price range of the dimmed days (≈ the visible range), so it stays a few pixels tall
    // when zoomed out, and never less than half an ATR when zoomed in.
    float spanHi = dimHis.size() > 0 ? dimHis.max() : na
    float spanLo = dimLos.size() > 0 ? dimLos.min() : na
    float pxPad  = math.max(nz(atr) * 0.5, nz(math.max(spanHi, close) - math.min(spanLo, close)) * 0.01)
    for [fi, f] in dimFills
        bool dimIt = fOn and f.get_line1().get_x2() <= rightT
        f.set_color(dimIt ? dc : C_NONE)
        if dimIt
            // Stretch to the current price only: it is already on screen, so auto scale is unaffected.
            f.get_line1().set_y1(math.max(dimHis.get(fi), close + pxPad))
            f.get_line1().set_y2(math.max(dimHis.get(fi), close + pxPad))
            f.get_line2().set_y1(math.min(dimLos.get(fi), close - pxPad))
            f.get_line2().set_y2(math.min(dimLos.get(fi), close - pxPad))
        else
            f.get_line1().set_y1(dimHis.get(fi))
            f.get_line1().set_y2(dimHis.get(fi))
            f.get_line2().set_y1(dimLos.get(fi))
            f.get_line2().set_y2(dimLos.get(fi))
    // Separators: today only with Focus Mode · Current Day; otherwise the whole current week.
    bool onlyToday = fOn and dimMode == F_DAY
    for sl in seps
        sl.set_color(onlyToday and sl.get_x1() < rightT ? C_NONE : sepCl)
 
    // Fade killzones behind the overlay (restored when Focus Mode is off)
    kz1.fade(fOn, rightT)
    kz2.fade(fOn, rightT)
    kz3.fade(fOn, rightT)
    kz4.fade(fOn, rightT)
    kz5.fade(fOn, rightT)

← 返回列表