Session Windows [FCD]

SP989 · study · 480 行 · 点赞 5 · 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
// Session Windows [FCD]
// Product family: Futures Context Desk
// Version: 1.1
// Date: 2026-11-01
// License: Mozilla Public License 2.0 (open source)
// Description: intraday ET time windows (boxes or background), Asia / London / Overnight (Globex)
//              reference highs and lows extended to the RTH close, and a session VWAP
//              (anchored 09:30 ET or 18:00 ET) with optional standard deviation bands.
//              1.1: plain-English status line, "level taken" markers during RTH, and
//              one-click alerts (alert() calls plus one alertcondition() per event).
//              All session times use America/New_York explicitly, never the chart timezone.
 
//@version=6
indicator("Session Windows [FCD]", shorttitle = "Session Windows [FCD]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ─────────────────────────────────────────────────────────────────────────────
// Constants
// ─────────────────────────────────────────────────────────────────────────────
string TZ       = "America/New_York"
int    DAY_MS   = 86400000
color  COL_IN   = #2962FF   // status: inside a time window (blue)
color  COL_OUT  = #5D606B   // status: outside the windows (gray)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Display Options
// ─────────────────────────────────────────────────────────────────────────────
string GRP_DISP     = "Display Options"
int    daysToShow   = input.int(3, "Days to show", minval = 1, maxval = 30, group = GRP_DISP, tooltip = "How many trading days get boxes and lines, counted back from the newest bar. A trading day starts at 18:00 New York time (ET) the evening before.")
string winMode      = input.string("High-Low box", "Window style", options = ["High-Low box", "Full-height background"], group = GRP_DISP, tooltip = "High-Low box: a box from the highest to the lowest price inside each time window. Full-height background: the whole chart height is shaded during the window.")
int    boxTransp    = input.int(88, "Window fill transparency", minval = 0, maxval = 100, group = GRP_DISP, tooltip = "0 = solid color, 100 = invisible.")
int    borderTransp = input.int(60, "Window border transparency", minval = 0, maxval = 100, group = GRP_DISP, tooltip = "0 = solid color, 100 = invisible.")
bool   showWinLabel = input.bool(true, "Show window names on the chart", group = GRP_DISP)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Session Windows (ET)
// ─────────────────────────────────────────────────────────────────────────────
string GRP_WIN  = "Time Windows (New York time, ET)"
string TT_WIN   = "Each row: on/off, start-end time in New York time (ET), color, and name. W0 to W5 are just short names for the six windows. The name is shown on the chart, in the status line and in alerts."
bool   on0 = input.bool(true, "", inline = "w0", group = GRP_WIN)
string s0  = input.session("0005-0600", "", inline = "w0", group = GRP_WIN)
color  c0  = input.color(#7E57C2, "", inline = "w0", group = GRP_WIN)
string t0  = input.string("W0 Overnight", "", inline = "w0", group = GRP_WIN, tooltip = TT_WIN)
 
bool   on1 = input.bool(true, "", inline = "w1", group = GRP_WIN)
string s1  = input.session("0930-1100", "", inline = "w1", group = GRP_WIN)
color  c1  = input.color(#2962FF, "", inline = "w1", group = GRP_WIN)
string t1  = input.string("W1 Open", "", inline = "w1", group = GRP_WIN, tooltip = TT_WIN)
 
bool   on2 = input.bool(true, "", inline = "w2", group = GRP_WIN)
string s2  = input.session("1100-1200", "", inline = "w2", group = GRP_WIN)
color  c2  = input.color(#00897B, "", inline = "w2", group = GRP_WIN)
string t2  = input.string("W2 Mid-morning", "", inline = "w2", group = GRP_WIN, tooltip = TT_WIN)
 
bool   on4 = input.bool(true, "", inline = "w4", group = GRP_WIN)
string s4  = input.session("1200-1400", "", inline = "w4", group = GRP_WIN)
color  c4  = input.color(#787B86, "", inline = "w4", group = GRP_WIN)
string t4  = input.string("W4 Lunch", "", inline = "w4", group = GRP_WIN, tooltip = TT_WIN)
 
bool   on3 = input.bool(true, "", inline = "w3", group = GRP_WIN)
string s3  = input.session("1400-1530", "", inline = "w3", group = GRP_WIN)
color  c3  = input.color(#F57C00, "", inline = "w3", group = GRP_WIN)
string t3  = input.string("W3 Afternoon", "", inline = "w3", group = GRP_WIN, tooltip = TT_WIN)
 
bool   on5 = input.bool(true, "", inline = "w5", group = GRP_WIN)
string s5  = input.session("1530-1600", "", inline = "w5", group = GRP_WIN)
color  c5  = input.color(#E91E63, "", inline = "w5", group = GRP_WIN)
string t5  = input.string("W5 Last 30", "", inline = "w5", group = GRP_WIN, tooltip = TT_WIN)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Reference Sessions (ET)
// ─────────────────────────────────────────────────────────────────────────────
string GRP_REF      = "Reference Highs and Lows (ET)"
bool   onAsia       = input.bool(true, "Asia", inline = "ra", group = GRP_REF)
string sAsia        = input.session("1800-0300", "", inline = "ra", group = GRP_REF)
color  cAsia        = input.color(#26A69A, "", inline = "ra", group = GRP_REF, tooltip = "High and low of the Asia session (default 18:00-03:00 ET). The lines run until the 16:00 ET close of the same trading day.")
bool   onLdn        = input.bool(true, "London", inline = "rl", group = GRP_REF)
string sLdn         = input.session("0300-0830", "", inline = "rl", group = GRP_REF)
color  cLdn         = input.color(#5C6BC0, "", inline = "rl", group = GRP_REF, tooltip = "High and low of the London session (default 03:00-08:30 ET).")
bool   onGbx        = input.bool(false, "Overnight", inline = "rg", group = GRP_REF)
string sGbx         = input.session("1800-0930", "", inline = "rg", group = GRP_REF)
color  cGbx         = input.color(#8D6E63, "", inline = "rg", group = GRP_REF, tooltip = "High and low of the whole overnight session. Globex = the CME electronic session that trades overnight, 18:00 ET until the 09:30 ET open of regular trading hours (RTH = 09:30-16:00 ET).")
int    refWidth     = input.int(1, "Line width", minval = 1, maxval = 4, group = GRP_REF)
string refStyleStr  = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = GRP_REF)
bool   showRefLabel = input.bool(true, "Show high/low names at the line ends", group = GRP_REF)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Markers
// ─────────────────────────────────────────────────────────────────────────────
string GRP_MK      = "Markers"
bool   showMarkers = input.bool(true, "Show \"level taken\" markers", group = GRP_MK, tooltip = "During regular trading hours (RTH = 09:30-16:00 ET), a small note appears the first time price trades above an Asia / London / Overnight high (▲, above the bar) or below one of their lows (▼, below the bar). Each level is marked at most once per day. Only today's and the previous day's markers are kept, so the chart stays clean.")
color  mkBg        = input.color(color.new(#434651, 10), "Marker background / text", inline = "mk", group = GRP_MK)
color  mkTxt       = input.color(#FFFFFF, "", inline = "mk", group = GRP_MK, tooltip = "First swatch = marker background color. Second swatch = marker text color.")
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Alerts
// ─────────────────────────────────────────────────────────────────────────────
string GRP_AL   = "Alerts"
string TT_FREQ  = "Off (default): the alert fires once, the moment it happens, while the bar is still forming. On: the alert waits until the bar closes, and fires only if the event still holds at the close (a window start always holds; a level stays taken once price has traded through it)."
bool   alWin    = input.bool(true, "Alert when a time window starts", group = GRP_AL, tooltip = "Message example: \"MNQ1!: Lunch window started (12:00-14:00 ET)\". Fires once on the first bar of the window.")
bool   alAsia   = input.bool(true, "Alert when the Asia high or low is taken", group = GRP_AL, tooltip = "\"Taken\" = price trades above the high or below the low for the first time during RTH (09:30-16:00 ET). Needs the Asia line switched on.")
bool   alLdn    = input.bool(true, "Alert when the London high or low is taken", group = GRP_AL, tooltip = "Same as Asia, for the London high and low. Needs the London line switched on.")
bool   alGbx    = input.bool(true, "Alert when the Overnight high or low is taken", group = GRP_AL, tooltip = "Same as Asia, for the Overnight (Globex) high and low. Needs the Overnight line switched on (it is off by default).")
bool   alClose  = input.bool(false, "Wait for the bar to close before alerting", group = GRP_AL, tooltip = TT_FREQ)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Session VWAP
// ─────────────────────────────────────────────────────────────────────────────
string GRP_VW      = "Session VWAP"
bool   showVwap    = input.bool(true, "Show VWAP", group = GRP_VW, tooltip = "VWAP = volume-weighted average price: the average price of the session, where each price counts in proportion to the volume traded at it.")
string vwAnchorStr = input.string("RTH 09:30 ET", "Start the VWAP at", options = ["RTH 09:30 ET", "Globex 18:00 ET"], group = GRP_VW, tooltip = "RTH 09:30 ET = the open of regular trading hours. Globex 18:00 ET = the start of the overnight session, the start of the futures trading day.")
float  vwSrc       = input.source(hlc3, "Price used", group = GRP_VW, tooltip = "Default hlc3 = (high + low + close) / 3 of each bar.")
bool   vwRthOnly   = input.bool(true, "Hide outside RTH (when started at 09:30)", group = GRP_VW, tooltip = "RTH = regular trading hours, 09:30-16:00 ET.")
bool   vwLimitDays = input.bool(true, "Limit to the days shown", group = GRP_VW)
color  vwCol       = input.color(#FF9800, "VWAP color", group = GRP_VW)
bool   showB1      = input.bool(true, "Band 1 - width (x std dev), color", inline = "b1", group = GRP_VW)
float  mult1       = input.float(1.0, "", minval = 0.1, step = 0.1, inline = "b1", group = GRP_VW)
color  b1Col       = input.color(color.new(#FF9800, 40), "", inline = "b1", group = GRP_VW, tooltip = "Checkbox = show band 1. Number = band width in standard deviations. Swatch = band color. Bands sit above and below the VWAP at this many standard deviations (a measure of how far prices have spread around the VWAP since it started).")
bool   showB2      = input.bool(false, "Band 2 - width (x std dev), color", inline = "b2", group = GRP_VW)
float  mult2       = input.float(2.0, "", minval = 0.1, step = 0.1, inline = "b2", group = GRP_VW)
color  b2Col       = input.color(color.new(#FF9800, 65), "", inline = "b2", group = GRP_VW, tooltip = "Checkbox = show band 2. Number = band width in standard deviations. Swatch = band color.")
bool   fillB1      = input.bool(true, "Fill band 1", inline = "f1", group = GRP_VW)
color  fillCol     = input.color(color.new(#FF9800, 93), "", inline = "f1", group = GRP_VW)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs: Table
// ─────────────────────────────────────────────────────────────────────────────
string GRP_TBL   = "Status Table"
bool   showTable = input.bool(true, "Show status table", group = GRP_TBL, tooltip = "Top line: what is happening now, in plain words (blue = inside a time window, gray = outside). Below: the levels marked today and the current reference values.")
string tblPosStr = input.string("Bottom Left", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = GRP_TBL)
color  tblBg     = input.color(color.new(#131722, 15), "Background / text", inline = "tc", group = GRP_TBL)
color  tblTxt    = input.color(#D1D4DC, "", inline = "tc", group = GRP_TBL, tooltip = "First swatch = table background color. Second swatch = table text color.")
 
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
// Line style from string input.
f_style(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
// 16:00 ET RTH close of the trading day a bar belongs to (bars from 18:00 ET belong to the next day).
f_rthClose(int t) =>
    int base = hour(t, TZ) >= 18 ? t + DAY_MS : t
    timestamp(TZ, year(base, TZ), month(base, TZ), dayofmonth(base, TZ), 16, 0)
 
// Start (18:00 ET of the prior calendar day) of the trading day that lies n weekdays back
// from the last chart bar's trading day. Runs once (loop of at most ~45 steps).
f_cutoff(int n) =>
    int t     = last_bar_time
    int d     = hour(t, TZ) >= 18 ? t + DAY_MS : t
    int noon  = timestamp(TZ, year(d, TZ), month(d, TZ), dayofmonth(d, TZ), 12, 0)
    int cnt   = 1
    while cnt < n
        noon -= DAY_MS
        int dw = dayofweek(noon, TZ)
        if dw != dayofweek.saturday and dw != dayofweek.sunday
            cnt += 1
    int prev = noon - DAY_MS
    timestamp(TZ, year(prev, TZ), month(prev, TZ), dayofmonth(prev, TZ), 18, 0)
 
f_tblPos(string s) =>
    switch s
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_fmt(float v) =>
    na(v) ? "–" : str.tostring(v, format.mintick)
 
// "0930-1100" (optionally followed by ":days") -> "09:30-11:00 ET".
f_sessTxt(string s) =>
    str.length(s) < 9 ? s + " ET" : str.substring(s, 0, 2) + ":" + str.substring(s, 2, 4) + "-" + str.substring(s, 5, 7) + ":" + str.substring(s, 7, 9) + " ET"
 
// "W4 Lunch" -> "Lunch" (drops the short W0-W5 code for plain-language text).
f_name(string t) =>
    string code = str.match(t, "^W[0-9]+ ")
    code == "" ? t : str.substring(t, str.length(code))
 
// Appends s to a newline-separated list when c is true.
f_add(string acc, bool c, string s) =>
    c ? (acc == "" ? s : acc + "\n" + s) : acc
 
// Appends s to a comma-separated list when c is true.
f_addc(string acc, bool c, string s) =>
    c ? (acc == "" ? s : acc + ", " + s) : acc
 
// ─────────────────────────────────────────────────────────────────────────────
// Global state
// ─────────────────────────────────────────────────────────────────────────────
bool   okTF     = timeframe.isintraday and timeframe.in_seconds(timeframe.period) <= 3600
bool   fullMode = winMode == "Full-height background"
string refStyle = f_style(refStyleStr)
var int cutoff  = f_cutoff(daysToShow)
bool   inDays   = time >= cutoff
 
// Regular trading hours (RTH) 09:30-16:00 ET.
bool rthIn    = not na(time(timeframe.period, "0930-1600", TZ))
bool rthStart = rthIn and not rthIn[1]
 
// ─────────────────────────────────────────────────────────────────────────────
// Session window (box or full-height label). Returns [inside window, window started on this bar].
// Must be called on every bar (it references its own history).
// ─────────────────────────────────────────────────────────────────────────────
f_window(bool on, string sess, color c, string txt) =>
    bool inS     = not na(time(timeframe.period, sess, TZ))
    // A session already running on the first chart bar is not treated as started (its range would be partial).
    bool started = inS and bar_index > 0 and not inS[1]
    var box   b  = na
    var label lb = na
    var float hi = na
    var float lo = na
    if started
        b  := na
        lb := na
        hi := high
        lo := low
        if on and okTF and inDays
            if fullMode
                if showWinLabel
                    // Label's lower-left corner sits on the window's first bar at its running high (top-left of the window).
                    lb := label.new(bar_index, hi, txt, style = label.style_label_lower_left, color = #00000000, textcolor = c, size = size.small)
            else
                b := box.new(bar_index, hi, bar_index, lo, border_color = color.new(c, borderTransp), border_width = 1, bgcolor = color.new(c, boxTransp), text = showWinLabel ? txt : "", text_size = size.small, text_color = c, text_halign = text.align_left, text_valign = text.align_top)
    else if inS
        hi := math.max(hi, high)
        lo := math.min(lo, low)
        if not na(b)
            box.set_right(b, bar_index)
            box.set_top(b, hi)
            box.set_bottom(b, lo)
        if not na(lb)
            label.set_y(lb, hi)
    [inS, started and on and okTF]
 
// ─────────────────────────────────────────────────────────────────────────────
// Reference session high/low, lines extended to the RTH close of the same trading day.
// Returns [high, low, inside session] of the current/most recent session. Must be called on every bar.
// ─────────────────────────────────────────────────────────────────────────────
f_ref(bool on, string sess, color c, string nm) =>
    bool inS     = not na(time(timeframe.period, sess, TZ))
    bool started = inS and bar_index > 0 and not inS[1]
    var float hi = na
    var float lo = na
    var line  lh = na
    var line  ll = na
    var label bh = na
    var label bl = na
    if started
        hi := high
        lo := low
        lh := na
        ll := na
        bh := na
        bl := na
        if on and okTF and inDays
            int x2 = f_rthClose(time)
            lh := line.new(time, hi, x2, hi, xloc = xloc.bar_time, color = c, width = refWidth, style = refStyle)
            ll := line.new(time, lo, x2, lo, xloc = xloc.bar_time, color = c, width = refWidth, style = refStyle)
            if showRefLabel
                bh := label.new(x2, hi, nm + " high", xloc = xloc.bar_time, style = label.style_label_left, color = #00000000, textcolor = c, size = size.small)
                bl := label.new(x2, lo, nm + " low", xloc = xloc.bar_time, style = label.style_label_left, color = #00000000, textcolor = c, size = size.small)
    else if inS
        hi := math.max(hi, high)
        lo := math.min(lo, low)
        if not na(lh)
            line.set_y1(lh, hi)
            line.set_y2(lh, hi)
            line.set_y1(ll, lo)
            line.set_y2(ll, lo)
        if not na(bh)
            label.set_y(bh, hi)
            label.set_y(bl, lo)
    [hi, lo, inS]
 
// ─────────────────────────────────────────────────────────────────────────────
// "Level taken": true on the first RTH bar whose high trades above (isHigh) or whose low trades
// below the level, at most once per RTH day. Ignored while the reference session itself is running.
// Must be called on every bar.
// ─────────────────────────────────────────────────────────────────────────────
f_taken(bool on, float lvl, bool inRefSess, bool isHigh) =>
    var bool done = false
    if rthStart
        done := false
    bool hit = false
    if on and okTF and rthIn and not inRefSess and not done and not na(lvl)
        if isHigh ? high > lvl : low < lvl
            hit  := true
            done := true
    hit
 
// ─────────────────────────────────────────────────────────────────────────────
// Windows
// ─────────────────────────────────────────────────────────────────────────────
[in0, st0] = f_window(on0, s0, c0, t0)
[in1, st1] = f_window(on1, s1, c1, t1)
[in2, st2] = f_window(on2, s2, c2, t2)
[in4, st4] = f_window(on4, s4, c4, t4)
[in3, st3] = f_window(on3, s3, c3, t3)
[in5, st5] = f_window(on5, s5, c5, t5)
 
color bgW = na
if fullMode and okTF and inDays
    bgW := in0 and on0 ? color.new(c0, boxTransp) : in1 and on1 ? color.new(c1, boxTransp) : in2 and on2 ? color.new(c2, boxTransp) : in4 and on4 ? color.new(c4, boxTransp) : in3 and on3 ? color.new(c3, boxTransp) : in5 and on5 ? color.new(c5, boxTransp) : na
bgcolor(bgW, title = "Window background")
 
// ─────────────────────────────────────────────────────────────────────────────
// Reference sessions
// ─────────────────────────────────────────────────────────────────────────────
[asiaH, asiaL, inAsia] = f_ref(onAsia, sAsia, cAsia, "Asia")
[ldnH, ldnL, inLdn]    = f_ref(onLdn, sLdn, cLdn, "London")
[gbxH, gbxL, inGbx]    = f_ref(onGbx, sGbx, cGbx, "Overnight")
 
// ─────────────────────────────────────────────────────────────────────────────
// Level-taken events (RTH only)
// ─────────────────────────────────────────────────────────────────────────────
bool asiaHT = f_taken(onAsia, asiaH, inAsia, true)
bool asiaLT = f_taken(onAsia, asiaL, inAsia, false)
bool ldnHT  = f_taken(onLdn, ldnH, inLdn, true)
bool ldnLT  = f_taken(onLdn, ldnL, inLdn, false)
bool gbxHT  = f_taken(onGbx, gbxH, inGbx, true)
bool gbxLT  = f_taken(onGbx, gbxL, inGbx, false)
 
// Plain list of the levels taken in the current RTH day (for the table).
var string takenToday = ""
if rthStart
    takenToday := ""
takenToday := f_addc(takenToday, asiaHT, "Asia high")
takenToday := f_addc(takenToday, asiaLT, "Asia low")
takenToday := f_addc(takenToday, ldnHT, "London high")
takenToday := f_addc(takenToday, ldnLT, "London low")
takenToday := f_addc(takenToday, gbxHT, "Overnight high")
takenToday := f_addc(takenToday, gbxLT, "Overnight low")
 
// ─────────────────────────────────────────────────────────────────────────────
// Markers: one label above the bar for highs taken, one below for lows taken.
// Only the current and the previous RTH day are kept (at most 12 labels).
// ─────────────────────────────────────────────────────────────────────────────
var array<label> mkCur  = array.new<label>()
var array<label> mkPrev = array.new<label>()
if rthStart
    for l in mkPrev
        label.delete(l)
    mkPrev := mkCur
    mkCur  := array.new<label>()
 
string hiTxt = ""
hiTxt := f_add(hiTxt, asiaHT, "Asia high taken ▲")
hiTxt := f_add(hiTxt, ldnHT, "London high taken ▲")
hiTxt := f_add(hiTxt, gbxHT, "Overnight high taken ▲")
string loTxt = ""
loTxt := f_add(loTxt, asiaLT, "Asia low taken ▼")
loTxt := f_add(loTxt, ldnLT, "London low taken ▼")
loTxt := f_add(loTxt, gbxLT, "Overnight low taken ▼")
 
if showMarkers and hiTxt != ""
    mkCur.push(label.new(bar_index, high, hiTxt, yloc = yloc.abovebar, style = label.style_label_down, color = mkBg, textcolor = mkTxt, size = size.small))
if showMarkers and loTxt != ""
    mkCur.push(label.new(bar_index, low, loTxt, yloc = yloc.belowbar, style = label.style_label_up, color = mkBg, textcolor = mkTxt, size = size.small))
 
// ─────────────────────────────────────────────────────────────────────────────
// alert() calls: one alert with "Any alert() function call" covers every event below.
// ─────────────────────────────────────────────────────────────────────────────
// Frequency: once per bar (fires on the first tick of the event) by default; once per bar close
// when "Wait for the bar to close" is on. Constants are passed literally in each branch.
f_send(string msg) =>
    if alClose
        alert(msg, alert.freq_once_per_bar_close)
    else
        alert(msg, alert.freq_once_per_bar)
 
f_winAlert(bool st, string t, string s) =>
    if alWin and st
        f_send(syminfo.ticker + ": " + f_name(t) + " window started (" + f_sessTxt(s) + ")")
 
f_lvlAlert(bool en, bool hit, string what, float lvl) =>
    if en and hit
        f_send(syminfo.ticker + ": " + what + " taken at " + str.tostring(close, format.mintick) + " (level " + str.tostring(lvl, format.mintick) + ")")
 
f_winAlert(st0, t0, s0)
f_winAlert(st1, t1, s1)
f_winAlert(st2, t2, s2)
f_winAlert(st4, t4, s4)
f_winAlert(st3, t3, s3)
f_winAlert(st5, t5, s5)
f_lvlAlert(alAsia, asiaHT, "Asia high", asiaH)
f_lvlAlert(alAsia, asiaLT, "Asia low", asiaL)
f_lvlAlert(alLdn, ldnHT, "London high", ldnH)
f_lvlAlert(alLdn, ldnLT, "London low", ldnL)
f_lvlAlert(alGbx, gbxHT, "Overnight high", gbxH)
f_lvlAlert(alGbx, gbxLT, "Overnight low", gbxL)
 
// Individual alert conditions (pick one by name in the Create Alert dialog).
alertcondition(st0, "Window W0 (Overnight) started", "{{ticker}}: W0 Overnight window started")
alertcondition(st1, "Window W1 (Open) started", "{{ticker}}: W1 Open window started")
alertcondition(st2, "Window W2 (Mid-morning) started", "{{ticker}}: W2 Mid-morning window started")
alertcondition(st4, "Window W4 (Lunch) started", "{{ticker}}: W4 Lunch window started")
alertcondition(st3, "Window W3 (Afternoon) started", "{{ticker}}: W3 Afternoon window started")
alertcondition(st5, "Window W5 (Last 30) started", "{{ticker}}: W5 Last 30 window started")
alertcondition(asiaHT, "Asia high taken", "{{ticker}}: Asia high taken at {{close}}")
alertcondition(asiaLT, "Asia low taken", "{{ticker}}: Asia low taken at {{close}}")
alertcondition(ldnHT, "London high taken", "{{ticker}}: London high taken at {{close}}")
alertcondition(ldnLT, "London low taken", "{{ticker}}: London low taken at {{close}}")
alertcondition(gbxHT, "Overnight high taken", "{{ticker}}: Overnight high taken at {{close}}")
alertcondition(gbxLT, "Overnight low taken", "{{ticker}}: Overnight low taken at {{close}}")
 
// ─────────────────────────────────────────────────────────────────────────────
// Session VWAP (ta.vwap with anchor and stdev multiplier, v6 tuple form)
// ─────────────────────────────────────────────────────────────────────────────
// Globex day change: the bar's trading day (RTH close it belongs to) differs from the prior bar's.
// Handles the Sunday 18:00 reopen after Friday's last bar and symbols without a daily halt.
int  tdNow    = f_rthClose(time)
int  tdPrev   = f_rthClose(nz(time[1], time))
bool gbxStart = tdNow != tdPrev
bool rthAnch  = vwAnchorStr == "RTH 09:30 ET"
bool anchor   = rthAnch ? rthStart : gbxStart
 
[vw, vwU1, vwL1] = ta.vwap(vwSrc, anchor, mult1)
[vwB, vwU2, vwL2] = ta.vwap(vwSrc, anchor, mult2)
 
// Before the first anchor in the loaded history ta.vwap accumulates from bar 0, so hide it until then.
var bool seenAnchor = false
if anchor
    seenAnchor := true
 
bool vwVisible = showVwap and okTF and seenAnchor and (not vwLimitDays or inDays) and (not (rthAnch and vwRthOnly) or rthIn)
// The anchor bar normally gets color na to break the line from the prior session. With the RTH-only
// option the prior bar is already na, so the 09:30 point can keep its color.
bool  hideAnch  = anchor and not (rthAnch and vwRthOnly)
color vwLineCol = hideAnch ? color(na) : vwCol
color b1LineCol = hideAnch ? color(na) : b1Col
color b2LineCol = hideAnch ? color(na) : b2Col
 
plot(vwVisible ? vw : na, "Session VWAP", color = vwLineCol, linewidth = 2, style = plot.style_linebr)
pU1 = plot(vwVisible and showB1 ? vwU1 : na, "VWAP upper band 1", color = b1LineCol, linewidth = 1, style = plot.style_linebr)
pL1 = plot(vwVisible and showB1 ? vwL1 : na, "VWAP lower band 1", color = b1LineCol, linewidth = 1, style = plot.style_linebr)
plot(vwVisible and showB2 ? vwU2 : na, "VWAP upper band 2", color = b2LineCol, linewidth = 1, style = plot.style_linebr)
plot(vwVisible and showB2 ? vwL2 : na, "VWAP lower band 2", color = b2LineCol, linewidth = 1, style = plot.style_linebr)
fill(pU1, pL1, color = fillB1 and not hideAnch ? fillCol : color(na), title = "Band 1 fill")
 
// ─────────────────────────────────────────────────────────────────────────────
// Status table. Row 0 = plain-English status (merged across both columns, merged once).
// ─────────────────────────────────────────────────────────────────────────────
var table tb = table.new(f_tblPos(tblPosStr), 2, 7, bgcolor = tblBg, border_width = 1, border_color = color.new(tblTxt, 85), frame_width = 1, frame_color = color.new(tblTxt, 70))
var bool tbMerged = false
 
f_row(int r, string k, string v, color kc) =>
    table.cell(tb, 0, r, k, text_color = kc, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = tblTxt, text_size = size.small, text_halign = text.align_right)
 
if barstate.islast and showTable
    if not tbMerged
        table.merge_cells(tb, 0, 0, 1, 0)
        tbMerged := true
    table.clear(tb, 0, 1, 1, 6)
    if not okTF
        table.cell(tb, 0, 0, "Session Windows: use a 1 to 60 minute chart", text_color = color.white, bgcolor = COL_OUT, text_size = size.normal)
    else
        string curWin = in0 and on0 ? t0 : in1 and on1 ? t1 : in2 and on2 ? t2 : in4 and on4 ? t4 : in3 and on3 ? t3 : in5 and on5 ? t5 : ""
        string curSes = in0 and on0 ? s0 : in1 and on1 ? s1 : in2 and on2 ? s2 : in4 and on4 ? s4 : in3 and on3 ? s3 : in5 and on5 ? s5 : ""
        string status = curWin == "" ? "Now: outside the time windows" : "Now: " + f_name(curWin) + " window (" + f_sessTxt(curSes) + ")"
        table.cell(tb, 0, 0, status, text_color = color.white, bgcolor = curWin == "" ? COL_OUT : COL_IN, text_size = size.normal, text_halign = text.align_center)
        int r = 1
        if onAsia or onLdn or onGbx
            f_row(r, "Levels taken today", takenToday == "" ? "none yet" : takenToday, tblTxt)
            r += 1
        if onAsia
            f_row(r, "Asia high / low", f_fmt(asiaH) + " / " + f_fmt(asiaL), cAsia)
            r += 1
        if onLdn
            f_row(r, "London high / low", f_fmt(ldnH) + " / " + f_fmt(ldnL), cLdn)
            r += 1
        if onGbx
            f_row(r, "Overnight high / low", f_fmt(gbxH) + " / " + f_fmt(gbxL), cGbx)
            r += 1
        if showVwap
            f_row(r, "VWAP", na(volume) ? "no volume data" : seenAnchor ? f_fmt(vw) : "waiting for start", vwCol)

← 返回列表