Opening Prices

NobleArt · study · 1037 行 · 点赞 1 · 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/
// © shadow
// Created: 2026-09-06
// Last modified: 2026-09-06
// version 1.2
//
// 1.2 - Added an "Intraday Opens" section: twelve opens anchored to a time of day, selectable in
//       30 minute steps on a 24 hour clock, with a timezone selector defaulting to New York. An
//       intraday open is drawn only where a candle on the current chart timeframe opens exactly on
//       the selected time.
//       Only 06:00 and 10:00 are enabled by default, and a "Show Intraday Opens" master switch
//       gates the whole section without disturbing the individual ticks.
//     - Every level now defaults to `COLOR_DEFAULT`, black at 60% transparency, in place of the five
//       per-open colors.
//     - Replaced `draw()` with `drawLevel()`, which takes its drawing state as a `Level` argument so
//       that one routine can serve all seventeen levels from a loop.
//     - Added a "Label Spacing" input, the ATR(10) multiplier deciding when two opens are close
//       enough for the later one's label to be fanned right. Was a fixed half ATR; 0 turns the fan
//       out off and ends every line flush.
//     - The 1 month and 12 month opens now default to off.
//
// -----------------------------------------------------------------------------------------------
// 
 
// @version=6
indicator("Daily Weekly Monthly Yearly Opens", "Opens", overlay = true, max_lines_count = 500, dynamic_requests = true)
 
 
//--------------------------------------------------------------------
//#region                      Constants
//--------------------------------------------------------------------
 
color   COLOR_DEFAULT   = color.new(color.black, 60)
int     HEAD_PADDING    = -2
int     HEAD_TRANSP     = 60
string  LABEL_SIZE      = size.small
string  LABEL_STYLE     = label.style_none
string  LINE_STYLE      = line.style_solid
int     LINE_WIDTH      = 1
int     OFFSET_PADDING  = 4
string  TAIL_STYLE      = line.style_dotted
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                         Types
//--------------------------------------------------------------------
 
// @type Contains the open's data.
type Open
    int     barIndex
    float   price
    string  name
    bool    display
 
 
// @type Holds the drawing objects belonging to one level. Keeping this state outside `drawLevel()`
//       is what lets a single routine serve every level from a loop: a `var` declared inside a
//       function belongs to its call site, so a looped call would share one set of drawings.
type Level
    line        body
    label       tag
    line        tail
    array<line> bodies
    array<line> heads
 
 
// @enum Contains fields with configurable timeframe options as titles.
enum Timeframes
    s5  = "5 seconds"
    s10 = "10 seconds"
    s15 = "15 seconds"
    s30 = "30 seconds"
    m1  = "1 minute"
    m2  = "2 minutes"
    m3  = "3 minutes"
    m5  = "5 minutes"
    m10 = "10 minutes"
    m15 = "15 minutes"
    m30 = "30 minutes"
    m45 = "45 minutes"
    h1  = "1 hour"
    h2  = "2 hours"
    h3  = "3 hours"
    h4  = "4 hours"
    h6  = "6 hours"
    h8  = "8 hours"
    h12 = "12 hours"
    D1  = "1 day"
    W1  = "1 week"
    M1  = "1 month"
    M3  = "3 months"
    M6  = "6 months"
    M12 = "12 months"
 
 
// @enum Contains the intraday open times, on a 24 hour clock in 30 minute steps.
enum Timeslots
    t0000 = "00:00"
    t0030 = "00:30"
    t0100 = "01:00"
    t0130 = "01:30"
    t0200 = "02:00"
    t0230 = "02:30"
    t0300 = "03:00"
    t0330 = "03:30"
    t0400 = "04:00"
    t0430 = "04:30"
    t0500 = "05:00"
    t0530 = "05:30"
    t0600 = "06:00"
    t0630 = "06:30"
    t0700 = "07:00"
    t0730 = "07:30"
    t0800 = "08:00"
    t0830 = "08:30"
    t0900 = "09:00"
    t0930 = "09:30"
    t1000 = "10:00"
    t1030 = "10:30"
    t1100 = "11:00"
    t1130 = "11:30"
    t1200 = "12:00"
    t1230 = "12:30"
    t1300 = "13:00"
    t1330 = "13:30"
    t1400 = "14:00"
    t1430 = "14:30"
    t1500 = "15:00"
    t1530 = "15:30"
    t1600 = "16:00"
    t1630 = "16:30"
    t1700 = "17:00"
    t1730 = "17:30"
    t1800 = "18:00"
    t1830 = "18:30"
    t1900 = "19:00"
    t1930 = "19:30"
    t2000 = "20:00"
    t2030 = "20:30"
    t2100 = "21:00"
    t2130 = "21:30"
    t2200 = "22:00"
    t2230 = "22:30"
    t2300 = "23:00"
    t2330 = "23:30"
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                        Inputs
//--------------------------------------------------------------------
 
string      group1                      = "Opens"
string      group4                      = "Intraday Opens"
string      group2                      = "Style"
string      group3                      = "Preferences"
 
string      rightOffsetTooltip          = "Extend the current opens to the right of the last bar."
string      labelSpacingTooltip         = "How far apart two opens have to be before their labels are allowed to share the same " +
                                          "right edge, as a multiple of ATR(10)." +
                                          "\n\nEach open whose price falls within this distance of an earlier one is fanned 4 bars " +
                                          "further right so the labels do not sit on top of each other." +
                                          "\n\nLower it when levels that look well separated are still being fanned out. Set it to 0 " +
                                          "to switch the fan out off entirely and end every line flush."
