Session Tracker [GoldenDream]

Golden_Dream · study · 426 行 · 点赞 24 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GoldenDream
//@version=6
// ════════════════════════════════════════════════════════════════════════════
//  Session Tracker [GoldenDream]
//
//  A clean, information-dense view of the Sydney, Tokyo, London and New York
//  sessions.
//
//  • Each session is defined in its OWN local time zone, so daylight saving
//    changes are handled automatically.
//  • Live session boxes with the range labelled.
//  • Completed session highs and lows extend forward as reference levels and
//    change style once price takes them out.
//  • Dashboard: status, countdown, range vs average, session direction, whether
//    the last session's high / low has been taken, and today's range vs ADR.
//  • Alerts for session opens / closes and session high / low breaks.
// ════════════════════════════════════════════════════════════════════════════
indicator("Session Tracker [GoldenDream]", shorttitle="Sessions", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
 
//────────────────────────────────────────────
// INPUTS
//────────────────────────────────────────────
grp_s = "Sessions (on · name · hours · time zone · colour)"
s1On   = input.bool(true, "", inline="s1", group=grp_s)
s1Name = input.string("Sydney", "", inline="s1", group=grp_s)
s1Time = input.session("0700-1600", "", inline="s1", group=grp_s)
s1Tz   = input.string("Australia/Sydney", "", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "UTC"], inline="s1", group=grp_s)
s1Col  = input.color(#9C6ADE, "", inline="s1", group=grp_s)
 
s2On   = input.bool(true, "", inline="s2", group=grp_s)
s2Name = input.string("Tokyo", "", inline="s2", group=grp_s)
s2Time = input.session("0900-1800", "", inline="s2", group=grp_s)
s2Tz   = input.string("Asia/Tokyo", "", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "UTC"], inline="s2", group=grp_s)
s2Col  = input.color(#E5534B, "", inline="s2", group=grp_s)
 
s3On   = input.bool(true, "", inline="s3", group=grp_s)
s3Name = input.string("London", "", inline="s3", group=grp_s)
s3Time = input.session("0800-1700", "", inline="s3", group=grp_s)
s3Tz   = input.string("Europe/London", "", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "UTC"], inline="s3", group=grp_s)
s3Col  = input.color(#3B82F6, "", inline="s3", group=grp_s)
 
s4On   = input.bool(true, "", inline="s4", group=grp_s)
s4Name = input.string("New York", "", inline="s4", group=grp_s)
s4Time = input.session("0800-1700", "", inline="s4", group=grp_s)
s4Tz   = input.string("America/New_York", "", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "UTC"], inline="s4", group=grp_s)
s4Col  = input.color(#F5A524, "", inline="s4", group=grp_s)
 
grp_c        = "Chart"
showBoxes    = input.bool(true, "Session boxes", group=grp_c)
boxTransp    = input.int(88, "Box transparency", minval=0, maxval=100, group=grp_c)
showLabels   = input.bool(true, "Session name and range labels", group=grp_c)
showOpen     = input.bool(false, "Session open price line", group=grp_c)
showMid      = input.bool(false, "Session midpoint line", group=grp_c)
extendLevels = input.bool(true, "Extend high / low after the session closes", group=grp_c, tooltip="The completed session's high and low are projected forward until that session opens again. Dotted = untouched, solid = taken out.")
stopOnBreak  = input.bool(true, "Stop extending a level once it's taken out", group=grp_c)
showOverlap  = input.bool(false, "Shade session overlaps", group=grp_c, tooltip="Light background shading whenever two or more sessions are open at once, e.g. London / New York.")
keepDays     = input.int(10, "Sessions kept on chart (per session)", minval=1, maxval=60, group=grp_c, tooltip="Older drawings are removed to keep the chart clean.")
rangeUnits   = input.string("Pips", "Range units", options=["Pips", "Price"], group=grp_c)
 
grp_d    = "Dashboard"
showDash = input.bool(true, "Show dashboard", group=grp_d)
dashMode = input.string("Full", "Detail", options=["Full", "Compact"], group=grp_d, tooltip="Compact shows status, range and range vs average only.")
dashPos  = input.string("Top Right", "Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grp_d)
dashSize = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=grp_d)
avgLen   = input.int(20, "Average range over N sessions", minval=1, maxval=200, group=grp_d)
adrLen   = input.int(14, "ADR length (days)", minval=1, maxval=100, group=grp_d)
clockTz  = input.string("UTC", "Clock time zone", options=["Australia/Sydney", "Australia/Melbourne", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "UTC"], group=grp_d)
 
grp_a        = "Alerts (create one alert: Any alert() function call)"
alertSession = input.bool(true, "Session opens and closes", group=grp_a)
alertBreaks  = input.bool(true, "Price takes out a completed session's high / low", group=grp_a)
 
//────────────────────────────────────────────
// TYPES + HELPERS
//────────────────────────────────────────────
type Sess
    string  name
    string  hours
    string  tz
    color   col
    bool    on
    bool    active = false
    bool    hiExt = false
    bool    loExt = false
    bool    hiTaken = false
    bool    loTaken = false
    bool    justOpened = false
    bool    justClosed = false
    bool    brokeHi = false
    bool    brokeLo = false
    float   hi
    float   lo
    float   op
    float   lastClose
    int     startBar
    float   lastRange
    box     bx
    label   lb
    line    hiLn
    line    loLn
    line    midLn
    line    opLn
    float[] ranges
    box[]   bxHist
    label[] lbHist
    line[]  lnHist
 
getPipsScale() =>
    is_jpy = str.contains(str.upper(syminfo.ticker), "JPY")
    is_fx  = syminfo.type == "forex"
    is_idx = syminfo.type == "index" or syminfo.type == "cfd"
    is_fx ? (is_jpy ? 0.01 : 0.0001) : (is_idx ? 0.1 : syminfo.mintick)
pip_unit = getPipsScale()
 
f_rng(float r) =>
    na(r) ? "—" : rangeUnits == "Pips" ? str.tostring(r / pip_unit, "#,###") + " pips" : str.tostring(r, format.mintick)
 
f_signed(float v) =>
    na(v) ? "—" : (v > 0 ? "▲ " : v < 0 ? "▼ " : "") + (rangeUnits == "Pips" ? str.tostring(math.abs(v) / pip_unit, "#,###") : str.tostring(math.abs(v), format.mintick))
 
f_dur(int ms) =>
    int totalMin = int(math.max(ms, 0) / 60000)
    int h = int(totalMin / 60)
    int m = totalMin % 60
    h > 0 ? str.tostring(h) + "h " + str.tostring(m) + "m" : str.tostring(m) + "m"
 
f_parse(string hrs) =>
    int sh = int(str.tonumber(str.substring(hrs, 0, 2)))
    int sm = int(str.tonumber(str.substring(hrs, 2, 4)))
    int eh = int(str.tonumber(str.substring(hrs, 5, 7)))
    int em = int(str.tonumber(str.substring(hrs, 7, 9)))
    [sh, sm, eh, em]
 
// Milliseconds until the session next closes (if open) or opens (if closed),
// worked out in the session's own time zone. Weekends are skipped.
f_countdown(string hrs, string tz, bool isOpen) =>
    [sh, sm, eh, em] = f_parse(hrs)
    int now = timenow
    int y  = year(now, tz)
    int mo = month(now, tz)
    int d  = dayofmonth(now, tz)
    int target = na
    if isOpen
        target := timestamp(tz, y, mo, d, eh, em)
        if target <= now
            target := target + 86400000
    else
        target := timestamp(tz, y, mo, d, sh, sm)
        if target <= now
            target := target + 86400000
        int guard = 0
        while (dayofweek(target, tz) == dayofweek.saturday or dayofweek(target, tz) == dayofweek.sunday) and guard < 3
            target := target + 86400000
            guard += 1
        target := timestamp(tz, year(target, tz), month(target, tz), dayofmonth(target, tz), sh, sm)
    target - now
 
method trimHistory(Sess this, int linesPerSession) =>
    while this.bxHist.size() > keepDays
        box.delete(this.bxHist.shift())
    while this.lbHist.size() > keepDays
        label.delete(this.lbHist.shift())
    while this.lnHist.size() > keepDays * linesPerSession
        line.delete(this.lnHist.shift())
 
method update(Sess this, bool inS, int linesPerSession) =>
    this.justOpened := false
    this.justClosed := false
    this.brokeHi    := false
    this.brokeLo    := false
 
    if inS and not this.active
        // ── session opens ──
        this.active     := true
        this.justOpened := true
        this.hiExt      := false
        this.loExt      := false
        this.hiTaken    := false
        this.loTaken    := false
        this.hi         := high
        this.lo         := low
        this.op         := open
        this.lastClose  := close
        this.startBar   := bar_index
        if showBoxes
            this.bx := box.new(bar_index, high, bar_index, low, border_color=color.new(this.col, 35), bgcolor=color.new(this.col, boxTransp), border_width=1)
            this.bxHist.push(this.bx)
        if showLabels
            this.lb := label.new(bar_index, high, this.name, style=label.style_label_lower_left, color=color(na), textcolor=this.col, size=size.small)
            this.lbHist.push(this.lb)
        if extendLevels
            this.hiLn := line.new(bar_index, high, bar_index, high, color=color.new(this.col, 30), style=line.style_dotted)
            this.loLn := line.new(bar_index, low, bar_index, low, color=color.new(this.col, 30), style=line.style_dotted)
            this.lnHist.push(this.hiLn)
            this.lnHist.push(this.loLn)
        if showMid
            this.midLn := line.new(bar_index, hl2, bar_index, hl2, color=color.new(this.col, 50), style=line.style_dashed)
            this.lnHist.push(this.midLn)
        if showOpen
            this.opLn := line.new(bar_index, open, bar_index, open, color=color.new(this.col, 20), width=1)
            this.lnHist.push(this.opLn)
        this.trimHistory(linesPerSession)
    else if inS and this.active
        // ── session in progress ──
        this.hi        := math.max(this.hi, high)
        this.lo        := math.min(this.lo, low)
        this.lastClose := close
        if showBoxes
            box.set_top(this.bx, this.hi)
            box.set_bottom(this.bx, this.lo)
            box.set_right(this.bx, bar_index)
    else if not inS and this.active
        // ── session closed on the previous bar ──
        this.active     := false
        this.justClosed := true
        this.lastRange  := this.hi - this.lo
        this.ranges.push(this.lastRange)
        if this.ranges.size() > avgLen
            this.ranges.shift()
        this.hiExt := extendLevels
        this.loExt := extendLevels
        if showLabels and not na(this.lb)
            label.set_text(this.lb, this.name + "  " + f_rng(this.lastRange))
 
    // ── after the close: watch for the high / low being taken out ──
    if not this.active and not na(this.lastRange)
        if not this.hiTaken and high > this.hi
            this.hiTaken := true
            this.brokeHi := true
            if extendLevels
                line.set_style(this.hiLn, line.style_solid)
                line.set_color(this.hiLn, color.new(this.col, 65))
                line.set_x2(this.hiLn, bar_index)
            if stopOnBreak
                this.hiExt := false
        if not this.loTaken and low < this.lo
            this.loTaken := true
            this.brokeLo := true
            if extendLevels
                line.set_style(this.loLn, line.style_solid)
                line.set_color(this.loLn, color.new(this.col, 65))
                line.set_x2(this.loLn, bar_index)
            if stopOnBreak
                this.loExt := false
 
    // ── live drawing updates ──
    if extendLevels
        if this.active
            line.set_xy1(this.hiLn, this.startBar, this.hi)
            line.set_xy2(this.hiLn, bar_index, this.hi)
            line.set_xy1(this.loLn, this.startBar, this.lo)
            line.set_xy2(this.loLn, bar_index, this.lo)
        else
            if this.hiExt
                line.set_x2(this.hiLn, bar_index)
            if this.loExt
                line.set_x2(this.loLn, bar_index)
    if this.active
        float mid = (this.hi + this.lo) / 2
        if showMid
            line.set_xy1(this.midLn, this.startBar, mid)
            line.set_xy2(this.midLn, bar_index, mid)
        if showOpen
            line.set_x2(this.opLn, bar_index)
        if showLabels and not na(this.lb)
            label.set_y(this.lb, this.hi)
            label.set_text(this.lb, this.name + "  " + f_rng(this.hi - this.lo))
 
method fireAlerts(Sess this) =>
    if alertSession and this.justOpened
        alert(this.name + " session open | " + syminfo.ticker + " at " + str.tostring(open, format.mintick), alert.freq_once_per_bar)
    if alertSession and this.justClosed
        alert(this.name + " session closed | " + syminfo.ticker + " | Range " + f_rng(this.lastRange) + " | High " + str.tostring(this.hi, format.mintick) + " | Low " + str.tostring(this.lo, format.mintick), alert.freq_once_per_bar)
    if alertBreaks and this.brokeHi
        alert(syminfo.ticker + " took out the " + this.name + " high (" + str.tostring(this.hi, format.mintick) + ")", alert.freq_once_per_bar)
    if alertBreaks and this.brokeLo
        alert(syminfo.ticker + " took out the " + this.name + " low (" + str.tostring(this.lo, format.mintick) + ")", alert.freq_once_per_bar)
 
//────────────────────────────────────────────
// SESSION STATE
//────────────────────────────────────────────
var Sess S1 = Sess.new(name=s1Name, hours=s1Time, tz=s1Tz, col=s1Col, on=s1On, ranges=array.new<float>(), bxHist=array.new<box>(), lbHist=array.new<label>(), lnHist=array.new<line>())
var Sess S2 = Sess.new(name=s2Name, hours=s2Time, tz=s2Tz, col=s2Col, on=s2On, ranges=array.new<float>(), bxHist=array.new<box>(), lbHist=array.new<label>(), lnHist=array.new<line>())
var Sess S3 = Sess.new(name=s3Name, hours=s3Time, tz=s3Tz, col=s3Col, on=s3On, ranges=array.new<float>(), bxHist=array.new<box>(), lbHist=array.new<label>(), lnHist=array.new<line>())
var Sess S4 = Sess.new(name=s4Name, hours=s4Time, tz=s4Tz, col=s4Col, on=s4On, ranges=array.new<float>(), bxHist=array.new<box>(), lbHist=array.new<label>(), lnHist=array.new<line>())
 
// Mon–Fri in each session's own time zone
bool in1 = s1On and not na(time(timeframe.period, s1Time + ":23456", s1Tz))
bool in2 = s2On and not na(time(timeframe.period, s2Time + ":23456", s2Tz))
bool in3 = s3On and not na(time(timeframe.period, s3Time + ":23456", s3Tz))
bool in4 = s4On and not na(time(timeframe.period, s4Time + ":23456", s4Tz))
 
int linesPer = (extendLevels ? 2 : 0) + (showMid ? 1 : 0) + (showOpen ? 1 : 0)
 
if timeframe.isintraday
    S1.update(in1, linesPer)
    S2.update(in2, linesPer)
    S3.update(in3, linesPer)
    S4.update(in4, linesPer)
    S1.fireAlerts()
    S2.fireAlerts()
    S3.fireAlerts()
    S4.fireAlerts()
 
int openCount = (in1 ? 1 : 0) + (in2 ? 1 : 0) + (in3 ? 1 : 0) + (in4 ? 1 : 0)
bgcolor(showOverlap and timeframe.isintraday and openCount >= 2 ? color.new(#8A919E, 92) : na, title="Session overlap")
 
// Simple per-session alert conditions (alternative to the single alert() alert)
alertcondition(in1 and not in1[1], "Session 1 open", "Session 1 open on {{ticker}}")
alertcondition(in2 and not in2[1], "Session 2 open", "Session 2 open on {{ticker}}")
alertcondition(in3 and not in3[1], "Session 3 open", "Session 3 open on {{ticker}}")
alertcondition(in4 and not in4[1], "Session 4 open", "Session 4 open on {{ticker}}")
 
//────────────────────────────────────────────
// DAILY RANGE VS ADR
//────────────────────────────────────────────
[dHigh, dLow] = request.security(syminfo.tickerid, "D", [high, low], lookahead=barmerge.lookahead_off)
float adr = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLen)[1], lookahead=barmerge.lookahead_on)
float dayRange = dHigh - dLow
 
//────────────────────────────────────────────
// DASHBOARD
//────────────────────────────────────────────
f_pos(string s) =>
    s == "Top Right" ? position.top_right : s == "Top Left" ? position.top_left : s == "Bottom Right" ? position.bottom_right : position.bottom_left
 
txtSize = dashSize == "Tiny" ? size.tiny : dashSize == "Normal" ? size.normal : size.small
bool full = dashMode == "Full"
int nCols = full ? 8 : 4
color bgMain  = color.new(#0F1115, 5)
color bgHead  = color.new(#1C2027, 0)
color txtDim  = #8A919E
color txtMain = #E6E8EB
color colUp   = #22C55E
color colDn   = #EF4444
color colHot  = #F5A524
 
f_cell(table t, int c, int r, string s, color tc, color bg, string align) =>
    table.cell(t, c, r, s, text_color=tc, bgcolor=bg, text_size=txtSize, text_halign=align)
 
f_row(table t, int r, Sess s, bool inS) =>
    if not s.on
        f_cell(t, 0, r, s.name, txtDim, color(na), text.align_left)
        f_cell(t, 1, r, "OFF", txtDim, color(na), text.align_center)
        for k = 2 to nCols - 1
            f_cell(t, k, r, "", txtDim, color(na), text.align_center)
    else
        float rng   = s.active ? s.hi - s.lo : s.lastRange
        float avg   = s.ranges.size() > 0 ? s.ranges.avg() : na
        float ratio = na(avg) or avg == 0 or na(rng) ? na : rng / avg * 100
        color ratioCol = na(ratio) ? txtDim : ratio >= 120 ? colHot : ratio <= 80 ? txtDim : txtMain
        float chg   = na(s.op) ? na : s.lastClose - s.op
        string hl   = s.active ? "live" : na(s.lastRange) ? "—" : s.hiTaken and s.loTaken ? "↑ ↓" : s.hiTaken ? "↑ high" : s.loTaken ? "↓ low" : "intact"
        color hlCol = s.active ? txtDim : s.hiTaken and s.loTaken ? colHot : s.hiTaken ? colUp : s.loTaken ? colDn : txtMain
 
        int c = 0
        f_cell(t, c, r, "■ " + s.name, s.col, color(na), text.align_left)
        c += 1
        f_cell(t, c, r, inS ? "● OPEN" : "closed", inS ? colUp : txtDim, color(na), text.align_center)
        c += 1
        if full
            int left = f_countdown(s.hours, s.tz, inS)
            f_cell(t, c, r, (inS ? "closes " : "opens ") + f_dur(left), inS ? txtMain : txtDim, color(na), text.align_right)
            c += 1
        f_cell(t, c, r, f_rng(rng), txtMain, color(na), text.align_right)
        c += 1
        if full
            f_cell(t, c, r, f_rng(avg), txtDim, color(na), text.align_right)
            c += 1
        f_cell(t, c, r, na(ratio) ? "—" : str.tostring(ratio, "#") + "%", ratioCol, color(na), text.align_right)
        c += 1
        if full
            f_cell(t, c, r, f_signed(chg), na(chg) ? txtDim : chg > 0 ? colUp : chg < 0 ? colDn : txtMain, color(na), text.align_right)
            c += 1
            f_cell(t, c, r, hl, hlCol, color(na), text.align_right)
 
var table dash = na
if showDash and barstate.islast
    if na(dash)
        dash := table.new(f_pos(dashPos), 8, 8, bgcolor=bgMain, border_color=color.new(#2A2F37, 0), border_width=1, frame_color=color.new(#2A2F37, 0), frame_width=1)
    table.clear(dash, 0, 0, 7, 7)
 
    // header
    f_cell(dash, 0, 0, "SESSIONS", txtMain, bgHead, text.align_left)
    f_cell(dash, 1, 0, "GoldenDream", #D4AF37, bgHead, text.align_center)
    for hc = 2 to nCols - 2
        f_cell(dash, hc, 0, "", txtMain, bgHead, text.align_center)
    f_cell(dash, nCols - 1, 0, str.format_time(timenow, "EEE HH:mm", clockTz), txtDim, bgHead, text.align_right)
 
    // column titles
    int c = 0
    f_cell(dash, c, 1, "SESSION", txtDim, color(na), text.align_left)
    c += 1
    f_cell(dash, c, 1, "STATUS", txtDim, color(na), text.align_center)
    c += 1
    if full
        f_cell(dash, c, 1, "NEXT", txtDim, color(na), text.align_right)
        c += 1
    f_cell(dash, c, 1, "RANGE", txtDim, color(na), text.align_right)
    c += 1
    if full
        f_cell(dash, c, 1, "AVG (" + str.tostring(avgLen) + ")", txtDim, color(na), text.align_right)
        c += 1
    f_cell(dash, c, 1, "VS AVG", txtDim, color(na), text.align_right)
    c += 1
    if full
        f_cell(dash, c, 1, "OPEN→CLOSE", txtDim, color(na), text.align_right)
        c += 1
        f_cell(dash, c, 1, "H / L TAKEN", txtDim, color(na), text.align_right)
 
    if timeframe.isintraday
        f_row(dash, 2, S1, in1)
        f_row(dash, 3, S2, in2)
        f_row(dash, 4, S3, in3)
        f_row(dash, 5, S4, in4)
 
        // today's range vs average daily range
        float adrPct = na(adr) or adr == 0 ? na : dayRange / adr * 100
        f_cell(dash, 0, 6, "TODAY", txtMain, bgHead, text.align_left)
        f_cell(dash, 1, 6, f_rng(dayRange), txtMain, bgHead, text.align_center)
        for cc = 2 to nCols - 2
            f_cell(dash, cc, 6, "", txtMain, bgHead, text.align_center)
        f_cell(dash, nCols - 1, 6, na(adrPct) ? "ADR —" : str.tostring(adrPct, "#") + "% of ADR (" + f_rng(adr) + ")", na(adrPct) ? txtDim : adrPct >= 100 ? colHot : txtMain, bgHead, text.align_right)
    else
        f_cell(dash, 0, 2, "Use an intraday timeframe (1H or lower)", colHot, color(na), text.align_left)

← 返回列表