Period Boundaries + Tail Zones (Refined)

coolrishu · study · 529 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
indicator("Period Boundaries + Tail Zones (Refined)", "DHANONE3 Time Zones", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)
 
// ─────────────────────────────── helpers ───────────────────────────────
f_style(simple string s) => s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
f_box_style(simple string s) => s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
f_size(simple string s)  => s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : size.large
f_dur(float sec)         => sec >= 86400 ? str.tostring(sec / 86400, "#.##") + " d" : sec >= 3600 ? str.tostring(sec / 3600, "#.##") + " h" : str.tostring(sec / 60, "#.##") + " min"
f_hm(int mins)           => str.format("{0,number,00}:{1,number,00}", mins / 60, mins % 60)
f_tag(simple int k, simple int b) => k == 0 ? "M" : k == 1 ? "W" : k == 2 ? "D" : b % 1440 == 0 ? str.tostring(b / 1440) + "D" : b % 60 == 0 ? str.tostring(b / 60) + "H" : str.tostring(b) + "M"
 
f_advDay(int ts, simple string z) =>
    int c = ts + 86400000
    while dayofweek(c, z) == dayofweek.saturday or dayofweek(c, z) == dayofweek.sunday
        c := c + 86400000
    c
f_fwdWd(int ts, simple string z) =>
    int c = ts
    while dayofweek(c, z) == dayofweek.saturday or dayofweek(c, z) == dayofweek.sunday
        c := c + 86400000
    c
f_backWd(int ts, simple string z) =>
    int c = ts
    while dayofweek(c, z) == dayofweek.saturday or dayofweek(c, z) == dayofweek.sunday
        c := c - 86400000
    c
 
// ───────────────────────────── ① mapping ─────────────────────────────
string GM = "① Mapping"
mode      = input.string("Auto (by chart TF)", "Mode", options = ["Auto (by chart TF)", "Manual"], group = GM)
manAnchor = input.timeframe("60", "Manual · anchor TF", group = GM)
manTail   = input.float(15, "Manual · tail length (minutes)", minval = 0.1, group = GM)
ovr1      = input.float(0, "Override primary tail (minutes, 0 = default)", minval = 0, group = GM)
ovr2      = input.float(0, "Override secondary tail (minutes, 0 = default)", minval = 0, group = GM)
dedupe    = input.bool(true, "1-min: hide 15-min line where the 1-H line falls", group = GM)
infoOn    = input.bool(true, "Show info panel", group = GM)
 
// ───────────────── ② session start (auto per instrument) ─────────────────
string GC = "② Session start"
calInput  = input.bool(true, "Anchor intraday periods to session start", group = GC)
srcMode   = input.string("Auto — detect from instrument", "Open time source", options = ["Auto — detect from instrument", "Preset · India 09:15 IST", "Preset · COMEX / NYMEX 03:30 IST", "Preset · US equities 19:00 IST", "Preset · MCX 09:00 IST", "Manual — hour/minute below"], group = GC)
indiaRule = input.bool(true, "Force 09:15 IST for Indian symbols (incl. GIFT Nifty)", group = GC)
startH    = input.int(9,  "Manual · hour",  minval = 0, maxval = 23, group = GC, inline = "st")
startM    = input.int(15, ":  minute",      minval = 0, maxval = 59, group = GC, inline = "st")
tz        = input.string("Asia/Kolkata", "Timezone", group = GC, options = ["Asia/Kolkata", "Asia/Dubai", "Asia/Singapore", "Asia/Tokyo", "Europe/London", "America/New_York", "UTC"])
 
// ───────────────────────────── ③ primary line ─────────────────────────────
string G1 = "③ Primary boundary line"
l1On   = input.bool(true, "Show primary lines", group = G1)
l1Col  = input.color(#2962FF, "Colour", group = G1, inline = "p1")
l1Tr   = input.int(0, "Transp %", minval = 0, maxval = 100, group = G1, inline = "p1")
l1W    = input.int(2, "Thickness", minval = 1, maxval = 8, group = G1, inline = "p2")
l1Sty  = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], group = G1, inline = "p2")
l1Keep = input.int(80, "Max primary lines kept", minval = 1, maxval = 240, group = G1)
 
