Session Boxes

zidery333 · study · 238 行 · 点赞 21 · 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/
// © Zid
 
//@version=6
indicator("Session Boxes", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// Default times are ICT kill zones, in New York time.
 
// ─── Colours ───────────────────────────────────────────────────────────────
// Defaults come from Zid's chart. On a dark chart, Auto swaps to light text and lines.
CREAM = #F5EBE0
TAN   = #D4A276
BROWN = #583101
 
// ─── Inputs ────────────────────────────────────────────────────────────────
GRP_SESSIONS = "Kill zones"
GRP_BOX      = "Boxes"
GRP_OPEN     = "NY open line"
GRP_LEVELS   = "High / low lines"
GRP_COLOURS  = "Colours"
 
asiaOnInput      = input.bool(true, "", inline = "asia", group = GRP_SESSIONS, display = display.none)
asiaNameInput    = input.string("Asia", "", inline = "asia", group = GRP_SESSIONS, display = display.none)
asiaTimeInput    = input.session("2000-0000", "", inline = "asia", group = GRP_SESSIONS, display = display.none)
asiaColorInput   = input.color(TAN, "", inline = "asia", group = GRP_SESSIONS, display = display.none)
 
londonOnInput    = input.bool(true, "", inline = "london", group = GRP_SESSIONS, display = display.none)
londonNameInput  = input.string("London", "", inline = "london", group = GRP_SESSIONS, display = display.none)
londonTimeInput  = input.session("0200-0500", "", inline = "london", group = GRP_SESSIONS, display = display.none)
londonColorInput = input.color(TAN, "", inline = "london", group = GRP_SESSIONS, display = display.none)
 
nyOnInput        = input.bool(true, "", inline = "ny", group = GRP_SESSIONS, display = display.none)
nyNameInput      = input.string("NY", "", inline = "ny", group = GRP_SESSIONS, display = display.none)
nyTimeInput      = input.session("0700-1000", "", inline = "ny", group = GRP_SESSIONS, display = display.none)
nyColorInput     = input.color(TAN, "", inline = "ny", group = GRP_SESSIONS, display = display.none)
 
timezoneInput    = input.string("America/New_York", "Time zone", group = GRP_SESSIONS,
     tooltip = "The time zone the times above are in. Examples: America/New_York, Europe/London, Asia/Tokyo, UTC", display = display.none)
daysInput        = input.int(5, "Days to show", minval = 1, maxval = 120, group = GRP_SESSIONS, display = display.none)
 
showBoxInput     = input.bool(true, "Show boxes", group = GRP_BOX, display = display.none)
fillInput        = input.int(82, "Fill see-through %", minval = 0, maxval = 100, group = GRP_BOX, display = display.none)
borderStyleInput = input.string("Solid", "Border", options = ["Solid", "Dashed", "Dotted", "None"], inline = "border", group = GRP_BOX, display = display.none)
borderInput      = input.int(45, "see-through %", minval = 0, maxval = 100, inline = "border", group = GRP_BOX, display = display.none)
showNamesInput   = input.bool(true, "Names", inline = "names", group = GRP_BOX, display = display.none)
nameSizeInput    = input.int(10, "Size", minval = 6, maxval = 40, inline = "names", group = GRP_BOX, display = display.none)
 
showOpenInput    = input.bool(true, "Show NY open line", group = GRP_OPEN,
     tooltip = "A line from top to bottom of the chart at the New York open each day, in the time zone above.", display = display.none)
openHourInput    = input.int(9, "At", minval = 0, maxval = 23, inline = "opentime", group = GRP_OPEN, display = display.none)
openMinuteInput  = input.int(30, ":", minval = 0, maxval = 59, inline = "opentime", group = GRP_OPEN, display = display.none)
openStyleInput   = input.string("Dotted", "Line", options = ["Solid", "Dashed", "Dotted"], inline = "open", group = GRP_OPEN, display = display.none)
openWidthInput   = input.int(1, "Width", minval = 1, maxval = 4, inline = "open", group = GRP_OPEN, display = display.none)
 
showLevelsInput  = input.bool(true, "Show high / low lines", group = GRP_LEVELS,
     tooltip = "When a kill zone ends, its high and low carry forward to the right.", display = display.none)
whenTakenInput   = input.string("Stop at the touch", "When price takes a line", options = ["Stop at the touch", "Keep extending", "Remove it"], group = GRP_LEVELS, display = display.none)
lineStyleInput   = input.string("Solid", "Line", options = ["Solid", "Dashed", "Dotted"], inline = "line", group = GRP_LEVELS, display = display.none)
lineWidthInput   = input.int(1, "Width", minval = 1, maxval = 4, inline = "line", group = GRP_LEVELS, display = display.none)
showTagsInput    = input.bool(true, "Line names", inline = "tags", group = GRP_LEVELS, display = display.none)
tagSizeInput     = input.int(9, "Size", minval = 6, maxval = 30, inline = "tags", group = GRP_LEVELS, display = display.none)
reachInput       = input.int(5, "Lines reach past price by", minval = 0, maxval = 50, group = GRP_LEVELS,
     tooltip = "How many bars past the newest candle a live line reaches, so its name sits clear of price.", display = display.none)
alertsInput      = input.bool(true, "Alert when a line is taken", group = GRP_LEVELS,
     tooltip = "Works with the lines hidden too. To get these, create an alert on this script and choose 'Any alert() function call'.", display = display.none)
 
colourModeInput  = input.string("Auto", "Text and lines", options = ["Auto", "Custom"], group = GRP_COLOURS,
     tooltip = "Auto: brown on light charts, cream on dark charts. Custom: use the two colours below.", display = display.none)
nameColorInput   = input.color(BROWN, "Names", inline = "custom", group = GRP_COLOURS, active = colourModeInput == "Custom", display = display.none)
lineColorInput   = input.color(color.new(BROWN, 35), "Lines", inline = "custom", group = GRP_COLOURS, active = colourModeInput == "Custom", display = display.none)
openColorInput   = input.color(color.new(BROWN, 45), "Open line", inline = "custom", group = GRP_COLOURS, active = colourModeInput == "Custom", display = display.none)
 
// ─── Colours in use ────────────────────────────────────────────────────────
bool  isDarkChart = color.r(chart.bg_color) * 0.299 + color.g(chart.bg_color) * 0.587 + color.b(chart.bg_color) * 0.114 < 128
bool  autoColours = colourModeInput == "Auto"
color nameColor   = autoColours ? (isDarkChart ? CREAM : BROWN) : nameColorInput
color lineColor   = autoColours ? (isDarkChart ? color.new(TAN, 25) : color.new(BROWN, 35)) : lineColorInput
color openColor   = autoColours ? (isDarkChart ? color.new(TAN, 40) : color.new(BROWN, 45)) : openColorInput
 
// Every line taken on this candle, so they all go out in one alert.
array<string> takenNow = array.new<string>()
 
// ─── Types and functions ───────────────────────────────────────────────────
// One carried-forward high or low.
type Level
    line   ln
    label  tag
    string name
    string day
    float  price
    bool   isHigh
    bool   swept = false
    bool   done  = false
 
// The time today at hh:mm in the chosen time zone.
clockTime(int hh, int mm) =>
    timestamp(timezoneInput, year(time, timezoneInput), month(time, timezoneInput), dayofmonth(time, timezoneInput), hh, mm)
 
lineStyle(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
// With the lines hidden it draws nothing, but still watches the price for alerts.
newLevel(string name, string day, float price, bool isHigh, int fromBar, int x) =>
    line ln = na
    label tag = na
    if showLevelsInput
        ln := line.new(fromBar, price, x, price, color = lineColor, width = lineWidthInput, style = lineStyle(lineStyleInput))
    if showLevelsInput and showTagsInput
        tag := label.new(x, price, name + (isHigh ? " high" : " low"), style = label.style_label_lower_right,
             color = color.new(BROWN, 100), textcolor = lineColor, size = tagSizeInput, textalign = text.align_right)
    Level.new(ln, tag, name, day, price, isHigh)
 
// Moves the line's end, and its name with it.
moveLevel(Level lv, int x) =>
    if not na(lv.ln)
        lv.ln.set_x2(x)
    if not na(lv.tag)
        lv.tag.set_x(x)
 
// A taken line goes quiet: it fades and loses its name.
fadeLevel(Level lv) =>
    if not na(lv.tag)
        label.delete(lv.tag)
        lv.tag := na
    if not na(lv.ln)
        lv.ln.set_color(color.new(lineColor, 80))
 
deleteLevel(Level lv) =>
    line.delete(lv.ln)
    if not na(lv.tag)
        label.delete(lv.tag)
 
// Notes a line the first time price trades through it, e.g. "Tue London high 29,281.50".
noteTaken(Level lv) =>
    takenNow.push(lv.day + " " + lv.name + (lv.isHigh ? " high " : " low ") + str.tostring(lv.price, format.mintick))
 
// Draws one kill zone and its lines. Each call keeps its own drawings.
drawSession(bool on, string name, string sess, color col) =>
    var box   current = na
    var label title   = na
    var int   highBar = na
    var int   lowBar  = na
    var array<box>   boxes  = array.new<box>()
    var array<label> titles = array.new<label>()
    var array<Level> levels = array.new<Level>()
 
    bool inSession = on and timeframe.isintraday and not na(time(timeframe.period, sess, timezoneInput))
    bool started   = inSession and not inSession[1]
    bool ended     = not inSession and inSession[1]
 
    // The box grows with the kill zone.
    if started
        current := box.new(bar_index, high, bar_index + 1, low,
             border_color = borderStyleInput == "None" or not showBoxInput ? na : color.new(col, borderInput),
             border_width = 1, border_style = lineStyle(borderStyleInput),
             bgcolor = showBoxInput ? color.new(col, fillInput) : na)
        title := showNamesInput ? label.new(bar_index, high, name, style = label.style_label_down,
             color = color.new(BROWN, 100), textcolor = nameColor, size = nameSizeInput) : na
        highBar := bar_index
        lowBar  := bar_index
        boxes.push(current)
        titles.push(title)
        if boxes.size() > daysInput
            box.delete(boxes.shift())
            label.delete(titles.shift())
    else if inSession and not na(current)
        current.set_right(bar_index + 1)
        if high > current.get_top()
            current.set_top(high)
            highBar := bar_index
        if low < current.get_bottom()
            current.set_bottom(low)
            lowBar := bar_index
        // Keep the name centred above the box.
        if not na(title)
            title.set_xy(int(math.round((current.get_left() + current.get_right()) / 2)), current.get_top())
 
    // When it ends, its high and low start carrying forward.
    // The day is the one the kill zone ends on, so Asia counts as the next day.
    if ended and (showLevelsInput or alertsInput) and not na(current)
        string endDay = str.format_time(time, "EEE", timezoneInput)
        levels.push(newLevel(name, endDay, current.get_top(), true, highBar, bar_index + reachInput))
        levels.push(newLevel(name, endDay, current.get_bottom(), false, lowBar, bar_index + reachInput))
        while levels.size() > daysInput * 2
            deleteLevel(levels.shift())
 
    // Extend each line until price takes it.
    for lv in levels
        if not lv.done
            bool taken = lv.isHigh ? high > lv.price : low < lv.price
            if taken and not lv.swept
                lv.swept := true
                noteTaken(lv)
            if taken and whenTakenInput == "Remove it"
                lv.done := true
                deleteLevel(lv)
            else if taken and whenTakenInput == "Stop at the touch"
                lv.done := true
                moveLevel(lv, bar_index)
                fadeLevel(lv)
            else
                moveLevel(lv, bar_index + reachInput)
                if lv.swept
                    fadeLevel(lv)
 
// ─── Drawing ───────────────────────────────────────────────────────────────
drawSession(asiaOnInput, asiaNameInput, asiaTimeInput, asiaColorInput)
drawSession(londonOnInput, londonNameInput, londonTimeInput, londonColorInput)
drawSession(nyOnInput, nyNameInput, nyTimeInput, nyColorInput)
 
// ─── NY open line ──────────────────────────────────────────────────────────
// On the first candle that starts at or after the open, the same candle the NY box starts on.
// A chart can only draw on a candle: 09:30 on 1m to 30m, 09:32 on 4m, 10:00 on 1h.
var array<line> openLines = array.new<line>()
bool afterOpen = time >= clockTime(openHourInput, openMinuteInput)
if showOpenInput and timeframe.isintraday and afterOpen and not afterOpen[1]
    openLines.push(line.new(bar_index, high, bar_index, low - syminfo.mintick, extend = extend.both,
         color = openColor, width = openWidthInput, style = lineStyle(openStyleInput)))
    if openLines.size() > daysInput
        line.delete(openLines.shift())
 
// ─── Alert ─────────────────────────────────────────────────────────────────
// One alert names every line taken, e.g. "NQ1! took Tue London high 29,281.50".
// Each line alerts once, even when a second one is taken later in the same candle.
varip array<string> alerted = array.new<string>()
if alertsInput and barstate.isrealtime
    array<string> fresh = array.new<string>()
    for s in takenNow
        if not alerted.includes(s)
            fresh.push(s)
            alerted.push(s)
    if fresh.size() > 0
        alert(syminfo.ticker + " took " + fresh.join(", "), alert.freq_all)
    while alerted.size() > 200
        alerted.shift()

← 返回列表