Session Candles [josseliani]

josseliani · study · 773 行 · 点赞 248 · TradingView 原页

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

Pine Script

//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0
// at https://mozilla.org/MPL/2.0/
// © 2026 josseliani
//
// ============================================================================
// SESSION CANDLES
// Author: josseliani
// License: Mozilla Public License 2.0 (MPL-2.0)
// ============================================================================
//
// Each trading session — one candle.
//
// Displays custom session OHLC candles in a screen-anchored mini-chart,
// helping users compare session ranges, sweeps, breaks and Weekly Open.
//
// FEATURES
// • Sequential sessions, equal eight-hour periods or custom time windows.
// • Live session candles, range midpoints and previous-session references.
// • Sweep / break markers based on the session close relative to those levels.
// • Session VWAP and an optional frozen reference from the completed session.
// • Confirmed pivot structure and session-direction BUY / SELL signals.
// • Configurable Kill Zone boxes for visual time context.
// • Optional opening levels, EMA filtering, signal delay and Mobile view.
//
// SIGNAL BEHAVIOR
// Signals require a confirmed structure break on the correct side of VWAP.
// Up to three attempts per session; opposite-direction retries are allowed
// only before the preceding attempt achieves a favorable move of 1 ATR.
// Signals are confirmed at chart-bar close. Kill Zone boxes do not filter them.
//
// DISPLAY NOTES
// Live session candles and their sweep / break markers remain provisional.
// Pivots are confirmed after four bars to the right, then marked on their
// original bars. Signal calculations use them only after confirmation.
//
// USAGE
// Use standard intraday charts of 60 minutes or less with aligned session
// boundaries. VWAP requires usable volume data. Results vary by timeframe.
// Enable "Mobile view" for a smaller mini-chart with shorter captions.
//
// This indicator provides analytical context, not a complete trading system.
// ============================================================================
 
indicator("Session Candles [josseliani]", overlay=true, behind_chart=false, max_lines_count=250, max_boxes_count=100, max_labels_count=500)
// Native screen-anchored session chart. No external drawing library.
// Confirmed BOS + VWAP entries; up to three attempts per session; time boxes are context only.
// Publication candidate 15.1. Confirmed pivots are displayed on their origin bars.
// Window references are captured before the new window's first bar is accumulated.
gS = "Session schedule"
sessionPreset = input.string("Sequential sessions", "Preset", options=["Sequential sessions", "Equal 8-hour windows", "Custom windows"], group=gS)
scheduleTZ = input.string("America/New_York", "Schedule timezone (IANA)", group=gS, tooltip="All candle windows use this clock. America/New_York adjusts for DST. Chart timezone does not change the schedule.")
customAsia = input.session("1800-0200", "Custom window A", group=gS)
customLondon = input.session("0200-0800", "Custom window L", group=gS)
customNY = input.session("0800-1800", "Custom window N", group=gS)
customDayHour = input.int(18, "Custom / equal-window day starts at (hour)", minval=0, maxval=23, group=gS, tooltip="For custom windows, order their starts A, L, N after this boundary. Overlaps are allowed. Evening windows belong to the following trade date.")
windowAName = "Asia"
windowLName = "London"
windowNName = "New York"
f_hh(int h) =>
    str.tostring(h % 24,"00")+"00"
int dayStartHour = sessionPreset == "Sequential sessions" ? 18 : customDayHour
string asiaHours = sessionPreset == "Custom windows" ? customAsia : sessionPreset == "Equal 8-hour windows" ? f_hh(dayStartHour)+"-"+f_hh(dayStartHour+8) : "1800-0200"
string lonHours = sessionPreset == "Custom windows" ? customLondon : sessionPreset == "Equal 8-hour windows" ? f_hh(dayStartHour+8)+"-"+f_hh(dayStartHour+16) : "0200-0800"
string nyHours = sessionPreset == "Custom windows" ? customNY : sessionPreset == "Equal 8-hour windows" ? f_hh(dayStartHour+16)+"-"+f_hh(dayStartHour) : "0800-1800"
string asiaTZ = scheduleTZ
string lonTZ = scheduleTZ
string nyTZ = scheduleTZ
f_start_minutes(string hours) =>
    int(str.tonumber(str.substring(hours,0,2)))*60+int(str.tonumber(str.substring(hours,2,4)))
f_order(string hours) =>
    (f_start_minutes(hours)-dayStartHour*60+1440)%1440
if barstate.isfirst and not (f_order(asiaHours) < f_order(lonHours) and f_order(lonHours) < f_order(nyHours))
    runtime.error("Order window starts A, L, N after the trading-day boundary. End times may overlap.")