string      tailsTooltip                = "Extend the current opens to the left of the chart."
string      headsTooltip                = "Extend the previous opens to the right."
string      discoverPricesTooltip       = "Discover the opens on the chart instead of requesting higher-timeframe data." +
                                          "\n\nYou can use this setting when price discrepancies exist between the chart and end-of-day data feeds." +
                                          "\n\nOn continuous futures contracts (GC1!, NQ1!, ES1!, ...) this also keeps the levels correct across a " +
                                          "contract rollover: the requested higher-timeframe open still carries the expiring contract's price, while " +
                                          "the chart's own bars are the ones you are actually trading." +
                                          "\n\nApplies to daily-or-higher opens on any chart timeframe lower than the open's timeframe."
string      extendedHoursTooltip        = "If the extended trading hours are visible on the intraday chart, display the opens on the pre/post market session."
string      intradayTimeTooltip         = "Anchor a level to the opening price of a specific time of day, in 30 minute steps. " +
                                          "Requires an intraday chart." +
                                          "\n\nThe level only appears when a candle on the current chart timeframe opens exactly on the selected " +
                                          "time. 10:00 resolves on the 1H and 4H charts; 09:30 needs a 30 minute chart or lower on a 24 hour " +
                                          "session; a 90 minute chart resolves only the times its own grid lands on, such as 06:00 and 09:00." +
                                          "\n\nWhen the chart's candles do not line up with the selected time, the level stays hidden rather than " +
                                          "anchoring to the wrong bar. Switch to a lower timeframe to bring it back." +
                                          "\n\nDays with no candle at that time (a holiday, a half session, or a time outside the visible session) " +
                                          "produce no new level, and the previous one carries forward."
string      intradayTimezoneTooltip     = "The timezone the intraday open times are expressed in." +
                                          "\n\n\"Exchange\" uses the symbol's own timezone."
string      intradayMasterTooltip       = "A master switch for the whole section. Untick it to clear every intraday open off the " +
                                          "chart in one click, and tick it again to bring back exactly the times you had selected." +
                                          "\n\nThe individual ticks below are left untouched, so a trading layout and a journaling " +
                                          "layout are one checkbox apart."
 
bool        enableOpenInput1            = input.bool  (true,           title = "",                 group = group1, inline = "#1")
Timeframes  openTimeframeInput1         = input.enum  (Timeframes.D1,  title = "",                 group = group1, inline = "#1", display = display.none)
color       openColorInput1             = input.color (COLOR_DEFAULT,  title = "",                 group = group1, inline = "#1")
int         openLookbackInput1          = input.int   (1,              title = "",                 group = group1, inline = "#1", minval = 1, maxval = 500, display = display.none)
bool        enableOpenInput2            = input.bool  (true,           title = "",                 group = group1, inline = "#2")
Timeframes  openTimeframeInput2         = input.enum  (Timeframes.W1,  title = "",                 group = group1, inline = "#2", display = display.none)
color       openColorInput2             = input.color (COLOR_DEFAULT,  title = "",                 group = group1, inline = "#2")
int         openLookbackInput2          = input.int   (1,              title = "",                 group = group1, inline = "#2", minval = 1, maxval = 500, display = display.none)
bool        enableOpenInput3            = input.bool  (false,          title = "",                 group = group1, inline = "#3")
Timeframes  openTimeframeInput3         = input.enum  (Timeframes.M1,  title = "",                 group = group1, inline = "#3", display = display.none)
color       openColorInput3             = input.color (COLOR_DEFAULT,  title = "",                 group = group1, inline = "#3")
int         openLookbackInput3          = input.int   (1,              title = "",                 group = group1, inline = "#3", minval = 1, maxval = 500, display = display.none)
bool        enableOpenInput4            = input.bool  (false,          title = "",                 group = group1, inline = "#4")
Timeframes  openTimeframeInput4         = input.enum  (Timeframes.M3,  title = "",                 group = group1, inline = "#4", display = display.none)
color       openColorInput4             = input.color (COLOR_DEFAULT,  title = "",                 group = group1, inline = "#4")
int         openLookbackInput4          = input.int   (1,              title = "",                 group = group1, inline = "#4", minval = 1, maxval = 500, display = display.none)
bool        enableOpenInput5            = input.bool  (false,          title = "",                 group = group1, inline = "#5")
Timeframes  openTimeframeInput5         = input.enum  (Timeframes.M12, title = "",                 group = group1, inline = "#5", display = display.none)
color       openColorInput5             = input.color (COLOR_DEFAULT,  title = "",                 group = group1, inline = "#5")
int         openLookbackInput5          = input.int   (1,              title = "",                 group = group1, inline = "#5", minval = 1, maxval = 500, display = display.none)
 
bool        enableIntradayInput         = input.bool  (true,  title = "Show Intraday Opens", group = group4, tooltip = intradayMasterTooltip)
 