// ─────────────────── ④ secondary line (1-min chart only) ───────────────────
string G2 = "④ Secondary line  (1-min chart → 1-H boundary)"
l2On   = input.bool(true, "Show secondary lines", group = G2)
l2Col  = input.color(#FF6D00, "Colour", group = G2, inline = "s1")
l2Tr   = input.int(0, "Transp %", minval = 0, maxval = 100, group = G2, inline = "s1")
l2W    = input.int(3, "Thickness", minval = 1, maxval = 8, group = G2, inline = "s2")
l2Sty  = input.string("Dashed", "Style", options = ["Solid", "Dashed", "Dotted"], group = G2, inline = "s2")
l2Keep = input.int(40, "Max secondary lines kept", minval = 1, maxval = 240, group = G2)
 
// ───────────────────────────── ⑤ line tags ─────────────────────────────
string GT = "⑤ Line tags"
tagOn    = input.bool(true, "Show tag text on lines", group = GT)
tagPos   = input.string("Top (above bar)", "Position", options = ["Top (above bar)", "Bottom (below bar)"], group = GT)
tagStyle = input.string("Tag", "Look", options = ["Tag", "Text only"], group = GT)
tagSize  = input.string("Tiny", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = GT)
tagUseLn = input.bool(true, "Use line colour for tag", group = GT)
tagCol   = input.color(color.white, "Custom tag colour", group = GT)
tagPre1  = input.string("", "Primary tag override (blank = auto)", group = GT)
tagPre2  = input.string("", "Secondary tag override (blank = auto)", group = GT)
 
// ───────────────────────────── ⑥ tail zones ─────────────────────────────
string GZ = "⑥ Tail zones"
zOn      = input.bool(true, "Show tail zones", group = GZ)
zKeep    = input.int(12, "Number of tail zones to show", minval = 1, maxval = 200, group = GZ)
zOnlyNxt = input.bool(false, "Show only the current / upcoming tail zone", group = GZ)
z1Col    = input.color(#2962FF, "Primary zone", group = GZ, inline = "z1")
z1Tr     = input.int(88, "Transp %", minval = 0, maxval = 100, group = GZ, inline = "z1")
z2Col    = input.color(#FF6D00, "Secondary zone", group = GZ, inline = "z2")
z2Tr     = input.int(90, "Transp %", minval = 0, maxval = 100, group = GZ, inline = "z2")
zBordOn  = input.bool(false, "Zone border", group = GZ, inline = "z3")
zBordW   = input.int(1, "Width", minval = 1, maxval = 4, group = GZ, inline = "z3")
zBordSty = input.string("Solid", "Border Style Choice", options = ["Solid", "Dashed", "Dotted"], group = GZ, inline = "z4")
 
// ──────────────────── ⑦ upcoming (projected ahead of price) ────────────────────
string GP = "⑦ Upcoming / projected"
pL1     = input.int(1, "Upcoming primary lines",        minval = 0, maxval = 50, group = GP, inline = "q1")
pZ1     = input.int(1, "· tail zones",                  minval = 0, maxval = 50, group = GP, inline = "q1")
pL2     = input.int(1, "Upcoming secondary lines (1m)", minval = 0, maxval = 50, group = GP, inline = "q2")
pZ2     = input.int(1, "· tail zones",                  minval = 0, maxval = 50, group = GP, inline = "q2")
pExtraTr= input.int(35, "Extra transparency on projected items %", minval = 0, maxval = 100, group = GP)
pStyOn  = input.bool(true, "Override projected line style", group = GP, inline = "q3")
pSty    = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], group = GP, inline = "q3")
pTagOn  = input.bool(true, "Tag projected lines", group = GP)
 
// ──────────────── ⑧ zone height & chart scale (v5 fix) ────────────────
string GS = "⑧ Zone height & chart scale"
zRender = input.string("Boxes · recent range", "Zone rendering", options = ["Boxes · recent range", "Boxes · full history", "Background fill (no scale impact)"], group = GS)
zLook   = input.int(300, "Recent range lookback (bars)", minval = 20, maxval = 5000, group = GS)
zPad    = input.float(0.15, "Zone overshoot × range", minval = 0, maxval = 3, step = 0.05, group = GS)
 
// ───────────────── ⑨ HTF Levels & Dynamic Switches (NEW Upgrade) ─────────────────
string G_HTF = "⑨ HTF Open/High/Low & Liquidity Levels"
showHTF      = input.bool(true, "Show PDH/PDL, PWH/PWL & 4H Levels", group = G_HTF)
showLiq      = input.bool(true, "Show Nearest Liquidity Level", group = G_HTF)
daysBack     = input.int(1, "PDH/PDL Multi-Day Horizon (1=Prev Day, 2=2 Days Ago, etc.)", minval=1, maxval=10, group=G_HTF)
weeksBack    = input.int(1, "PWH/PWL Multi-Week Horizon (1=Prev Week, 2=2 Weeks Ago, etc.)", minval=1, maxval=10, group=G_HTF)
 
// Color switches (Above vs Below active market price)
c_above      = input.color(color.red, "Levels Colour (Above Price)", group = G_HTF)
c_below      = input.color(color.green, "Levels Colour (Below Price)", group = G_HTF)
liqCol       = input.color(color.aqua, "Liquidity Levels Colour", group = G_HTF)
liqLookback  = input.int(50, "Liquidity Pivot Lookback", minval = 5, maxval = 200, group = G_HTF)
 
// ─────────────────────────── TF detection & map ───────────────────────────
int  cs   = timeframe.in_seconds()
bool is1D = cs == 86400
bool is4H = cs == 14400
bool is1H = cs == 3600
bool is15 = cs == 900
bool is5  = cs == 300
bool is1  = cs == 60
bool autoOk = is1D or is4H or is1H or is15 or is5 or is1
bool manual = mode == "Manual"
bool active = manual or autoOk
bool useSec = not manual and is1
bool calOn  = calInput and timeframe.isintraday
 
int    manSec = timeframe.in_seconds(manAnchor)
string A1 = manual ? manAnchor : is1D ? "1M" : is4H ? "1W" : is1H ? "1D" : is15 ? "240" : is5 ? "60" : is1 ? "15" : timeframe.period
string A2 = useSec ? "60" : timeframe.period
 
int K1 = manual ? (manSec >= 2419200 ? 0 : manSec >= 604800 ? 1 : manSec >= 86400 ? 2 : 3) : is1D ? 0 : is4H ? 1 : is1H ? 2 : 3
int B1 = manual ? math.round(manSec / 60) : is15 ? 240 : is5 ? 60 : is1 ? 15 : 0
int B1e = K1 == 2 ? 1440 : K1 == 3 ? B1 : 0
int K2 = 3
int B2e = useSec ? 60 : 0
 
float d1 = manual ? manTail * 60 : is1D ? 7 * 86400 : is4H ? 86400 : is1H ? 3600 : is15 ? 1800 : is5 ? 900 : is1 ? 240 : 0
float T1 = ovr1 > 0 ? ovr1 * 60 : d1
float T2 = ovr2 > 0 ? ovr2 * 60 : (useSec ? 900 : 0)
 
// ════════════ AUTO-DETECTED SESSION OPEN ════════════
int dayOpen = request.security(syminfo.tickerid, "1D", time,       lookahead = barmerge.lookahead_on)
int dayEnd  = request.security(syminfo.tickerid, "1D", time_close, lookahead = barmerge.lookahead_on)
 
bool isPreset = str.startswith(srcMode, "Preset")
string tzEff  = isPreset ? "Asia/Kolkata" : tz          
 
bool isMcx   = str.contains(syminfo.prefix, "MCX")
bool isIndia = not isMcx and (str.contains(syminfo.prefix, "NSE") or str.contains(syminfo.prefix, "BSE") or str.contains(syminfo.ticker, "GIFT") or syminfo.timezone == "Asia/Kolkata")
 
int detMins = na(dayOpen) ? na : hour(dayOpen, tzEff) * 60 + minute(dayOpen, tzEff)
int startMins = srcMode == "Manual — hour/minute below"     ? startH * 60 + startM :
   srcMode == "Preset · India 09:15 IST"                    ? 555  :
   srcMode == "Preset · COMEX / NYMEX 03:30 IST"            ? 210  :
   srcMode == "Preset · US equities 19:00 IST"              ? 1140 :
   srcMode == "Preset · MCX 09:00 IST"                      ? 540  :
   (indiaRule and isIndia ? 555 : nz(detMins, 555))
int startHe = startMins / 60
int startMe = startMins % 60
 
// ───────────────────── calibrated session grid ─────────────────────
int minsOfDay = hour(time, tzEff) * 60 + minute(time, tzEff)
int adjTime   = minsOfDay >= startMins ? time : time - 86400000     
int sessDayId = year(adjTime, tzEff) * 10000 + month(adjTime, tzEff) * 100 + dayofmonth(adjTime, tzEff)
bool newDay   = active and sessDayId != nz(sessDayId[1], sessDayId)
int minsFrom  = (minsOfDay - startMins + 1440) % 1440
int bi1 = B1e > 0 ? int(math.floor(minsFrom / B1e)) : 0
int bi2 = B2e > 0 ? int(math.floor(minsFrom / B2e)) : 0
 
var int prevDow = na
bool calNewWeek = false
if newDay
    int dw = dayofweek(adjTime, tzEff)
    calNewWeek := na(prevDow) or dw <= prevDow
    prevDow := dw
int  monthId    = year(adjTime, tzEff) * 100 + month(adjTime, tzEff)
bool calNewMnth = newDay and monthId != nz(monthId[1], monthId)
 
bool calNew1 = K1 == 0 ? calNewMnth : K1 == 1 ? calNewWeek : K1 == 2 ? newDay : (newDay or bi1 != nz(bi1[1], bi1))
bool calNew2 = useSec and (newDay or bi2 != nz(bi2[1], bi2))
 
// ───────────────────── boundary events ─────────────────────
bool ev1 = active and (calOn ? calNew1 : timeframe.change(A1))
bool ev2 = useSec and (calOn ? calNew2 : timeframe.change(A2))
 
var int blk1 = na
var int blk2 = na
if ev1
    blk1 := time
if ev2
    blk2 := time
 
// ───────────────────── period close timestamps ─────────────────────
int natEnd1 = request.security(syminfo.tickerid, A1, time_close, lookahead = barmerge.lookahead_on)
int natEnd2 = request.security(syminfo.tickerid, A2, time_close, lookahead = barmerge.lookahead_on)
 
int end1 = natEnd1
if calOn and B1e > 0 and not na(blk1)
    int ce = blk1 + B1e * 60000
    end1 := not na(dayEnd) and dayEnd < ce and dayEnd > blk1 ? dayEnd : ce
int end2 = natEnd2
if calOn and B2e > 0 and not na(blk2)
    int ce2 = blk2 + B2e * 60000
    end2 := not na(dayEnd) and dayEnd < ce2 and dayEnd > blk2 ? dayEnd : ce2
 
// ───────────────────── in-zone state ─────────────────────
bool in1 = active and T1 > 0 and not na(end1) and time_close > end1 - T1 * 1000
bool in2 = useSec and T2 > 0 and not na(end2) and time_close > end2 - T2 * 1000
bool zBg   = zRender == "Background fill (no scale impact)"
bool z1New = zOn and not zBg and in1 and not in1[1]
bool z2New = zOn and not zBg and in2 and not in2[1]
 
// ───────────────────── drawing: lines + tags ─────────────────────
bool drawSec = l2On and ev2
bool drawPri = l1On and ev1 and not (dedupe and drawSec)
 
string tag1 = tagPre1 == "" ? f_tag(K1, B1e) : tagPre1
string tag2 = tagPre2 == "" ? f_tag(K2, B2e) : tagPre2
bool   tagUp = tagPos == "Top (above bar)"
 
var array<line>  ln1 = array.new<line>()
var array<line>  ln2 = array.new<line>()
var array<label> lb1 = array.new<label>()
var array<label> lb2 = array.new<label>()
 
f_tagNew(string txt, color c) =>
    label.new(bar_index, tagUp ? high : low, txt, xloc = xloc.bar_index, yloc = tagUp ? yloc.abovebar : yloc.belowbar, style = tagStyle == "Tag" ? (tagUp ? label.style_label_down : label.style_label_up) : label.style_none, color = tagStyle == "Tag" ? c : color.new(color.black, 100), textcolor = tagStyle == "Tag" ? color.white : c, size = f_size(tagSize))
 
if drawSec
    line l = line.new(bar_index, low, bar_index, high, xloc = xloc.bar_index, extend = extend.both, color = color.new(l2Col, l2Tr), style = f_style(l2Sty), width = l2W)
    array.push(ln2, l)
    if array.size(ln2) > l2Keep
        line.delete(array.shift(ln2))
    if tagOn
        array.push(lb2, f_tagNew(tag2, tagUseLn ? l2Col : tagCol))
        if array.size(lb2) > l2Keep
            label.delete(array.shift(lb2))
 
if drawPri
    line l = line.new(bar_index, low, bar_index, high, xloc = xloc.bar_index, extend = extend.both, color = color.new(l1Col, l1Tr), style = f_style(l1Sty), width = l1W)
    array.push(ln1, l)
    if array.size(ln1) > l1Keep
        line.delete(array.shift(ln1))
    if tagOn
        array.push(lb1, f_tagNew(tag1, tagUseLn ? l1Col : tagCol))
        if array.size(lb1) > l1Keep
            label.delete(array.shift(lb1))
 
// ═════════════ ⑧ SCALE-SAFE ZONE EXTENTS (v5) ═════════════
var float hiA = na
var float loA = na
hiA := math.max(nz(hiA, high), high)
loA := math.min(nz(loA, low),  low)
 
float rHi = zRender == "Boxes · full history" ? hiA : nz(ta.highest(high, zLook), hiA)
float rLo = zRender == "Boxes · full history" ? loA : nz(ta.lowest(low,   zLook), loA)
float rng = math.max(rHi - rLo, syminfo.mintick * 10)
float topY = rHi + rng * zPad
float botY = math.max(rLo - rng * zPad, math.max(rLo * 0.5, syminfo.mintick))   
 
var array<box> zb1 = array.new<box>()
var array<box> zb2 = array.new<box>()
 
if zOnlyNxt and ev1
    while array.size(zb1) > 0
        box.delete(array.shift(zb1))
if zOnlyNxt and ev2
    while array.size(zb2) > 0
        box.delete(array.shift(zb2))
 
// ═════════════ MODIFICATION: DYNAMIC CUSTOMIZABLE BORDER STYLES ═════════════
if z2New
    box b = box.new(int(end2 - T2 * 1000), topY, end2, botY, xloc = xloc.bar_time, bgcolor = color.new(z2Col, z2Tr), border_color = zBordOn ? color.new(z2Col, math.max(z2Tr - 30, 0)) : color.new(color.black, 100), border_width = zBordOn ? zBordW : 0, border_style = f_box_style(zBordSty))
    array.push(zb2, b)
    if array.size(zb2) > zKeep
        box.delete(array.shift(zb2))
 
if z1New
    box b = box.new(int(end1 - T1 * 1000), topY, end1, botY, xloc = xloc.bar_time, bgcolor = color.new(z1Col, z1Tr), border_color = zBordOn ? color.new(z1Col, math.max(z1Tr - 30, 0)) : color.new(color.black, 100), border_width = zBordOn ? zBordW : 0, border_style = f_box_style(zBordSty))
    array.push(zb1, b)
    if array.size(zb1) > zKeep
        box.delete(array.shift(zb1))
 
if barstate.islast
    if array.size(zb1) > 0
        for i = 0 to array.size(zb1) - 1
            box.set_top(array.get(zb1, i), topY)
            box.set_bottom(array.get(zb1, i), botY)
    if array.size(zb2) > 0
        for i = 0 to array.size(zb2) - 1
            box.set_top(array.get(zb2, i), topY)
            box.set_bottom(array.get(zb2, i), botY)
 
bgcolor(zBg and zOn and in1 ? color.new(z1Col, z1Tr) : na, title = "Primary tail zone (bg)")
bgcolor(zBg and zOn and in2 ? color.new(z2Col, z2Tr) : na, title = "Secondary tail zone (bg)")
 
// ══════════════════ ⑦ PROJECTION OF UPCOMING ITEMS ══════════════════
var array<line>  pln1 = array.new<line>()
var array<label> plb1 = array.new<label>()
var array<box>   pzb1 = array.new<box>()
var array<line>  pln2 = array.new<line>()
var array<label> plb2 = array.new<label>()
var array<box>   pzb2 = array.new<box>()
 
f_pLine(int ts, color c, int tr, simple string sty, int w, array<line> la) =>
    array.push(la, line.new(ts, low, ts, high, xloc = xloc.bar_time, extend = extend.both, color = color.new(c, math.min(tr + pExtraTr, 100)), style = f_style(pStyOn ? pSty : sty), width = w))
 
f_pTag(int ts, string txt, color c, array<label> la) =>
    if pTagOn and tagOn
        array.push(la, label.new(ts, tagUp ? high : low, txt, xloc = xloc.bar_time, yloc = yloc.price, style = tagStyle == "Tag" ? (tagUp ? label.style_label_down : label.style_label_up) : label.style_none, color = tagStyle == "Tag" ? color.new(c, math.min(pExtraTr, 90)) : color.new(color.black, 100), textcolor = tagStyle == "Tag" ? color.white : color.new(c, math.min(pExtraTr, 90)), size = f_size(tagSize)))
 
f_pZone(int zs, int ze, color c, int tr, array<box> ba) =>
    array.push(ba, box.new(zs, topY, ze, botY, xloc = xloc.bar_time, bgcolor = color.new(c, math.min(tr + pExtraTr, 100)), border_color = zBordOn ? color.new(c, math.min(tr, 100)) : color.new(color.black, 100), border_width = zBordOn ? zBordW : 0, border_style = f_box_style(zBordSty)))
 
f_projGrid(int blkStart, int sessStart, int sessLen, int blockMin, float tailSec, int nL, int nZ, color lc, int ltr, simple string lsty, int lw, string tg, color zc, int ztr, array<line> la, array<label> lba, array<box> ba) =>
    int sS = sessStart
    int bS = na(blkStart) ? sessStart : blkStart
    int nl = 0
    int nz = 0
    if blockMin > 0
        for i = 0 to 400
            int sE = sS + sessLen
            int gE = bS + blockMin * 60000
            int bE = gE < sE ? gE : sE
            int zs = int(bE - tailSec * 1000)
            if nz < nZ and tailSec > 0 and zs > time_close
                f_pZone(zs, bE, zc, ztr, ba)
                nz += 1
            if gE >= sE
                sS := f_advDay(sS, tzEff)
                bS := sS
            else
                bS := gE
            if nl < nL and bS > time_close
                f_pLine(bS, lc, ltr, lsty, lw, la)
                f_pTag(bS, tg, lc, lba)
                nl += 1
            if nl >= nL and nz >= nZ
                break
    true
 
if barstate.islast
    while array.size(pln1) > 0
        line.delete(array.shift(pln1))
    while array.size(plb1) > 0
        label.delete(array.shift(plb1))
    while array.size(pzb1) > 0
        box.delete(array.shift(pzb1))
    while array.size(pln2) > 0
        line.delete(array.shift(pln2))
    while array.size(plb2) > 0
        label.delete(array.shift(plb2))
    while array.size(pzb2) > 0
        box.delete(array.shift(pzb2))
 
    int refT   = calOn ? adjTime : time
    int curSS  = timestamp(tzEff, year(refT, tzEff), month(refT, tzEff), dayofmonth(refT, tzEff), startHe, startMe)
    int sessLn = not na(dayEnd) and dayEnd > curSS ? dayEnd - curSS : 23400000   
    int nZ1    = (zOn and not zBg) ? pZ1 : 0
    int nZ2    = (zOn and not zBg) ? pZ2 : 0
 
    if active and (pL1 > 0 or nZ1 > 0)
        if K1 >= 2                                     
            f_projGrid(blk1, curSS, sessLn, B1e, T1, l1On ? pL1 : 0, nZ1, l1Col, l1Tr, l1Sty, l1W, tag1, z1Col, z1Tr, pln1, plb1, pzb1)
        else if K1 == 1                                
            int dowN = dayofweek(refT, tzEff)
            int back = dowN == dayofweek.sunday ? 6 : dowN - 2
            int monS = curSS - back * 86400000
            int nl = 0
            int nz = 0
            for k = 0 to 60
                int wS = monS + k * 7 * 86400000
                int wE = wS + 4 * 86400000 + sessLn
                int zs = int(wE - T1 * 1000)
                if nz < nZ1 and T1 > 0 and zs > time_close
                    f_pZone(zs, wE, z1Col, z1Tr, pzb1)
                    nz += 1
                if nl < (l1On ? pL1 : 0) and wS > time_close and k > 0
                    int ws2 = f_fwdWd(wS, tzEff)
                    f_pLine(ws2, l1Col, l1Tr, l1Sty, l1W, pln1)
                    f_pTag(ws2, tag1, l1Col, plb1)
                    nl += 1
                if nl >= (l1On ? pL1 : 0) and nz >= nZ1
                    break
        else                                           
            int y0 = year(refT, tzEff)
            int m0 = month(refT, tzEff)
            int nl = 0
            int nz = 0
            for k = 0 to 36
                int mS = f_fwdWd(timestamp(tzEff, y0, m0 + k, 1, startHe, startMe), tzEff)
                int mE = f_backWd(timestamp(tzEff, y0, m0 + k + 1, 1, startHe, startMe) - 86400000, tzEff) + sessLn
                int zs = int(mE - T1 * 1000)
                if nz < nZ1 and T1 > 0 and zs > time_close
                    f_pZone(zs, mE, z1Col, z1Tr, pzb1)
                    nz += 1
                if nl < (l1On ? pL1 : 0) and mS > time_close
                    f_pLine(mS, l1Col, l1Tr, l1Sty, l1W, pln1)
                    f_pTag(mS, tag1, l1Col, plb1)
                    nl += 1
                if nl >= (l1On ? pL1 : 0) and nz >= nZ1
                    break
 
    if useSec and (pL2 > 0 or nZ2 > 0)
        f_projGrid(blk2, curSS, sessLn, B2e, T2, l2On ? pL2 : 0, nZ2, l2Col, l2Tr, l2Sty, l2W, tag2, z2Col, z2Tr, pln2, plb2, pzb2)
 
// ══════════════════ ⑨ HTF Levels & Dynamic Switches (Refined) ══════════════════
var line htfLine1 = na, var line htfLine2 = na
var line htfLine3 = na, var line htfLine4 = na
var line htfLine5 = na, var line htfLine6 = na
var line liqLine = na
 
// Multi-day & Multi-week data loading using dynamic history index offsets
float pdh = request.security(syminfo.tickerid, "1D", high[daysBack], lookahead = barmerge.lookahead_on)
float pdl = request.security(syminfo.tickerid, "1D", low[daysBack], lookahead = barmerge.lookahead_on)
float pwh = request.security(syminfo.tickerid, "1W", high[weeksBack], lookahead = barmerge.lookahead_on)
float pwl = request.security(syminfo.tickerid, "1W", low[weeksBack], lookahead = barmerge.lookahead_on)
float h4h = request.security(syminfo.tickerid, "240", high[1], lookahead = barmerge.lookahead_on)
float h4l = request.security(syminfo.tickerid, "240", low[1], lookahead = barmerge.lookahead_on)
 
// Calculate dynamic nearest liquidity levels using structural pivot points
float pivotHi = ta.pivothigh(high, liqLookback, liqLookback)
float pivotLo = ta.pivotlow(low, liqLookback, liqLookback)
 
var float activeUpperLiq = na
var float activeLowerLiq = na
 
if not na(pivotHi)
    activeUpperLiq := pivotHi
if not na(pivotLo)
    activeLowerLiq := pivotLo
 
// Find which liquidity pool is strictly closer to the current close
float nearLiquidity = na
if not na(activeUpperLiq) and not na(activeLowerLiq)
    nearLiquidity := math.abs(close - activeUpperLiq) < math.abs(close - activeLowerLiq) ? activeUpperLiq : activeLowerLiq
else if not na(activeUpperLiq)
    nearLiquidity := activeUpperLiq
else if not na(activeLowerLiq)
    nearLiquidity := activeLowerLiq
 
// FIX CW10002: Evaluate cross state globally outside condition blocks
bool crossPDH = ta.cross(close, pdh)
bool crossPDL = ta.cross(close, pdl)
bool crossPWH = ta.cross(close, pwh)
bool crossPWL = ta.cross(close, pwl)
bool crossH4H = ta.cross(close, h4h)
bool crossH4L = ta.cross(close, h4l)
bool crossLiq = not na(nearLiquidity) ? ta.cross(close, nearLiquidity) : false
 
// Handle real-time plot updates via lines to clear past artifacts cleanly
if barstate.islast
    if showHTF
        line.delete(htfLine1), line.delete(htfLine2)
        line.delete(htfLine3), line.delete(htfLine4)
        line.delete(htfLine5), line.delete(htfLine6)
        
        // Dynamically shift color based on above/below current market execution
        color colPDH = pdh > close ? c_above : c_below
        color colPDL = pdl > close ? c_above : c_below
        color colPWH = pwh > close ? c_above : c_below
        color colPWL = pwl > close ? c_above : c_below
        color colH4H = h4h > close ? c_above : c_below
        color colH4L = h4l > close ? c_above : c_below
 
        // Build customized multi-day / multi-week contextual strings
        string strPDH = "D" + str.tostring(daysBack) + " H"
        string strPDL = "D" + str.tostring(daysBack) + " L"
        string strPWH = "W" + str.tostring(weeksBack) + " H"
        string strPWL = "W" + str.tostring(weeksBack) + " L"
 
        // Render Dynamic Lines
        htfLine1 := line.new(x1 = bar_index - 50, y1 = pdh, x2 = bar_index + 10, y2 = pdh, color = colPDH, width = 1, style = line.style_solid)
        htfLine2 := line.new(x1 = bar_index - 50, y1 = pdl, x2 = bar_index + 10, y2 = pdl, color = colPDL, width = 1, style = line.style_solid)
        label.new(bar_index + 10, pdh, strPDH, textcolor = colPDH, style = label.style_none, size = size.small)
        label.new(bar_index + 10, pdl, strPDL, textcolor = colPDL, style = label.style_none, size = size.small)
 
        htfLine3 := line.new(x1 = bar_index - 40, y1 = pwh, x2 = bar_index + 8, y2 = pwh, color = colPWH, width = 1, style = line.style_dashed)
        htfLine4 := line.new(x1 = bar_index - 40, y1 = pwl, x2 = bar_index + 8, y2 = pwl, color = colPWL, width = 1, style = line.style_dashed)
        label.new(bar_index + 8, pwh, strPWH, textcolor = colPWH, style = label.style_none, size = size.small)
        label.new(bar_index + 8, pwl, strPWL, textcolor = colPWL, style = label.style_none, size = size.small)
 
        htfLine5 := line.new(x1 = bar_index - 30, y1 = h4h, x2 = bar_index + 5, y2 = h4h, color = colH4H, width = 1, style = line.style_dotted)
        htfLine6 := line.new(x1 = bar_index - 30, y1 = h4l, x2 = bar_index + 5, y2 = h4l, color = colH4L, width = 1, style = line.style_dotted)
        label.new(bar_index + 5, h4h, "4H H", textcolor = colH4H, style = label.style_none, size = size.small)
        label.new(bar_index + 5, h4l, "4H L", textcolor = colH4L, style = label.style_none, size = size.small)
 
    if showLiq and not na(nearLiquidity)
        line.delete(liqLine)
        // FIX CE10272: Standardized line style used instead of invalid line.style_double
        liqLine := line.new(x1 = bar_index - liqLookback, y1 = nearLiquidity, x2 = bar_index + 15, y2 = nearLiquidity, color = liqCol, width = 2, style = line.style_solid)
        label.new(bar_index + 15, nearLiquidity, "Nearest Liq", textcolor = liqCol, style = label.style_none, size = size.small)
 
// ───────────────────────────── info panel ─────────────────────────────
var table t = na
if infoOn and barstate.islast
    if na(t)
        t := table.new(position.top_right, 2, 8, bgcolor = color.new(color.black, 75), border_color = color.new(color.gray, 60), border_width = 1)
    table.cell(t, 0, 0, "Chart TF",  text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 0, timeframe.period + (manual ? " · manual" : ""), text_color = color.white, text_size = size.tiny)
    table.cell(t, 0, 1, "Opens",     text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 1, f_hm(startMins) + " " + tzEff + (isPreset ? " · preset" : srcMode == "Manual — hour/minute below" ? " · manual" : indiaRule and isIndia ? " · India rule" : " · detected"), text_color = calOn ? color.white : color.gray, text_size = size.tiny)
    table.cell(t, 0, 2, "Line",      text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 2, active ? tag1 + " open" : "unsupported TF", text_color = active ? l1Col : color.red, text_size = size.tiny)
    table.cell(t, 0, 3, "Tail",      text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 3, active ? "last " + f_dur(T1) : "—", text_color = l1Col, text_size = size.tiny)
    table.cell(t, 0, 4, "2nd line",  text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 4, useSec ? tag2 + " open" : "—", text_color = useSec ? l2Col : color.gray, text_size = size.tiny)
    table.cell(t, 0, 5, "2nd tail",  text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 5, useSec ? "last " + f_dur(T2) : "—", text_color = useSec ? l2Col : color.gray, text_size = size.tiny)
    table.cell(t, 0, 6, "Zones",     text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 6, not zOn ? "off" : zBg ? "background fill" : zOnlyNxt ? "current only" : "last " + str.tostring(zKeep), text_color = color.white, text_size = size.tiny)
    table.cell(t, 0, 7, "Upcoming",  text_color = color.silver, text_size = size.tiny)
    table.cell(t, 1, 7, str.tostring(pL1) + " line / " + str.tostring(pZ1) + " zone" + (useSec ? "  ·  " + str.tostring(pL2) + " / " + str.tostring(pZ2) : ""), text_color = color.white, text_size = size.tiny)
 
// ───────────────────────────── alerts ─────────────────────────────
alertcondition(ev1, "New primary period", "New primary period opened")
alertcondition(ev2, "New secondary period", "New secondary (1H) period opened")
alertcondition(crossPDH, "PDH Crossed", "Price crossed historical Daily High")
alertcondition(crossPDL, "PDL Crossed", "Price crossed historical Daily Low")
alertcondition(crossPWH, "PWH Crossed", "Price crossed historical Weekly High")
alertcondition(crossPWL, "PWL Crossed", "Price crossed historical Weekly Low")
alertcondition(crossLiq, "Liquidity Swept", "Price touched nearest structural liquidity pool")

← 返回列表