asiaColor = input.color(color.rgb(233,184,52), "Asia label / VWAP", group=gS)
lonColor = input.color(color.rgb(171,120,220), "London label / VWAP", group=gS)
nyColor = input.color(color.rgb(112,168,211), "New York label / VWAP", group=gS)
gP = "Session candles"
showPanel = input.bool(true, "Show session mini chart", group=gP)
displayDays = input.int(5, "Trading days to show", minval=1, maxval=8, group=gP, tooltip="Includes the latest available day. Dates without sessions are skipped. Each day reserves three session slots.")
count = displayDays * 3
historyDays = 0
panelPosition = input.string("Top right", "Corner", options=["Top right", "Top left", "Bottom right", "Bottom left"], group=gP)
baseWidth = 40.0
panelWidth = baseWidth * displayDays / 5.0
panelHeight = 30.0
drawingRows = 96
bodyShare = 82.0
showMid = input.bool(true, "Show midpoint on each session candle", group=gP, tooltip="Short light mark at (High + Low) / 2 of each session candle, not the body midpoint. The live candle midpoint moves with its High and Low. Visual only.")
showPrevious = input.bool(true, "Show previous session H / L / 50% guides", group=gP, tooltip="Three gray guides beside the latest session candle: previous session High, Low and their midpoint. Frozen when the latest session starts, including an overlap snapshot. This does not control the main-chart levels or signals.")
mobileMode = input.bool(false, "Mobile view", group=gP, tooltip="Reduces chart width and height by 25%, uses A / L / N captions and a short date once per day.")
compactText = mobileMode
float viewScale = mobileMode ? 0.75 : 1.0
captionSize = mobileMode ? 7 : 8
showRefEvents = input.bool(true, "Mark SWEEP / BREAK on session candles", group=gP, tooltip="Compared with frozen previous-session levels: amber = traded beyond the level, now back at or inside it; blue = current close beyond it. Faded LIVE marks are provisional. Solid CLOSED marks use the final session close. Each side is evaluated separately; no intrabar event order or entry signal is implied. Partial-history candles have no marks.")
showDates = true
bullColor = input.color(#16B89A, "Bullish candle / BUY", group=gP)
bearColor = input.color(#E86071, "Bearish candle / SELL", group=gP)
panelBg = input.color(#11151C, "Chart background", group=gP)
gK = "Kill Zone windows"
useLondonKZ = input.bool(true, "Enable London box", group=gK)
londonKZHours = input.session("0200-0500", "London box hours", group=gK)
useNYKZ = input.bool(true, "Enable New York AM box", group=gK)
nyKZHours = input.session("0830-1100", "New York AM hours", group=gK)
usePMKZ = input.bool(false, "Enable New York PM box", group=gK)
pmKZHours = input.session("1330-1600", "New York PM hours", group=gK)
kzTZ = input.string("America/New_York", "Box timezone (IANA)", group=gK, tooltip="Visual time windows only. They do not create or filter signals and never reset VWAP. America/New_York adjusts automatically for DST.")
showKZBoxes = input.bool(true, "Show time boxes", group=gK)
keepKZBoxes = 10
kzColor = input.color(color.new(#9DAAC8,92), "Box fill", group=gK)
gV = "Main chart: VWAP and levels"
showDailyOpen = input.bool(false, "Show Daily Open", group=gV, tooltip="First available bar of the trading day defined by the session schedule, not calendar midnight.")
showWeeklyOpen = input.bool(true, "Show Weekly Open", group=gV, tooltip="First available bar of the session-based trading week. Shown on the main chart and across that week in the mini chart.")
showPreviousOnChart = input.bool(true, "Show previous session High / Low", group=gV, tooltip="Two fixed reference levels for the active session only. They match its mini-chart references. REF means the previous session was still live when the snapshot was taken.")
showVWAP = input.bool(true, "Show signal VWAP", group=gV)
showH1Open = input.bool(false, "Show H1 Open", group=gV, tooltip="Current one-hour block anchored to the session-day start. Context only.")
showH4Open = input.bool(false, "Show H4 Open", group=gV, tooltip="Current four-hour block anchored to the session-day start. May differ from the standard TradingView H4 candle. Context only.")
showOtherVWAP = false
showFinishedVWAP = input.bool(true, "Keep completed VWAP for 60 minutes", group=gV, tooltip="Freezes the last valid value of the most recently completed session. Gray context line only; no new volume is added and it does not filter signals.")
gE = "Structure and signals"
allowRegular = input.bool(true, "Enable session signals", group=gE, tooltip="Up to three attempts per session. An opposite-direction retry is allowed only before the preceding attempt reaches a favorable move of 1 ATR. Confirmed BOS + VWAP required. Time boxes do not filter entries.")
showSignals = input.bool(true, "Show BUY / SELL badges", group=gE)
labelOffsetATR = 1.5
atrLength = 14
atrMultiple = 1.0
maxAttempts = 3
keepBadges = 150
signalDelay = input.int(0, "Wait after session start (minutes)", minval=0, maxval=180, group=gE, tooltip="BOS events before this time are recorded but never queued as later entries. A new confirmed BOS is required after the wait.")
useEMA = input.bool(false, "EMA filter", group=gE)
showEMA = input.bool(false, "Show EMA line", group=gE, tooltip="Visual only. Hiding the line does not disable the EMA filter.")
emaLength = input.int(21, "EMA length", minval=1, maxval=500, group=gE)
pivotDepth = 4
showStructure = input.bool(true, "Show BOS levels", group=gE)
keepBOS = 40
showPivots = input.bool(true, "Show confirmed pivot dots", group=gE, tooltip="Confirmed after four bars to the right, then drawn on the original pivot bar. Entries never use an unconfirmed pivot.")
if barstate.isfirst and (not chart.is_standard or not timeframe.isintraday or timeframe.in_seconds() > 3600)
    runtime.error("Use a standard intraday chart of 60 minutes or less. 1m / 5m / 15m is recommended.")
// Avoid using a full chart bar that straddles a configured window boundary.
f_aligned(string hours) =>
    float minutes = timeframe.in_seconds()/60.0
    int begin = f_start_minutes(hours)
    int finish = int(str.tonumber(str.substring(hours,5,7)))*60+int(str.tonumber(str.substring(hours,7,9)))
    minutes <= 1 or (begin % minutes == 0 and finish % minutes == 0)
if barstate.isfirst and (not f_aligned(asiaHours) or not f_aligned(lonHours) or not f_aligned(nyHours))
    runtime.error("Window boundaries must align with chart bars. Use 1m / 5m / 15m, or adjust window times.")
type SessionCandle
    float o
    float h
    float l
    float c
    int sid
    int started
    string dateText
    bool live
    bool partial
    int tradeDay = na
    float weekOpen = na
    int weekKey = na
    float refH = na
    float refL = na
    int refSid = -1
    int refStart = na
    bool refOverlap = false
    int highEvent = 0
    int lowEvent = 0
type SessionState
    SessionCandle candle = na
    int key = na
    float pv = 0.0
    float vol = 0.0
    bool badVolume = false
var array<SessionCandle> candles = array.new<SessionCandle>()
var SessionState asia = SessionState.new()
var SessionState london = SessionState.new()
var SessionState newYork = SessionState.new()
// A date-specific key also detects a new session after market/weekend gaps.
f_session_key(string hours, string tz) =>
    int hh = int(str.tonumber(str.substring(hours, 0, 2)))
    int mm = int(str.tonumber(str.substring(hours, 2, 4)))
    int dayShift = hour(time, tz) * 60 + minute(time, tz) < hh * 60 + mm ? 1 : 0
    timestamp(tz, year(time, tz), month(time, tz), dayofmonth(time, tz) - dayShift, hh, mm)
f_session_end(int key, string hours, string tz) =>
    int finish = int(str.tonumber(str.substring(hours,5,7)))*60+int(str.tonumber(str.substring(hours,7,9)))
    int extraDay = finish <= f_start_minutes(hours) ? 1 : 0
    timestamp(tz,year(key,tz),month(key,tz),dayofmonth(key,tz)+extraDay,int(finish/60),finish%60)
f_trade_day(int t) =>
    int shift = dayStartHour > 0 and hour(t,scheduleTZ) >= dayStartHour ? 1 : 0
    timestamp(scheduleTZ,year(t,scheduleTZ),month(t,scheduleTZ),dayofmonth(t,scheduleTZ)+shift,0,0)
// Session-based day and week anchors. Missing market bars are skipped.
// Do not invent an opening price when the loaded history begins mid-period.
int openDayKey = f_session_key(f_hh(dayStartHour)+"-"+f_hh(dayStartHour),scheduleTZ)
int openTradeDate = f_trade_day(time)
int daysFromMonday = (dayofweek(openTradeDate,scheduleTZ)+5)%7
int openWeekKey = timestamp(scheduleTZ,year(openTradeDate,scheduleTZ),month(openTradeDate,scheduleTZ),dayofmonth(openTradeDate,scheduleTZ)-daysFromMonday,0,0)
int openWeekBoundary = timestamp(scheduleTZ,year(openWeekKey,scheduleTZ),month(openWeekKey,scheduleTZ),dayofmonth(openWeekKey,scheduleTZ)-(dayStartHour > 0 ? 1 : 0),dayStartHour,0)
var float dailyOpen = na
var float weeklyOpen = na
var int dailyOpenTime = na
var int weeklyOpenTime = na
if barstate.isfirst or openDayKey != openDayKey[1]
    dailyOpen := not barstate.isfirst or time == openDayKey ? open : na
    dailyOpenTime := not na(dailyOpen) ? time : na
if barstate.isfirst or openWeekKey != openWeekKey[1]
    weeklyOpen := not barstate.isfirst or time == openWeekBoundary ? open : na
    weeklyOpenTime := not na(weeklyOpen) ? time : na
// Local-clock blocks preserve the configured schedule through timezone changes.
f_open_block_key(int blockHours) =>
    int elapsedMinutes = (hour(time,scheduleTZ)*60+minute(time,scheduleTZ)-dayStartHour*60+1440)%1440
    int blockMinutes = dayStartHour*60+int(math.floor(elapsedMinutes/(blockHours*60)))*blockHours*60
    timestamp(scheduleTZ,year(openDayKey,scheduleTZ),month(openDayKey,scheduleTZ),dayofmonth(openDayKey,scheduleTZ)+int(math.floor(blockMinutes/1440)),int(math.floor((blockMinutes%1440)/60)),0)
int h1OpenKey = f_open_block_key(1)
int h4OpenKey = f_open_block_key(4)
var float h1Open = na
var float h4Open = na
var int h1OpenTime = na
var int h4OpenTime = na
if barstate.isfirst or h1OpenKey != h1OpenKey[1]
    h1Open := not barstate.isfirst or time == h1OpenKey ? open : na
    h1OpenTime := not na(h1Open) ? time : na
if barstate.isfirst or h4OpenKey != h4OpenKey[1]
    h4Open := not barstate.isfirst or time == h4OpenKey ? open : na
    h4OpenTime := not na(h4Open) ? time : na
// Search only pre-existing candles. All snapshots are taken before ANY session update.
f_reference(int keyNow) =>
    float rh = na
    float rl = na
    int rt = na
    int rs = -1
    if keyNow > 0 and array.size(candles) > 0
        for i = 0 to array.size(candles)-1
            SessionCandle c = array.get(candles,i)
            if c.started < keyNow and not c.partial and (na(rt) or c.started > rt)
                rh := c.h
                rl := c.l
                rt := c.started
                rs := c.sid
    [rh,rl,rt,rs]
method update(SessionState state, bool inside, int keyNow, int sid, string tz, float rh, float rl, int rt, int rs, bool overlap) =>
    bool fresh = inside and (na(state.key) or keyNow != state.key)
    if fresh
        if not na(state.candle)
            state.candle.live := false
        bool partial = barstate.isfirst and time > keyNow
        state.candle := SessionCandle.new(open, high, low, close, sid, keyNow, str.format_time(keyNow, "dd MMM", tz), true, partial)
        state.candle.tradeDay := f_trade_day(keyNow)
        state.candle.weekOpen := weeklyOpen
        state.candle.weekKey := openWeekKey
        state.candle.dateText := str.format_time(state.candle.tradeDay,"dd MMM",scheduleTZ)
        state.candle.refH := rh
        state.candle.refL := rl
        state.candle.refSid := rs
        state.candle.refStart := rt
        state.candle.refOverlap := overlap
        array.push(candles, state.candle)
        state.key := keyNow
        state.pv := 0.0
        state.vol := 0.0
        state.badVolume := false
    if inside
        state.candle.h := math.max(state.candle.h, high)
        state.candle.l := math.min(state.candle.l, low)
        state.candle.c := close
        state.candle.live := true
        // Session OHLC state, not a sequence of chart-bar breakout badges.
        if not state.candle.partial and not na(state.candle.refH)
            state.candle.highEvent := state.candle.h > state.candle.refH ? (close > state.candle.refH ? 2 : 1) : 0
        if not state.candle.partial and not na(state.candle.refL)
            state.candle.lowEvent := state.candle.l < state.candle.refL ? (close < state.candle.refL ? 2 : 1) : 0
        if na(volume) or volume < 0
            state.badVolume := true
        else
            state.pv += hlc3 * volume
            state.vol += volume
    else if not na(state.candle)
        state.candle.live := false
    float value = inside and not state.badVolume and state.vol > 0 and not state.candle.partial ? state.pv / state.vol : na
    [value, fresh]
bool inAsia = not na(time(timeframe.period, asiaHours, asiaTZ))
bool inLon = not na(time(timeframe.period, lonHours, lonTZ))
bool inNY = not na(time(timeframe.period, nyHours, nyTZ))
int keyA = f_session_key(asiaHours,asiaTZ)
int keyL = f_session_key(lonHours,lonTZ)
int keyN = f_session_key(nyHours,nyTZ)
if (inAsia and (time < keyA or time_close > f_session_end(keyA,asiaHours,asiaTZ))) or (inLon and (time < keyL or time_close > f_session_end(keyL,lonHours,lonTZ))) or (inNY and (time < keyN or time_close > f_session_end(keyN,nyHours,nyTZ)))
    runtime.error("A chart bar crosses a session boundary. Use a lower timeframe or align the session hours with this feed's bars.")
// Avoid scanning history on every bar unless a new window actually starts.
bool freshA = inAsia and (na(asia.key) or asia.key != keyA)
bool freshL = inLon and (na(london.key) or london.key != keyL)
bool freshN = inNY and (na(newYork.key) or newYork.key != keyN)
[rah,ral,rat,ras] = f_reference(freshA ? keyA : 0)
[rlh,rll,rlt,rls] = f_reference(freshL ? keyL : 0)
[rnh,rnl,rnt,rns] = f_reference(freshN ? keyN : 0)
f_inside(int sid, int referenceKey, bool a, bool l, bool n) =>
    sid == 0 ? a and referenceKey == keyA : sid == 1 ? l and referenceKey == keyL : sid == 2 ? n and referenceKey == keyN : false
[vAsia, newAsia] = asia.update(inAsia,keyA,0,asiaTZ,rah,ral,rat,ras,f_inside(ras,rat,inAsia,inLon,inNY))
[vLon, newLon] = london.update(inLon,keyL,1,lonTZ,rlh,rll,rlt,rls,f_inside(rls,rlt,inAsia,inLon,inNY))
[vNY, newNY] = newYork.update(inNY,keyN,2,nyTZ,rnh,rnl,rnt,rns,f_inside(rns,rnt,inAsia,inLon,inNY))
while array.size(candles) > 300
    array.shift(candles)
// During overlap, signals follow the most recently started active session.
// Display settings never alter the calculations or alerts.
int activeSid = -1
int activeKey = na
float activeVWAP = na
if inAsia
    activeSid := 0
    activeKey := asia.key
    activeVWAP := vAsia
if inLon and (na(activeKey) or london.key >= activeKey)
    activeSid := 1
    activeKey := london.key
    activeVWAP := vLon
if inNY and (na(activeKey) or newYork.key >= activeKey)
    activeSid := 2
    activeKey := newYork.key
    activeVWAP := vNY
// Freeze a completed session at its scheduled end, not at the next available bar.
// Separate written function calls maintain separate histories for A / L / N.
f_finished_vwap(float v, bool inside, int key, string hours) =>
    var float frozen = na
    var int ended = na
    if not na(v[1]) and (not inside or key != key[1])
        int finishMinutes = int(str.tonumber(str.substring(hours,5,7)))*60+int(str.tonumber(str.substring(hours,7,9)))
        int extraDay = finishMinutes <= f_start_minutes(hours) ? 1 : 0
        int start = key[1]
        ended := timestamp(scheduleTZ,year(start,scheduleTZ),month(start,scheduleTZ),dayofmonth(start,scheduleTZ)+extraDay,int(finishMinutes/60),finishMinutes%60)
        frozen := v[1]
    [frozen,ended]
[finishedA,endedA] = f_finished_vwap(vAsia,inAsia,keyA,asiaHours)
[finishedL,endedL] = f_finished_vwap(vLon,inLon,keyL,lonHours)
[finishedN,endedN] = f_finished_vwap(vNY,inNY,keyN,nyHours)
float finishedVWAP = na
int finishedEnd = na
int finishedSid = -1
if not na(endedA)
    finishedVWAP := finishedA
    finishedEnd := endedA
    finishedSid := 0
if not na(endedL) and (na(finishedEnd) or endedL > finishedEnd)
    finishedVWAP := finishedL
    finishedEnd := endedL
    finishedSid := 1
if not na(endedN) and (na(finishedEnd) or endedN > finishedEnd)
    finishedVWAP := finishedN
    finishedEnd := endedN
    finishedSid := 2
bool finishedVisible = showFinishedVWAP and not na(finishedVWAP) and time >= finishedEnd and time < finishedEnd + 60*60000
plot(finishedVisible ? finishedVWAP : na, "Completed session VWAP (60 minutes)", color=color.new(color.gray,25), linewidth=1, style=plot.style_linebr, force_overlay=true)
var label finishedVWAPTag = na
if barstate.islast
    if not na(finishedVWAPTag)
        label.delete(finishedVWAPTag)
    if finishedVisible
        string finishedName = finishedSid == 0 ? "Asia" : finishedSid == 1 ? "London" : "NY"
        finishedVWAPTag := label.new(time + int(timeframe.in_seconds()*1000)*20, finishedVWAP, finishedName+" VWAP", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(color.gray,100), textcolor=color.gray, size=size.tiny, tooltip="Frozen completed-session VWAP: "+str.tostring(finishedVWAP,format.mintick), force_overlay=true)
// Showing or hiding boxes never changes signal calculations.
bool inLondonKZ = useLondonKZ and not na(time(timeframe.period,londonKZHours,kzTZ))
bool inNYKZ = useNYKZ and not na(time(timeframe.period,nyKZHours,kzTZ))
bool inPMKZ = usePMKZ and not na(time(timeframe.period,pmKZHours,kzTZ))
var array<box> kzBoxes = array.new<box>()
var array<box> liveKZ = array.new<box>(3,na)
var array<int> lastKZKey = array.new<int>(3,na)
if showKZBoxes
    for j = 0 to 2
        bool insideKZ = j == 0 ? inLondonKZ : j == 1 ? inNYKZ : inPMKZ
        string hoursKZ = j == 0 ? londonKZHours : j == 1 ? nyKZHours : pmKZHours
        int keyKZ = f_session_key(hoursKZ,kzTZ)
        // Only complete chart bars can contribute OHLC to a time box.
        if insideKZ and time >= keyKZ and time_close <= f_session_end(keyKZ,hoursKZ,kzTZ)
            box bx = array.get(liveKZ,j)
            if na(array.get(lastKZKey,j)) or keyKZ != array.get(lastKZKey,j)
                bx := box.new(time,high,time_close,low,xloc=xloc.bar_time,border_color=color.new(kzColor,60),border_width=1,bgcolor=kzColor,text=(j == 0 ? "London KZ" : j == 1 ? "New York AM KZ" : "New York PM KZ")+" | "+hoursKZ+" | "+kzTZ,text_size=size.tiny,text_color=color.new(chart.fg_color,30),text_halign=text.align_left,text_valign=text.align_top,force_overlay=true)
                array.set(liveKZ,j,bx)
                array.set(lastKZKey,j,keyKZ)
                array.push(kzBoxes,bx)
            else
                box.set_top(bx,math.max(box.get_top(bx),high))
                box.set_bottom(bx,math.min(box.get_bottom(bx),low))
                box.set_right(bx,time_close)
    while array.size(kzBoxes) > keepKZBoxes
        box.delete(array.shift(kzBoxes))
// Signed prices make BUY and SELL exact mirrors.
type Structure
    float level = na
    int pivotTime = na
    bool used = false
method seed(Structure st, float price, int pt, int direction) =>
    st.level := price * direction
    st.pivotTime := pt
    st.used := false
method check(Structure st, int direction, float vwap) =>
    bool event = false
    if not st.used and not na(st.level) and close * direction > st.level
        st.used := true
        event := close[1] * direction <= st.level and not na(vwap) and st.level > vwap * direction and close * direction > vwap * direction
    event
type Engine
    Structure upper = na
    Structure lower = na
    int attempts = 0
    int lastSide = 0
    float entry = na
    float targetDistance = na
    float favorable = 0.0
    bool reached = false
    int entryBar = na
method reset(Engine e, float h, float l, int ht, int lt) =>
    e.upper := Structure.new()
    e.lower := Structure.new()
    e.upper.seed(h,ht,1)
    e.lower.seed(l,lt,-1)
    e.attempts := 0
    e.lastSide := 0
    e.entry := na
    e.targetDistance := na
    e.favorable := 0.0
    e.reached := false
    e.entryBar := na
method advance(Engine e, int eventSide, float atrValue) =>
    int signal = 0
    // Entry-bar extremes precede the close entry and are excluded.
    // If excursion target and reversal happen on one later bar, target wins.
    if e.attempts > 0 and bar_index > e.entryBar
        float excursion = e.lastSide == 1 ? high - e.entry : e.entry - low
        e.favorable := math.max(e.favorable,excursion)
        e.reached := e.reached or e.favorable >= e.targetDistance
    bool firstAttempt = e.attempts == 0
    bool retry = e.attempts > 0 and not e.reached and eventSide == -e.lastSide
    if eventSide != 0 and e.attempts < maxAttempts and (firstAttempt or retry) and not na(atrValue) and atrValue > 0
        signal := eventSide
        e.lastSide := eventSide
        e.entry := close
        e.targetDistance := atrValue * atrMultiple
        e.entryBar := bar_index
        e.favorable := 0.0
        e.reached := false
        e.attempts += 1
    signal
var Engine asiaEngine = Engine.new()
var Engine lonEngine = Engine.new()
var Engine nyEngine = Engine.new()
float ph = ta.pivothigh(high,pivotDepth,pivotDepth)
float pl = ta.pivotlow(low,pivotDepth,pivotDepth)
var float lastPH = na
var float lastPL = na
var int lastPHTime = na
var int lastPLTime = na
Engine activeEngine = activeSid == 0 ? asiaEngine : activeSid == 1 ? lonEngine : nyEngine
bool buySignal = false
bool sellSignal = false
float bosBadgeLevel = na
float signalATR = ta.atr(atrLength)
float signalEMA = ta.ema(close,emaLength)
// Mandatory gold blackout 18:00-19:00 New York, independent of the session wait.
// Fixed New York clock follows US DST; only gold symbols are affected.
bool isGold = syminfo.basecurrency == "XAU" or syminfo.root == "GC" or syminfo.root == "MGC" or ((syminfo.type == "forex" or syminfo.type == "cfd" or syminfo.type == "futures") and (str.contains(str.upper(syminfo.ticker),"XAU") or str.contains(str.upper(syminfo.ticker),"GOLD")))
int goldBlockStart = timestamp("America/New_York",year(time,"America/New_York"),month(time,"America/New_York"),dayofmonth(time,"America/New_York"),18,0)
int goldBlockEnd = goldBlockStart + 60*60000
bool goldOpenBlocked = isGold and time < goldBlockEnd and time_close > goldBlockStart
float badgeGap = math.max(nz(ta.atr(14),high-low) * labelOffsetATR, syminfo.mintick * 10)
var array<label> tradeBadges = array.new<label>()
var array<line> bosLines = array.new<line>()
if barstate.isconfirmed
    array<Engine> engines = array.from(asiaEngine,lonEngine,nyEngine)
    array<bool> freshSessions = array.from(newAsia,newLon,newNY)
    array<bool> insideSessions = array.from(inAsia,inLon,inNY)
    array<float> vwaps = array.from(vAsia,vLon,vNY)
    for sid = 0 to 2
        Engine e = array.get(engines,sid)
        bool inside = array.get(insideSessions,sid)
        bool fresh = array.get(freshSessions,sid)
        float v = array.get(vwaps,sid)
        if fresh or na(e.upper)
            e.reset(lastPH,lastPL,lastPHTime,lastPLTime)
        if inside
            if not fresh
                if not na(ph)
                    e.upper.seed(ph,time[pivotDepth],1)
                if not na(pl)
                    e.lower.seed(pl,time[pivotDepth],-1)
            bool upperBreak = e.upper.check(1,v)
            bool lowerBreak = e.lower.check(-1,v)
            int eventSide = upperBreak ? 1 : lowerBreak ? -1 : 0
            // The whole breakout bar must start after the waiting period.
            bool ready = time >= activeKey + signalDelay*60000
            bool emaOK = not useEMA or (eventSide == 1 ? signalEMA > v and close > signalEMA : eventSide == -1 ? signalEMA < v and close < signalEMA : false)
            int eligibleEvent = sid == activeSid and ready and allowRegular and not na(v) and emaOK and not goldOpenBlocked ? eventSide : 0
            int signal = e.advance(eligibleEvent,signalATR)
            if sid == activeSid and eventSide != 0
                Structure source = eventSide == 1 ? e.upper : e.lower
                float level = source.level * eventSide
                bosBadgeLevel := level
                if showStructure
                    array.push(bosLines,line.new(source.pivotTime, level, time, level, xloc=xloc.bar_time, color=eventSide == 1 ? bullColor : bearColor, width=1, force_overlay=true))
            if sid == activeSid
                buySignal := signal == 1
                sellSignal := signal == -1
    while array.size(bosLines) > keepBOS
        line.delete(array.shift(bosLines))
    // Opening snapshots above use only pivots known before the session's first bar.
    if not na(ph)
        lastPH := ph
        lastPHTime := time[pivotDepth]
    if not na(pl)
        lastPL := pl
        lastPLTime := time[pivotDepth]
SessionCandle activeCandle = activeSid == 0 ? asia.candle : activeSid == 1 ? london.candle : activeSid == 2 ? newYork.candle : na
bool regularBuy = buySignal
bool regularSell = sellSignal
plot(showEMA ? signalEMA : na, "Signal-filter EMA", color=color.new(#A7ADB5,35), linewidth=1, force_overlay=true)
color activeColor = activeSid == 0 ? asiaColor : activeSid == 1 ? lonColor : nyColor
bool anchorChanged = activeSid != activeSid[1] or activeKey != activeKey[1]
plot(showVWAP ? activeVWAP : na, "Signal VWAP", color=anchorChanged ? na : activeColor, linewidth=2, style=plot.style_linebr, force_overlay=true)
plot(showOtherVWAP and activeSid != 0 ? vAsia : na, "Asia VWAP (context)", color=newAsia ? na : color.new(asiaColor,75), linewidth=1, style=plot.style_linebr, force_overlay=true)
plot(showOtherVWAP and activeSid != 1 ? vLon : na, "London VWAP (context)", color=newLon ? na : color.new(lonColor,75), linewidth=1, style=plot.style_linebr, force_overlay=true)
plot(showOtherVWAP and activeSid != 2 ? vNY : na, "NY VWAP (context)", color=newNY ? na : color.new(nyColor,75), linewidth=1, style=plot.style_linebr, force_overlay=true)
// Tiny dots stay at the true pivot price; confirmation still arrives pivotDepth bars later.
plot(showPivots ? ph : na, "Confirmed pivot high", color=#F05B61, linewidth=1, style=plot.style_circles, offset=-pivotDepth, force_overlay=true)
plot(showPivots ? pl : na, "Confirmed pivot low", color=#397BFF, linewidth=1, style=plot.style_circles, offset=-pivotDepth, force_overlay=true)
plot(buySignal or sellSignal ? activeVWAP : na, "VWAP at signal", display=display.data_window)
plot(buySignal or sellSignal ? activeSid + 1 : na, "Signal session: 1 Asia, 2 London, 3 NY", display=display.data_window)
var line highLevel = na
var line lowLevel = na
if barstate.islast
    if not na(highLevel)
        line.delete(highLevel)
    if not na(lowLevel)
        line.delete(lowLevel)
    if showStructure and activeSid >= 0 and not na(activeEngine.upper)
        Structure upper = activeEngine.upper
        Structure lower = activeEngine.lower
        if not na(upper.level) and not upper.used
            highLevel := line.new(upper.pivotTime, upper.level, time, upper.level, xloc=xloc.bar_time, color=color.new(bullColor,45), style=line.style_dotted, width=1, force_overlay=true)
        if not na(lower.level) and not lower.used
            lowLevel := line.new(lower.pivotTime, -lower.level, time, -lower.level, xloc=xloc.bar_time, color=color.new(bearColor,45), style=line.style_dotted, width=1, force_overlay=true)
// Two context levels only: no historical ladder and no additional entry signals.
var line previousHighLine = na
var line previousLowLine = na
var label previousHighTag = na
var label previousLowTag = na
if barstate.islast
    if not na(previousHighLine)
        line.delete(previousHighLine)
    if not na(previousLowLine)
        line.delete(previousLowLine)
    if not na(previousHighTag)
        label.delete(previousHighTag)
    if not na(previousLowTag)
        label.delete(previousLowTag)
    if showPreviousOnChart and not na(activeCandle) and not na(activeCandle.refH)
        string prefix = (activeCandle.refSid == 0 ? "Asia" : activeCandle.refSid == 1 ? "London" : "NY")+(activeCandle.refOverlap ? " REF " : " ")
        string context = activeCandle.refOverlap ? "Previous session snapshot at the current session open. The previous candle may continue changing; these levels stay fixed." : "Previous completed session. Fixed reference for the current session."
        int referenceTagTime = time + int(timeframe.in_seconds() * 1000) * 20
        color referenceColor = color.new(chart.fg_color,45)
        previousHighLine := line.new(activeCandle.started, activeCandle.refH, referenceTagTime, activeCandle.refH, xloc=xloc.bar_time, color=referenceColor, style=line.style_dashed, width=1, force_overlay=true)
        previousLowLine := line.new(activeCandle.started, activeCandle.refL, referenceTagTime, activeCandle.refL, xloc=xloc.bar_time, color=referenceColor, style=line.style_dashed, width=1, force_overlay=true)
        previousHighTag := label.new(referenceTagTime, activeCandle.refH, prefix+"High", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(color.gray,100), textalign=text.align_left, textcolor=color.new(chart.fg_color,20), size=size.tiny, tooltip=context+"\nHigh: "+str.tostring(activeCandle.refH,format.mintick), force_overlay=true)
        previousLowTag := label.new(referenceTagTime, activeCandle.refL, prefix+"Low", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(color.gray,100), textalign=text.align_left, textcolor=color.new(chart.fg_color,20), size=size.tiny, tooltip=context+"\nLow: "+str.tostring(activeCandle.refL,format.mintick), force_overlay=true)
// Opening levels are context only. Merge equal-price labels to avoid overlapping text.
var array<line> openLines = array.new<line>()
var array<label> openLabels = array.new<label>()
if barstate.islast
    while array.size(openLines) > 0
        line.delete(array.pop(openLines))
    while array.size(openLabels) > 0
        label.delete(array.pop(openLabels))
    int openLabelTime = time + int(timeframe.in_seconds()*1000)*20
    array<float> prices = array.from(weeklyOpen,dailyOpen,h4Open,h1Open)
    array<int> starts = array.from(weeklyOpenTime,dailyOpenTime,h4OpenTime,h1OpenTime)
    array<bool> enabled = array.from(showWeeklyOpen,showDailyOpen,showH4Open,showH1Open)
    array<string> names = array.from("Weekly Open","Daily Open","H4 Open","H1 Open")
    array<color> inks = array.from(color.new(#62B7FF,20),color.new(chart.fg_color,35),color.new(#C4A1DD,25),color.new(#D4C1A4,25))
    for i = 0 to 3
        float price = array.get(prices,i)
        if array.get(enabled,i) and not na(price)
            bool duplicate = false
            if i > 0
                for j = 0 to i-1
                    if array.get(enabled,j) and not na(array.get(prices,j)) and math.abs(price-array.get(prices,j)) < syminfo.mintick*0.5
                        duplicate := true
            if not duplicate
                string caption = array.get(names,i)
                int leftTime = array.get(starts,i)
                if i < 3
                    for j = i+1 to 3
                        if array.get(enabled,j) and not na(array.get(prices,j)) and math.abs(price-array.get(prices,j)) < syminfo.mintick*0.5
                            caption += " / "+array.get(names,j)
                            leftTime := math.min(leftTime,array.get(starts,j))
                color ink = array.get(inks,i)
                array.push(openLines,line.new(leftTime, price, openLabelTime, price, xloc=xloc.bar_time, color=ink, style=i == 0 ? line.style_dashed : line.style_dotted, width=1, force_overlay=true))
                array.push(openLabels,label.new(openLabelTime, price, caption, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(color.gray,100), textcolor=ink, size=size.tiny, tooltip=caption+": "+str.tostring(price,format.mintick)+" | Session clock: "+scheduleTZ, force_overlay=true))
// Badges and alerts use the same confirmed session event.
if barstate.isconfirmed and showSignals
    int badgeSide = buySignal ? 1 : sellSignal ? -1 : 0
    if badgeSide != 0
        string badgeText = badgeSide == 1 ? "BUY" : "SELL"
        color badgeColor = badgeSide == 1 ? bullColor : bearColor
        string meaning = "Session BOS + VWAP | Attempt "+str.tostring(activeEngine.attempts)
        string tip = meaning+(useEMA ? "\nEMA filter: "+str.tostring(emaLength) : "")+"\nSignal VWAP: "+str.tostring(activeVWAP,format.mintick)+(not na(bosBadgeLevel) ? "\nBOS: "+str.tostring(bosBadgeLevel,format.mintick) : "")
        array.push(tradeBadges,label.new(bar_index, badgeSide == 1 ? low - badgeGap : high + badgeGap, badgeText, style=badgeSide == 1 ? label.style_label_up : label.style_label_down, color=badgeColor, textcolor=color.white, size=size.tiny, tooltip=tip, force_overlay=true))
        while array.size(tradeBadges) > keepBadges
            label.delete(array.shift(tradeBadges))
alertcondition(regularBuy, "BUY: Session VWAP", "BUY | {{ticker}} | {{interval}} | Session BOS + VWAP | Close: {{close}}")
alertcondition(regularSell, "SELL: Session VWAP", "SELL | {{ticker}} | {{interval}} | Session BOS + VWAP | Close: {{close}}")
alertcondition(regularBuy or regularSell, "Any entry", "ENTRY | {{ticker}} | {{interval}} | Session BOS + VWAP | Close: {{close}}")
// Screen coordinates only: never reference chart times or price coordinates here.
// Fixed cell geometry is initialized before merging captions. Text setters preserve it.
f_corner(string corner) =>
    corner == "Top left" ? position.top_left : corner == "Bottom left" ? position.bottom_left : corner == "Bottom right" ? position.bottom_right : position.top_right
int rasterRows = math.min(drawingRows,int(9500/(count*5))-count-3)
int columns = count*5
f_row(float price, float topPrice, float priceSpan, int rows) =>
    int(math.max(0,math.min(rows-1,math.round((topPrice-price)/priceSpan*(rows-1)))))
var table mini = na
var string panelLayout = ""
var array<color> cellCache = array.new<color>()
if barstate.islast and showPanel
    // Stable A/L/N slots per trading day; missing or future windows stay empty.
    array<int> days = array.new<int>()
    if array.size(candles) > 0
        for i = 0 to array.size(candles)-1
            int td = array.get(candles,i).tradeDay
            if not array.includes(days,td)
                array.push(days,td)
    array.sort(days,order.ascending)
    int dayFinish = math.max(0,array.size(days)-historyDays)
    int dayBegin = math.max(0,dayFinish-displayDays)
    array<SessionCandle> shown = array.new<SessionCandle>(count,na)
    if dayFinish > dayBegin and array.size(candles) > 0
        for i = 0 to array.size(candles)-1
            SessionCandle sc = array.get(candles,i)
            for d = dayBegin to dayFinish-1
                if sc.tradeDay == array.get(days,d)
                    array.set(shown,(d-dayBegin)*3+sc.sid,sc)
    int n = 0
    int newestK = -1
    float lo = na
    float hi = na
    for k = 0 to count-1
        SessionCandle sc = array.get(shown,k)
        if not na(sc)
            n += 1
            newestK := k
            lo := na(lo) ? sc.l : math.min(lo,sc.l)
            hi := na(hi) ? sc.h : math.max(hi,sc.h)
            if showWeeklyOpen and not na(sc.weekOpen)
                lo := math.min(lo,sc.weekOpen)
                hi := math.max(hi,sc.weekOpen)
            if (showPrevious or showRefEvents) and not na(sc.refH)
                lo := math.min(lo,sc.refL)
                hi := math.max(hi,sc.refH)
    float rawSpan = math.max(nz(hi-lo),syminfo.mintick*2)
    float topPrice = nz(hi)+rawSpan*0.05
    float priceSpan = rawSpan*1.10
    int priorK = -1
    int prevHR = -1
    int prevLR = -1
    int prevMR = -1
    SessionCandle newest = newestK >= 0 ? array.get(shown,newestK) : na
    if showPrevious and not na(newest) and not na(newest.refH)
        prevHR := f_row(newest.refH,topPrice,priceSpan,rasterRows)
        prevLR := f_row(newest.refL,topPrice,priceSpan,rasterRows)
        prevMR := f_row((newest.refH+newest.refL)/2,topPrice,priceSpan,rasterRows)
        priorK := newestK
        for k = 0 to count-1
            SessionCandle c = array.get(shown,k)
            if not na(c) and c.started == newest.refStart
                priorK := k
    // Split only rows that contain a weekly level. Total panel height stays fixed.
    array<bool> splitRows = array.new<bool>(rasterRows,false)
    for k = 0 to count-1
        SessionCandle c = array.get(shown,k)
        if showWeeklyOpen and not na(c) and not na(c.weekOpen)
            array.set(splitRows,f_row(c.weekOpen,topPrice,priceSpan,rasterRows),true)
    array<int> rowMap = array.new<int>(rasterRows,0)
    array<float> heights = array.new<float>()
    string layoutKey = ""
    float normalHeight = panelHeight/rasterRows
    float thinHeight = math.min(0.10,normalHeight*0.35)
    for r = 0 to rasterRows-1
        array.set(rowMap,r,array.size(heights))
        bool split = array.get(splitRows,r)
        layoutKey += split ? "1" : "0"
        array.push(heights,split ? thinHeight : normalHeight)
        if split
            array.push(heights,normalHeight-thinHeight)
    int physicalRows = array.size(heights)
    bool rebuild = na(mini) or layoutKey != panelLayout
    if rebuild
        if not na(mini)
            table.delete(mini)
        mini := table.new(f_corner(panelPosition),columns,physicalRows+3,frame_color=color.new(chart.fg_color,65),frame_width=1,border_width=0,force_overlay=true)
        cellCache := array.new<color>(columns*physicalRows,na)
        panelLayout := layoutKey
        float bodyFraction = bodyShare/100.0
        float wickFraction = 0.04
        for col = 0 to columns-1
            int part = col%5
            float weight = part == 2 ? wickFraction : part == 1 or part == 3 ? (bodyFraction-wickFraction)/2.0 : (1.0-bodyFraction)/2.0
            for row = 0 to physicalRows+2
                float rh = row == 0 ? 2.5 : row == physicalRows+1 ? 2.5 : row == physicalRows+2 ? (showDates ? 2.0 : 0.1) : array.get(heights,row-1)
                table.cell(mini,col,row,"",width=panelWidth*viewScale*weight/count,height=rh*viewScale,text_size=1,bgcolor=panelBg)
        table.merge_cells(mini,0,0,columns-1,0)
        table.cell_set_text_size(mini,0,0,captionSize)
        table.cell_set_text_color(mini,0,0,chart.fg_color)
        for k = 0 to count-1
            table.merge_cells(mini,k*5,physicalRows+1,k*5+4,physicalRows+1)
            table.cell_set_text_size(mini,k*5,physicalRows+1,captionSize)
        for d = 0 to displayDays-1
            table.merge_cells(mini,d*15,physicalRows+2,d*15+14,physicalRows+2)
            table.cell_set_text_size(mini,d*15,physicalRows+2,captionSize)
            table.cell_set_text_color(mini,d*15,physicalRows+2,color.new(chart.fg_color,35))
    string refTag = not na(newest) and newest.refOverlap ? " REF" : ""
    string header = n == 0 ? "--" : compactText ? str.tostring(displayDays)+"D"+refTag : str.tostring(displayDays)+"D | "+str.tostring(n)+"S | * LIVE"+refTag
    header += showWeeklyOpen ? " | WO" : ""
    table.cell_set_text(mini,0,0,header)
    table.cell_set_tooltip(mini,0,0,"Schedule: "+scheduleTZ+"\nWO: thin solid blue Weekly Open, fixed per session-based week.\nA: "+asiaHours+" | L: "+lonHours+" | N: "+nyHours+"\nHighlighted captions: LIVE. Amber: return at/inside the reference. Blue: close beyond the reference. Faded LIVE marks are provisional; CLOSED marks are final session states. REF: frozen overlap snapshot.\nVWAP starts with each window. Time boxes are visual only and never reset VWAP or create extra signals.")
    for d = 0 to displayDays-1
        int di = dayBegin+d
        string dateCaption = showDates and di < dayFinish ? str.format_time(array.get(days,di),compactText ? "dd" : "dd MMM",scheduleTZ) : ""
        table.cell_set_text(mini,d*15,physicalRows+2,dateCaption)
    for k = 0 to count-1
        SessionCandle sc = array.get(shown,k)
        bool valid = not na(sc)
        int hr = valid ? f_row(sc.h,topPrice,priceSpan,rasterRows) : -1
        int lr = valid ? f_row(sc.l,topPrice,priceSpan,rasterRows) : -1
        int orow = valid ? f_row(sc.o,topPrice,priceSpan,rasterRows) : -1
        int cr = valid ? f_row(sc.c,topPrice,priceSpan,rasterRows) : -1
        int weekRow = valid and showWeeklyOpen and not na(sc.weekOpen) ? f_row(sc.weekOpen,topPrice,priceSpan,rasterRows) : -1
        int mr = valid ? f_row((sc.h+sc.l)/2,topPrice,priceSpan,rasterRows) : -1
        color ink = valid ? (sc.c >= sc.o ? bullColor : bearColor) : panelBg
        bool dayStart = k > 0 and k%3 == 0
        int eventHR = valid and not na(sc.refH) ? f_row(sc.refH,topPrice,priceSpan,rasterRows) : -1
        int eventLR = valid and not na(sc.refL) ? f_row(sc.refL,topPrice,priceSpan,rasterRows) : -1
        for row = 0 to rasterRows-1
            for part = 0 to 4
                bool body = valid and part >= 1 and part <= 3 and row >= math.min(orow,cr) and row <= math.max(orow,cr)
                bool wick = valid and part == 2 and row >= hr and row <= lr
                bool mid = valid and showMid and part >= 1 and part <= 3 and row == mr
                bool priorLevel = priorK >= 0 and k >= priorK and k <= newestK and (row == prevHR or row == prevLR or row == prevMR) and (k*5+part)%2 == 0
                bool weekLevel = weekRow >= 0 and row == weekRow
                bool divider = dayStart and part == 0 and row%6 == 0
                bool highMark = showRefEvents and valid and sc.highEvent > 0 and part == 0 and row == eventHR
                bool lowMark = showRefEvents and valid and sc.lowEvent > 0 and part == 4 and row == eventLR
                int eventKind = highMark ? sc.highEvent : lowMark ? sc.lowEvent : 0
                color fill = eventKind > 0 ? color.new(eventKind == 1 ? #FFBF47 : #62B7FF,sc.live ? 45 : 0) : mid ? color.new(chart.fg_color,15) : body or wick ? color.new(ink,valid and sc.live ? 15 : 0) : priorLevel ? color.new(chart.fg_color,70) : divider ? color.new(chart.fg_color,70) : panelBg
                int col = k*5+part
                int mapped = array.get(rowMap,row)
                int strips = array.get(splitRows,row) ? 2 : 1
                for strip = 0 to strips-1
                    int physical = mapped+strip
                    color painted = weekLevel and strip == 0 and eventKind == 0 ? color.new(#7AA8CC,10) : fill
                    int cacheIndex = physical*columns+col
                    color previousColor = array.get(cellCache,cacheIndex)
                    if na(previousColor) or previousColor != painted
                        table.cell_set_bgcolor(mini,col,physical+1,painted)
                        array.set(cellCache,cacheIndex,painted)
        string name = valid ? (compactText ? (sc.sid == 0 ? "A" : sc.sid == 1 ? "L" : "N") : (sc.sid == 0 ? "AS" : sc.sid == 1 ? "LDN" : "NY")) : ""
        string caption = name+(not compactText and valid and sc.live ? "*" : "")+(not compactText and valid and sc.partial ? "!" : "")
        bool weekEnd = valid and showWeeklyOpen and not na(sc.weekOpen)
        if weekEnd and k < count-1
            SessionCandle next = array.get(shown,k+1)
            weekEnd := na(next) or next.weekKey != sc.weekKey
        caption += weekEnd and not compactText ? " WO" : ""
        color sessionColor = valid ? (sc.sid == 0 ? asiaColor : sc.sid == 1 ? lonColor : nyColor) : chart.fg_color
        string refTip = valid and not na(sc.refH) ? "\n"+(sc.refOverlap ? "REF (overlap snapshot)" : "Previous completed window")+"\nRef High: "+str.tostring(sc.refH,format.mintick)+"\nRef Low: "+str.tostring(sc.refL,format.mintick)+"\n"+(sc.live ? "LIVE provisional" : "CLOSED final")+" high state: "+(sc.highEvent == 1 ? "SWEEP" : sc.highEvent == 2 ? "BREAK" : "NONE")+"\n"+(sc.live ? "LIVE provisional" : "CLOSED final")+" low state: "+(sc.lowEvent == 1 ? "SWEEP" : sc.lowEvent == 2 ? "BREAK" : "NONE") : ""
        string fullName = valid ? (sc.sid == 0 ? windowAName : sc.sid == 1 ? windowLName : windowNName) : ""
        string tip = valid ? fullName+" | "+sc.dateText+"\nOpen: "+str.tostring(sc.o,format.mintick)+"\nHigh: "+str.tostring(sc.h,format.mintick)+"\nLow: "+str.tostring(sc.l,format.mintick)+"\nClose: "+str.tostring(sc.c,format.mintick)+"\n50%: "+str.tostring((sc.h+sc.l)/2,format.mintick)+(sc.live ? "\nLIVE: close is not final" : "\nCLOSED") : ""
        tip += valid and showWeeklyOpen and not na(sc.weekOpen) ? "\nWeekly Open: "+str.tostring(sc.weekOpen,format.mintick) : ""
        table.cell_set_text(mini,k*5,physicalRows+1,caption)
        table.cell_set_text_color(mini,k*5,physicalRows+1,sessionColor)
        table.cell_set_tooltip(mini,k*5,physicalRows+1,tip+refTip+(valid and sc.partial ? "\nPARTIAL HISTORY" : ""))
        table.cell_set_bgcolor(mini,k*5,physicalRows+1,valid and sc.live ? color.new(sessionColor,75) : panelBg)

← 返回列表