bool        enableIntradayInput1        = input.bool  (false,          title = "",                 group = group4, inline = "#6")
Timeslots   intradayTimeInput1          = input.enum  (Timeslots.t0000, title = "",                group = group4, inline = "#6", display = display.none)
color       intradayColorInput1         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#6")
int         intradayLookbackInput1      = input.int   (1,              title = "",                 group = group4, inline = "#6", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput2        = input.bool  (false,          title = "",                 group = group4, inline = "#7")
Timeslots   intradayTimeInput2          = input.enum  (Timeslots.t0200, title = "",                group = group4, inline = "#7", display = display.none)
color       intradayColorInput2         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#7")
int         intradayLookbackInput2      = input.int   (1,              title = "",                 group = group4, inline = "#7", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput3        = input.bool  (true,           title = "",                 group = group4, inline = "#8")
Timeslots   intradayTimeInput3          = input.enum  (Timeslots.t0600, title = "",                group = group4, inline = "#8", display = display.none)
color       intradayColorInput3         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#8")
int         intradayLookbackInput3      = input.int   (1,              title = "",                 group = group4, inline = "#8", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput4        = input.bool  (false,          title = "",                 group = group4, inline = "#9")
Timeslots   intradayTimeInput4          = input.enum  (Timeslots.t0830, title = "",                group = group4, inline = "#9", display = display.none)
color       intradayColorInput4         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#9")
int         intradayLookbackInput4      = input.int   (1,              title = "",                 group = group4, inline = "#9", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput5        = input.bool  (false,          title = "",                 group = group4, inline = "#10")
Timeslots   intradayTimeInput5          = input.enum  (Timeslots.t0900, title = "",                group = group4, inline = "#10", display = display.none)
color       intradayColorInput5         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#10")
int         intradayLookbackInput5      = input.int   (1,              title = "",                 group = group4, inline = "#10", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput6        = input.bool  (false,          title = "",                 group = group4, inline = "#11")
Timeslots   intradayTimeInput6          = input.enum  (Timeslots.t0930, title = "",                group = group4, inline = "#11", display = display.none)
color       intradayColorInput6         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#11")
int         intradayLookbackInput6      = input.int   (1,              title = "",                 group = group4, inline = "#11", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput7        = input.bool  (true,           title = "",                 group = group4, inline = "#12")
Timeslots   intradayTimeInput7          = input.enum  (Timeslots.t1000, title = "",                group = group4, inline = "#12", display = display.none)
color       intradayColorInput7         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#12")
int         intradayLookbackInput7      = input.int   (1,              title = "",                 group = group4, inline = "#12", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput8        = input.bool  (false,          title = "",                 group = group4, inline = "#13")
Timeslots   intradayTimeInput8          = input.enum  (Timeslots.t1030, title = "",                group = group4, inline = "#13", display = display.none)
color       intradayColorInput8         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#13")
int         intradayLookbackInput8      = input.int   (1,              title = "",                 group = group4, inline = "#13", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput9        = input.bool  (false,          title = "",                 group = group4, inline = "#14")
Timeslots   intradayTimeInput9          = input.enum  (Timeslots.t1100, title = "",                group = group4, inline = "#14", display = display.none)
color       intradayColorInput9         = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#14")
int         intradayLookbackInput9      = input.int   (1,              title = "",                 group = group4, inline = "#14", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput10       = input.bool  (false,          title = "",                 group = group4, inline = "#15")
Timeslots   intradayTimeInput10         = input.enum  (Timeslots.t1200, title = "",                group = group4, inline = "#15", display = display.none)
color       intradayColorInput10        = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#15")
int         intradayLookbackInput10     = input.int   (1,              title = "",                 group = group4, inline = "#15", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput11       = input.bool  (false,          title = "",                 group = group4, inline = "#16")
Timeslots   intradayTimeInput11         = input.enum  (Timeslots.t1400, title = "",                group = group4, inline = "#16", display = display.none)
color       intradayColorInput11        = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#16")
int         intradayLookbackInput11     = input.int   (1,              title = "",                 group = group4, inline = "#16", minval = 1, maxval = 500, display = display.none)
bool        enableIntradayInput12       = input.bool  (false,          title = "",                 group = group4, inline = "#17")
Timeslots   intradayTimeInput12         = input.enum  (Timeslots.t2200, title = "",                group = group4, inline = "#17", display = display.none)
color       intradayColorInput12        = input.color (COLOR_DEFAULT,  title = "",                 group = group4, inline = "#17")
int         intradayLookbackInput12     = input.int   (1,              title = "",                 group = group4, inline = "#17", minval = 1, maxval = 500, display = display.none, tooltip = intradayTimeTooltip)
string      intradayTimezoneInput       = input.string("New York",     title = "Timezone",         group = group4, tooltip = intradayTimezoneTooltip, display = display.none, options = [
     "Exchange", "UTC", "New York", "Chicago", "Denver", "Los Angeles", "London", "Frankfurt", "Moscow",
     "Dubai", "Kolkata", "Hong Kong", "Tokyo", "Sydney"])
 
int         rightOffsetInput            = input.int   (5,              title = "Offset",           group = group2, inline = "Offset", tooltip = rightOffsetTooltip, minval = 1, display = display.none)
float       labelSpacingInput           = input.float (0.25,           title = "Label Spacing",    group = group2, tooltip = labelSpacingTooltip, minval = 0, step = 0.05, display = display.none)
bool        enableTailsInput            = input.bool  (false,          title = "Show Tails",       group = group2, tooltip = tailsTooltip)
bool        enableHeadsInput            = input.bool  (false,          title = "Show Projections", group = group2, tooltip = headsTooltip)
bool        discoverPricesInput         = input.bool  (true,           title = "Discover Prices",  group = group3, tooltip = discoverPricesTooltip)
bool        enableExtendedSessionInput  = input.bool  (false,          title = "Extended Hours",   group = group3, tooltip = extendedHoursTooltip)
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                   Functions & methods
//--------------------------------------------------------------------
 
// @function Check if the open for the specified `timeframe` can be displayed on the chart context.
// @returns  simple bool
method isVisible(simple string timeframe) =>
    timeframe.in_seconds(timeframe) > timeframe.in_seconds()
 
 
// @function Detect changes of opens.
// @returns  series bool
method change(
     simple string timeframe,
     series int    timeframeTime,
     simple bool   discoverPrice,
     simple bool   discoverExtendedPrice
     ) =>
 
    switch
        discoverExtendedPrice => timeframe.change(timeframe)
        discoverPrice         => ta.change(timeframeTime) > 0 or (barstate.isfirst and time == timeframeTime)
        =>                       ta.change(timeframeTime) > 0 or barstate.isfirst
 
 
// @function Request the data in the specified `timeframe` context.
// @returns  ([int, float]) The open's time and price.
method request(string timeframe, bool extendedSession) =>
    string tickerId = ticker.new(syminfo.prefix, syminfo.ticker, extendedSession ? session.extended : session.regular)
    request.security(tickerId, timeframe, [time, open], lookahead = barmerge.lookahead_on)
 
 
// @function Check if the specified `timeframe` returns end-of-day data.
// @returns  bool
method higherTimeframeFeed(simple string timeframe) =>
    timeframe.in_seconds(timeframe) >= timeframe.in_seconds("D")
 
 
// @function Check if the open can be sourced from the chart data.
//
//           MODIFIED: the previous `and timeframe.isintraday` condition restricted discovery to
//           intraday charts, which meant a weekly/monthly/yearly open fell back to requested data on
//           a daily or weekly chart and therefore broke across a futures contract rollover.
//           `isVisible()` already guarantees the chart timeframe is lower than the open's timeframe,
//           so the chart always holds a bar that opened the period.
// @returns  bool
discoverPrice(simple string timeframe, simple bool discovery) =>
    discovery and higherTimeframeFeed(timeframe)
 
 
// @function Check if the extended session open can be sourced from the chart.
// @returns  bool
discoverExtendedPrice(simple string timeframe, simple bool extendedSession) =>
    extendedSession and higherTimeframeFeed(timeframe) and syminfo.session == session.extended
 
 
// @function Check if the open time belongs to the previous bar.
// @returns  bool
adjustStartBarIndex(int t) =>
    time_close[1] > t
 
 
// @function Calculate the right position of the open level.
// @returns  (int) The bar index.
getRightBarIndex(int padding = 0) =>
    bar_index + rightOffsetInput + padding * OFFSET_PADDING
 
 
// @function Produce the `timeframe` parameter from the given user input.
// @returns  string
method param(simple Timeframes input) =>
    switch input
        Timeframes.s5  => "5S"
        Timeframes.s10 => "10S"
        Timeframes.s15 => "15S"
        Timeframes.s30 => "30S"
        Timeframes.m1  => "1"
        Timeframes.m2  => "2"
        Timeframes.m3  => "3"
        Timeframes.m5  => "5"
        Timeframes.m10 => "10"
        Timeframes.m15 => "15"
        Timeframes.m30 => "30"
        Timeframes.m45 => "45"
        Timeframes.h1  => "60"
        Timeframes.h2  => "120"
        Timeframes.h3  => "180"
        Timeframes.h4  => "240"
        Timeframes.h6  => "360"
        Timeframes.h8  => "480"
        Timeframes.h12 => "720"
        Timeframes.D1  => "1D"
        Timeframes.W1  => "1W"
        Timeframes.M1  => "1M"
        Timeframes.M3  => "3M"
        Timeframes.M6  => "6M"
        Timeframes.M12 => "12M"
 
 
// @function Produce the IANA timezone identifier from the given user input.
// @returns  simple string
method tzParam(simple string this) =>
    switch this
        "UTC"         => "UTC"
        "New York"    => "America/New_York"
        "Chicago"     => "America/Chicago"
        "Denver"      => "America/Denver"
        "Los Angeles" => "America/Los_Angeles"
        "London"      => "Europe/London"
        "Frankfurt"   => "Europe/Berlin"
        "Moscow"      => "Europe/Moscow"
        "Dubai"       => "Asia/Dubai"
        "Kolkata"     => "Asia/Kolkata"
        "Hong Kong"   => "Asia/Hong_Kong"
        "Tokyo"       => "Asia/Tokyo"
        "Sydney"      => "Australia/Sydney"
        =>               syminfo.timezone
 
 
// @function Produce the "HH:MM" text of the given timeslot selection, which is the enum field title.
// @returns  simple string
method timeText(simple Timeslots this) =>
    str.tostring(this)
 
 
// @function Convert a timeslot selection into the number of minutes elapsed since midnight.
// @returns  simple int
method minutesOfDay(simple Timeslots this) =>
    string _str    = this.timeText()
    int    _hour   = int(str.tonumber(str.substring(_str, 0, 2)))
    int    _minute = int(str.tonumber(str.substring(_str, 3, 5)))
    _hour * 60 + _minute
 
 
// @function Detect a bar that opens exactly on the intraday open's time.
//
//           The match is exact rather than "the first bar at or after the time", so the level only
//           anchors to a true candle open on the chart's own bar grid. A time that no bar opens on
//           never anchors and the level stays hidden: 10:00 resolves on the 1H and 4H charts, 09:30
//           needs a 30 minute chart or lower on a 24 hour session, and a 90 minute chart resolves
//           only the times its own grid lands on.
//
//           `barSecond` keeps sub-minute charts honest: on a 10 second chart every bar inside the
//           10:00 minute reports minute 0, and only the one starting at :00 seconds is the open.
// @returns  series bool
intradayChange(int barMinutes, int barSecond, simple int targetMinutes) =>
    barMinutes == targetMinutes and barSecond == 0
 
 
// @function Return the short display string for the specified `timeframe` string.
// @returns  string
method displayString(string this) =>
    // Get the readable format.
    string _str = switch this
        "1"     => "m"
        "2"     => "2m"
        "3"     => "3m"
        "5"     => "5m"
        "10"    => "10m"
        "15"    => "15m"
        "30"    => "30m"
        "45"    => "45m"
        "60"    => "H"
        "120"   => "2H"
        "180"   => "3H"
        "240"   => "4H"
        "360"   => "6H"
        "480"   => "8H"
        "720"   => "12H"
        "1440"  => "24H"
        "1D"    => "D"
        "1W"    => "W"
        "1M"    => "M"
        "12M"   => "Y"
        => this
 
    // Add spacing. A `style_none` label centres its text on the anchor, so trailing spaces shift the
    // visible text left of the line end. Treating every glyph as one width w, the visible right edge
    // lands at x + w * (n - L / 2) for n visible characters out of L total, which puts "D" plus 3
    // spaces one width short of the line and the "HH:MM" intraday names on the same offset.
    //
    // NOTE: the alignment this produces is close but not exact. The label font is proportional, so a
    // space is narrower than a digit and the single w above does not hold across name lengths. A
    // `label.style_label_right` over a transparent background would anchor the text exactly, at the
    // cost of changing where every label sits.
    switch str.length(_str)
        1 => _str + "   "
        2 => _str + "     "
        3 => _str + "       "
        => _str + "       "
 
 
// @function Build the drawing objects belonging to one level. Called once per level on the first bar.
// @returns  Level
newLevel(string name, color color) =>
    Level.new(
         body = na,
         tag  = label.new(
             x         = na,
             y         = na,
             text      = name,
             style     = LABEL_STYLE,
             textcolor = color,
             size      = LABEL_SIZE
             ),
         tail = line.new(
             x1     = na,
             y1     = na,
             x2     = na,
             y2     = na,
             color  = color,
             style  = TAIL_STYLE,
             width  = LINE_WIDTH,
             extend = extend.left
             ),
         bodies = array.new_line(),
         heads  = array.new_line()
         )
 
 
// @function Create and update the open level. An open is composed of a label, a "body" line, and optional "tail" and "head" line extensions.
//
//           MODIFIED: this was `draw()`, which held its drawings in `var` locals. A `var` inside a
//           function belongs to its call site, so every level needed its own unrolled call. The
//           state now lives in a `Level` passed by the caller, which lets one routine serve all of
//           the levels from a single loop.
// @returns  void
method drawLevel(Level this, bool change, Open openData, int lookback, color color, int padding) =>
 
    // Update the old open and create the new open.
 
    if change
        int _x2 = getRightBarIndex()
 
        // Anchor the previous open end position.
        this.body.set_x2(openData.barIndex -1)
 
        // Create the previous open "head".
        if enableHeadsInput
            this.heads.push(
                 line.new(
                     x1    = openData.barIndex -1,
                     x2    = openData.barIndex,
                     y1    = this.body.get_y1(),
                     y2    = this.body.get_y2(),
                     color = color.new(color, HEAD_TRANSP),
                     style = LINE_STYLE,
                     width = LINE_WIDTH
                     )
                 )
 
            // Trim the exceeding number of drawings.
            if this.heads.size() > lookback -1
                line.delete(this.heads.shift())
 
        // Update the last open label position and tooltip.
        this.tag.set_xy(_x2, openData.price)
        this.tag.set_tooltip(str.tostring(openData.price, format.mintick))
 
        // Create and store the last open line.
        this.body := line.new(
             x1    = openData.barIndex,
             x2    = _x2,
             y1    = openData.price,
             y2    = openData.price,
             color = color,
             style = LINE_STYLE,
             width = LINE_WIDTH
             )
        array.push(this.bodies, this.body)
 
        // Trim the exceeding number of drawings.
        if this.bodies.size() > lookback
            line.delete(this.bodies.shift())
 
        // Create the last open "tail".
        if enableTailsInput
            this.tail.set_xy1(openData.barIndex -1, openData.price)
            this.tail.set_xy2(openData.barIndex,    openData.price)
 
 
    // Update the right position of the "body" and "heads" lines.
 
    if barstate.islast
        if enableHeadsInput
            int _x2 = getRightBarIndex(HEAD_PADDING)
            for _head in this.heads
                _head.set_x2(_x2)
 
        int _x2 = getRightBarIndex(padding)
        this.body.set_x2(_x2)
        this.tag.set_x(_x2)
 
 
// @function Get the padding to apply to the open right position for not overlapping the other open labels.
//
//           MODIFIED: the per-index conditions were unrolled for the five fixed opens. The loop
//           form generalizes to any number of levels so the intraday opens are spaced out as well.
// @returns  int
method padding(array<Open> this, int idx, float proximityThreshold) =>
    int _padding = 0
 
    // Every open can share its level with any of the opens declared before it.
    if idx > 0
        float _price = this.get(idx).price
        for i = 0 to idx -1
            Open _other = this.get(i)
            if _other.display and math.abs(_other.price - _price) <= proximityThreshold
                _padding += 1
 
    _padding
 
 
// @function Update the open levels.
// @returns  (bool) Is true if the open changes.
update(
     Open           data,
     simple string  tf,
     simple bool    extendedSession,
     simple bool    discoverPrice,
     simple bool    discoverExtendedPrice
     ) =>
 
    // @variable The `open` and `time` requested from the timeframe context.
    [_tfTime, _tfOpen] = tf.request(extendedSession)
 
    // @variable Is true when the timeframe changes.
    bool _change = tf.change(_tfTime, discoverPrice, discoverExtendedPrice)
 
    // @variable Is true when pinpointing the opening bar index on the previous bar.
    bool _adjust = adjustStartBarIndex(_tfTime)
 
    // @variable Is true when sourcing the opening price from the chart context.
    bool _discovery = discoverPrice or discoverExtendedPrice
 
    if _change
        data.price    := _discovery ? open : _tfOpen
        data.barIndex := _discovery ? bar_index : (_adjust ? bar_index -1 : bar_index)
 
    _change
 
 
// @function Update an intraday open. The price always comes from the chart's own bars, so no
//           higher-timeframe request and no start bar adjustment are needed.
// @returns  (bool) Is true if the open changes.
updateIntraday(Open data, int barMinutes, int barSecond, simple int targetMinutes) =>
    // @variable Is true on the bar that opens exactly on the intraday open's time.
    bool _change = intradayChange(barMinutes, barSecond, targetMinutes)
 
    if _change
        data.price    := open
        data.barIndex := bar_index
 
    _change
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                 Variables declarations
//--------------------------------------------------------------------
 
// @variable The `timeframe` parameters produced from the enum input selections.
var string timeframe1 = openTimeframeInput1.param()
var string timeframe2 = openTimeframeInput2.param()
var string timeframe3 = openTimeframeInput3.param()
var string timeframe4 = openTimeframeInput4.param()
var string timeframe5 = openTimeframeInput5.param()
 
 
// @variable Are true when we can display the opens on the chart.
var simple bool display1 = enableOpenInput1 and timeframe1.isVisible()
var simple bool display2 = enableOpenInput2 and timeframe2.isVisible()
var simple bool display3 = enableOpenInput3 and timeframe3.isVisible()
var simple bool display4 = enableOpenInput4 and timeframe4.isVisible()
var simple bool display5 = enableOpenInput5 and timeframe5.isVisible()
 
 
// @variable Are true when sourcing the open prices from the chart instead of the requested timeframe context.
var simple bool discoverPrice1 = discoverPrice(timeframe1, discoverPricesInput)
var simple bool discoverPrice2 = discoverPrice(timeframe2, discoverPricesInput)
var simple bool discoverPrice3 = discoverPrice(timeframe3, discoverPricesInput)
var simple bool discoverPrice4 = discoverPrice(timeframe4, discoverPricesInput)
var simple bool discoverPrice5 = discoverPrice(timeframe5, discoverPricesInput)
 
 
// @variable Is true when we should plot the opens on the extended trading hours.
var simple bool extendedSession = enableExtendedSessionInput and syminfo.session == session.extended
 
 
// @variable Are true when we should source the open prices from the chart instead of the requested timeframe context.
var simple bool discoverExtendedPrice1 = discoverExtendedPrice(timeframe1, extendedSession)
var simple bool discoverExtendedPrice2 = discoverExtendedPrice(timeframe2, extendedSession)
var simple bool discoverExtendedPrice3 = discoverExtendedPrice(timeframe3, extendedSession)
var simple bool discoverExtendedPrice4 = discoverExtendedPrice(timeframe4, extendedSession)
var simple bool discoverExtendedPrice5 = discoverExtendedPrice(timeframe5, extendedSession)
 
 
// @variable The timezone the intraday open times are expressed in.
var simple string intradayTimezone = intradayTimezoneInput.tzParam()
 
 
// @variable The intraday open times as minutes elapsed since midnight.
var simple int intradayMinutes1  = intradayTimeInput1.minutesOfDay()
var simple int intradayMinutes2  = intradayTimeInput2.minutesOfDay()
var simple int intradayMinutes3  = intradayTimeInput3.minutesOfDay()
var simple int intradayMinutes4  = intradayTimeInput4.minutesOfDay()
var simple int intradayMinutes5  = intradayTimeInput5.minutesOfDay()
var simple int intradayMinutes6  = intradayTimeInput6.minutesOfDay()
var simple int intradayMinutes7  = intradayTimeInput7.minutesOfDay()
var simple int intradayMinutes8  = intradayTimeInput8.minutesOfDay()
var simple int intradayMinutes9  = intradayTimeInput9.minutesOfDay()
var simple int intradayMinutes10 = intradayTimeInput10.minutesOfDay()
var simple int intradayMinutes11 = intradayTimeInput11.minutesOfDay()
var simple int intradayMinutes12 = intradayTimeInput12.minutesOfDay()
 
 
// @variable Is true when the chart context can hold an intraday open at all.
//
//           MODIFIED: this was `timeframe.in_seconds() <= timeframe.in_seconds("30")`, a blanket
//           cutoff that hid a 10:00 level on the 1H and 4H charts even though those bars do open on
//           it. Alignment is now decided per bar by `intradayChange()` against the chart's own grid,
//           so the only thing left to gate here is the chart being intraday: on a daily-or-higher
//           chart every bar's time of day is the session open, which would match a target for the
//           wrong reason and duplicate the D/W/M opens.
//
//           `enableIntradayInput` is the section's master switch: it gates every intraday open at
//           once while leaving the individual selections below it untouched.
var simple bool intradayVisible = enableIntradayInput and timeframe.isintraday
 
 
// @variable Are true when we can display the intraday opens on the chart.
var simple bool display6  = enableIntradayInput1  and intradayVisible
var simple bool display7  = enableIntradayInput2  and intradayVisible
var simple bool display8  = enableIntradayInput3  and intradayVisible
var simple bool display9  = enableIntradayInput4  and intradayVisible
var simple bool display10 = enableIntradayInput5  and intradayVisible
var simple bool display11 = enableIntradayInput6  and intradayVisible
var simple bool display12 = enableIntradayInput7  and intradayVisible
var simple bool display13 = enableIntradayInput8  and intradayVisible
var simple bool display14 = enableIntradayInput9  and intradayVisible
var simple bool display15 = enableIntradayInput10 and intradayVisible
var simple bool display16 = enableIntradayInput11 and intradayVisible
var simple bool display17 = enableIntradayInput12 and intradayVisible
 
 
// @variable The `Open` UDTs.
var Open open1  = Open.new(name = timeframe1.displayString(),                    display = display1)
var Open open2  = Open.new(name = timeframe2.displayString(),                    display = display2)
var Open open3  = Open.new(name = timeframe3.displayString(),                    display = display3)
var Open open4  = Open.new(name = timeframe4.displayString(),                    display = display4)
var Open open5  = Open.new(name = timeframe5.displayString(),                    display = display5)
var Open open6  = Open.new(name = intradayTimeInput1.timeText().displayString(),  display = display6)
var Open open7  = Open.new(name = intradayTimeInput2.timeText().displayString(),  display = display7)
var Open open8  = Open.new(name = intradayTimeInput3.timeText().displayString(),  display = display8)
var Open open9  = Open.new(name = intradayTimeInput4.timeText().displayString(),  display = display9)
var Open open10 = Open.new(name = intradayTimeInput5.timeText().displayString(),  display = display10)
var Open open11 = Open.new(name = intradayTimeInput6.timeText().displayString(),  display = display11)
var Open open12 = Open.new(name = intradayTimeInput7.timeText().displayString(),  display = display12)
var Open open13 = Open.new(name = intradayTimeInput8.timeText().displayString(),  display = display13)
var Open open14 = Open.new(name = intradayTimeInput9.timeText().displayString(),  display = display14)
var Open open15 = Open.new(name = intradayTimeInput10.timeText().displayString(), display = display15)
var Open open16 = Open.new(name = intradayTimeInput11.timeText().displayString(), display = display16)
var Open open17 = Open.new(name = intradayTimeInput12.timeText().displayString(), display = display17)
 
 
// @variable The collection of last `Open`.
var array<Open> openArray = array.from(
     open1,  open2,  open3,  open4,  open5,  open6,  open7,  open8,  open9,
     open10, open11, open12, open13, open14, open15, open16, open17)
 
 
// @variable The per level colors, index aligned with `openArray`.
var array<color> colorArray = array.from(
     openColorInput1,     openColorInput2,     openColorInput3,     openColorInput4,
     openColorInput5,     intradayColorInput1, intradayColorInput2, intradayColorInput3,
     intradayColorInput4, intradayColorInput5, intradayColorInput6, intradayColorInput7,
     intradayColorInput8, intradayColorInput9, intradayColorInput10, intradayColorInput11,
     intradayColorInput12)
 
 
// @variable The per level lookbacks, index aligned with `openArray`.
var array<int> lookbackArray = array.from(
     openLookbackInput1,     openLookbackInput2,     openLookbackInput3,     openLookbackInput4,
     openLookbackInput5,     intradayLookbackInput1, intradayLookbackInput2, intradayLookbackInput3,
     intradayLookbackInput4, intradayLookbackInput5, intradayLookbackInput6, intradayLookbackInput7,
     intradayLookbackInput8, intradayLookbackInput9, intradayLookbackInput10, intradayLookbackInput11,
     intradayLookbackInput12)
 
 
// @variable The drawing objects of each level, index aligned with `openArray`.
var array<Level> levelArray = array.new<Level>()
if barstate.isfirst
    for i = 0 to openArray.size() -1
        levelArray.push(newLevel(openArray.get(i).name, colorArray.get(i)))
 
 
// @variable The current bar's opening time of day, in minutes elapsed since midnight, and its second.
int intradayBarMinutes = hour(time, intradayTimezone) * 60 + minute(time, intradayTimezone)
int intradayBarSecond  = second(time, intradayTimezone)
 
 
// @variable The maximum distance to determine if two levels overlap each other.
//
//           MODIFIED: this was a fixed `ta.atr(10) /2`. Half an ATR is far wider than a label is
//           tall on a higher timeframe chart, so opens that were plainly separated still got
//           fanned out. The multiplier is an input now because the right value depends on the
//           chart. A negative threshold at 0 disables the fan out completely: `math.abs()` is
//           never negative, so no pair can ever match, not even two opens on an identical price.
float proximityPaddingThreshold = labelSpacingInput <= 0 ? -1.0 : ta.atr(10) * labelSpacingInput
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                         Logic
//--------------------------------------------------------------------
 
bool change1 = if display1
    update(open1, timeframe1, extendedSession, discoverPrice1, discoverExtendedPrice1)
 
 
bool change2 = if display2
    update(open2, timeframe2, extendedSession, discoverPrice2, discoverExtendedPrice2)
 
 
bool change3 = if display3
    update(open3, timeframe3, extendedSession, discoverPrice3, discoverExtendedPrice3)
 
 
bool change4 = if display4
    update(open4, timeframe4, extendedSession, discoverPrice4, discoverExtendedPrice4)
 
 
bool change5 = if display5
    update(open5, timeframe5, extendedSession, discoverPrice5, discoverExtendedPrice5)
 
 
bool change6 = if display6
    updateIntraday(open6, intradayBarMinutes, intradayBarSecond, intradayMinutes1)
 
 
bool change7 = if display7
    updateIntraday(open7, intradayBarMinutes, intradayBarSecond, intradayMinutes2)
 
 
bool change8 = if display8
    updateIntraday(open8, intradayBarMinutes, intradayBarSecond, intradayMinutes3)
 
 
bool change9 = if display9
    updateIntraday(open9, intradayBarMinutes, intradayBarSecond, intradayMinutes4)
 
 
bool change10 = if display10
    updateIntraday(open10, intradayBarMinutes, intradayBarSecond, intradayMinutes5)
 
 
bool change11 = if display11
    updateIntraday(open11, intradayBarMinutes, intradayBarSecond, intradayMinutes6)
 
 
bool change12 = if display12
    updateIntraday(open12, intradayBarMinutes, intradayBarSecond, intradayMinutes7)
 
 
bool change13 = if display13
    updateIntraday(open13, intradayBarMinutes, intradayBarSecond, intradayMinutes8)
 
 
bool change14 = if display14
    updateIntraday(open14, intradayBarMinutes, intradayBarSecond, intradayMinutes9)
 
 
bool change15 = if display15
    updateIntraday(open15, intradayBarMinutes, intradayBarSecond, intradayMinutes10)
 
 
bool change16 = if display16
    updateIntraday(open16, intradayBarMinutes, intradayBarSecond, intradayMinutes11)
 
 
bool change17 = if display17
    updateIntraday(open17, intradayBarMinutes, intradayBarSecond, intradayMinutes12)
 
 
// @variable The change flags of each level, index aligned with `openArray`.
array<bool> changeArray = array.from(
     change1,  change2,  change3,  change4,  change5,  change6,  change7,  change8,  change9,
     change10, change11, change12, change13, change14, change15, change16, change17)
 
//#endregion
 
 
//--------------------------------------------------------------------
//#region                        Visuals
//--------------------------------------------------------------------
 
//#region - Draw the open levels.
 
// The loop counts down so that the lowest numbered level is drawn last and therefore sits on top,
// which is the order the unrolled calls used to produce.
for i = openArray.size() -1 to 0
    Open _open = openArray.get(i)
 
    if _open.display
        levelArray.get(i).drawLevel(
             changeArray.get(i),
             _open,
             lookbackArray.get(i),
             colorArray.get(i),
             barstate.islast ? openArray.padding(i, proximityPaddingThreshold) : 0
             )
 
//#endregion
 
 
//#region - Plot the open prices on the `status line`, `price scale`, `data window` as well for providing alert conditions.
 
displayControls = display.status_line + display.price_scale + display.data_window
 
plot(
     series   = open1.price,
     title    = "#1",
     color    = openColorInput1,
     editable = false,
     display  = enableOpenInput1 ? displayControls : display.none
     )
 
plot(
     series   = open2.price,
     title    = "#2",
     color    = openColorInput2,
     editable = false,
     display  = enableOpenInput2 ? displayControls : display.none
     )
 
plot(
     series = open3.price,
     title    = "#3",
     color    = openColorInput3,
     editable = false,
     display  = enableOpenInput3 ? displayControls : display.none
     )
 
plot(
     series   = open4.price,
     title    = "#4",
     color    = openColorInput4,
     editable = false,
     display  = enableOpenInput4 ? displayControls : display.none
     )
 
plot(
     series   = open5.price,
     title    = "#5",
     color    = openColorInput5,
     editable = false,
     display  = enableOpenInput5 ? displayControls : display.none
     )
 
plot(
     series   = open6.price,
     title    = "#6",
     color    = intradayColorInput1,
     editable = false,
     display  = enableIntradayInput1 ? displayControls : display.none
     )
 
plot(
     series   = open7.price,
     title    = "#7",
     color    = intradayColorInput2,
     editable = false,
     display  = enableIntradayInput2 ? displayControls : display.none
     )
 
plot(
     series   = open8.price,
     title    = "#8",
     color    = intradayColorInput3,
     editable = false,
     display  = enableIntradayInput3 ? displayControls : display.none
     )
 
plot(
     series   = open9.price,
     title    = "#9",
     color    = intradayColorInput4,
     editable = false,
     display  = enableIntradayInput4 ? displayControls : display.none
     )
 
plot(
     series   = open10.price,
     title    = "#10",
     color    = intradayColorInput5,
     editable = false,
     display  = enableIntradayInput5 ? displayControls : display.none
     )
 
plot(
     series   = open11.price,
     title    = "#11",
     color    = intradayColorInput6,
     editable = false,
     display  = enableIntradayInput6 ? displayControls : display.none
     )
 
plot(
     series   = open12.price,
     title    = "#12",
     color    = intradayColorInput7,
     editable = false,
     display  = enableIntradayInput7 ? displayControls : display.none
     )
 
plot(
     series   = open13.price,
     title    = "#13",
     color    = intradayColorInput8,
     editable = false,
     display  = enableIntradayInput8 ? displayControls : display.none
     )
 
plot(
     series   = open14.price,
     title    = "#14",
     color    = intradayColorInput9,
     editable = false,
     display  = enableIntradayInput9 ? displayControls : display.none
     )
 
plot(
     series   = open15.price,
     title    = "#15",
     color    = intradayColorInput10,
     editable = false,
     display  = enableIntradayInput10 ? displayControls : display.none
     )
 
plot(
     series   = open16.price,
     title    = "#16",
     color    = intradayColorInput11,
     editable = false,
     display  = enableIntradayInput11 ? displayControls : display.none
     )
 
plot(
     series   = open17.price,
     title    = "#17",
     color    = intradayColorInput12,
     editable = false,
     display  = enableIntradayInput12 ? displayControls : display.none
     )
 
//#endregion
 
//#endregion-

← 返回列表