ICT Opening Range Projections (tristanlee85)

tristanlee85 · study · 660 行 · 点赞 482 · TradingView 原页

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

Pine Script

// @version=6
// @author Tristan Lee (tristanlee85)
// @license MPL-2.0
// @description Opening Range Projections — Visualizes ICT's 30-minute session range, projections, and quadrant levels.
indicator("ICT Opening Range Projections (tristanlee85)", shorttitle="ICT ORP", overlay=true,
  max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
import tristanlee85/HelperLib/2 as lib
 
const bool   DEBUG                = true
const string DATE_FORMAT          = "MM-dd (E)"
const string TIME_FORMAT          = "HH:mm"
const string NUMBER_FORMAT        = "#.0000"
const string TZ                   = "America/New_York"
const string MIDNIGHT_NAME        = "Midnight"
const string LONDON_NAME          = "London"
const string NY_AM_NAME           = "NY AM"
const string NY_PM_NAME           = "NY PM"
const string ASIA_NAME            = "Asia"
const string USER_SESS1_NAME      = "User Session 1"
const string USER_SESS2_NAME      = "User Session 2"
const string USER_SESS3_NAME      = "User Session 3"
const string VALID_PERIOD_SECONDS = "1,5,15,30,60,300,600,900"
const int    BRACKET_WIDTH        = 2
const int    BRACKET_GAP          = 1
const string MIN_RANGE_TIP        = "Show the range high/low.\n\nThe minimum size, in ticks, required of a range in order to plot its levels.\n" + 
                                      "  0 to disable (default) - all range levels plotted regardless of size\n" + 
                                      "≥ 1 - range levels plotted ONLY if the size exceeds the minimum\n\n" +
                                      "If a range size is below the minimum, the below levels will still be plotted if enabed.\n" + 
                                      "NOTE: you must also have an option enabled in its section below or it will not plot below the minimum."
 
// @enum Projection label options
enum ProjectionLabelType
    stdev = "STDEV (e.g., 2.0 )"
    price = "Price (e.g., 12,345.00 )"
    both  = "Both  (e.g., 2.0 (12,345.00) )"
 
// @enum Range label options
enum RangeLabel
    HIGH    = "High"
    LOW     = "Low"
    QUAD_25 = "25%"
    QUAD_50 = "50%"
    QUAD_75 = "75%"
 
 
// Inputs for Opening Range Sessions
bool                  midnightToggle             = input.bool(true                              , title="Midnight (00:00 - 00:30)"           , group="Opening Range Sessions")
// bool               londonToggle               = input.bool(false                             , title="London (01:30 - 02:00)"             , group="Opening Range Sessions")
bool                  nyAmToggle                 = input.bool(true                              , title="NY (09:30 - 10:00 )"                , group="Opening Range Sessions")
bool                  nyPmToggle                 = input.bool(true                              , title="NY (13:30 - 14:00)"                 , group="Opening Range Sessions")
// bool               asiaToggle                 = input.bool(false                             , title="Asia (20:00 - 20:30)"               , group="Opening Range Sessions")
bool                  userSession1Toggle         = input.bool(false                             , title="User Session 1"                     , group="Opening Range Sessions")
string                userSession1               = input.session(""                             , title=""                                   , group="Opening Range Sessions")
bool                  userSession2Toggle         = input.bool(false                             , title="User Session 2"                     , group="Opening Range Sessions")
string                userSession2               = input.session(""                             , title=""                                   , group="Opening Range Sessions") 
bool                  userSession3Toggle         = input.bool(false                             , title="User Session 3"                     , group="Opening Range Sessions")
string                userSession3               = input.session(""                             , title=""                                   , group="Opening Range Sessions")
int                   numPrevSessions            = input.int(5                                  , title="Number Of Previous Sessions To Plot", group="Opening Range Sessions"                           , tooltip="Plotting too many sessions may result in lines not displaying due to charting limitations.")
// Inputs for Sessions
bool                  sessionsToggle             = input.bool(true                              , title="Enable"                             , group="Sessions"                                         , tooltip="Show session lines.")
color                 sessionsColor              = input.color(color.new(color.black, 50)     , title=""                                   , group="Sessions"              , inline="sessions"        )
lib.LineStyleType     sessionsStyle              = input.enum(lib.LineStyleType.SOLID           , title=""                                   , group="Sessions"              , inline="sessions"        )
int                   sessionsWidth              = input.int(1                                  , title="Width"                              , group="Sessions"              , inline="sessions"        , minval=1, maxval=5)
bool                  sessionsLabelToggle        = input.bool(true                              , title="Show Labels"                        , group="Sessions"              )
// Inputs for Opening Price
bool                  openingPriceToggle         = input.bool(true                              , title="Enable"                             , group="Opening Price"                                    , tooltip="Show opening price of the range.")
color                 openingPriceColor          = input.color(color.blue                     , title=""                                   , group="Opening Price"         , inline="opening_price"   )
lib.LineStyleType     openingPriceStyle          = input.enum(lib.LineStyleType.SOLID           , title=""                                   , group="Opening Price"         , inline="opening_price"   )
int                   openingPriceWidth          = input.int(1                                  , title="Width"                              , group="Opening Price"         , inline="opening_price"   , minval=1, maxval=5)
bool                  openingPriceLabelToggle    = input.bool(true                              , title="Show Labels"                        , group="Opening Price"         )
// Inputs for Range Levels
bool                  rangeLevelsToggle          = input.bool(true                              , title="Enable"                             , group="Range"                 , inline="range"           , tooltip=MIN_RANGE_TIP)
int                   minRangeTicks              = input.int(0                                  , title="Minimum Ticks For Range"            , group="Range"                 , inline="minTick"         )
color                 minRangeColor              = input.color(color.red                      , title=""                                   , group="Range"                 , inline="minTick"         , tooltip="Color of range bracket when below minimum")
bool                  minRangeOP                 = input.bool(true                              , title="Opening Price"                      , group="Range"                 , inline="min_range_opts")
bool                  minRangeRL                 = input.bool(true                              , title="Range H/L"                          , group="Range"                 , inline="min_range_opts")
bool                  minRangeQL                 = input.bool(true                              , title="Quadrants"                          , group="Range"                 , inline="min_range_opts")
bool                  minRangePR                 = input.bool(false                             , title="Projections"                        , group="Range"                 , inline="min_range_opts")
 
bool                  rangeLevelsFromSwingToggle = input.bool(false                             , title="Use Swing Points"                   , group="Range Levels"          , inline="range"           , tooltip="Enable to determine range from swing high/low; Disable to use absolute high/low")
color                 rangeLevelsColor           = input.color(color.new(color.purple, 0)     , title=""                                   , group="Range Levels"          , inline="range_style"     )
lib.LineStyleType     rangeLevelsStyle           = input.enum(lib.LineStyleType.SOLID           , title=""                                   , group="Range Levels"          , inline="range_style"     )
int                   rangeLevelsWidth           = input.int(1                                  , title=""                                   , group="Range Levels"          , inline="range_style"     , minval=1)
bool                  quadLevelsToggle           = input.bool(true                              , title="Show Quadrants"                     , group="Range Levels"                                     , tooltip="Show quadrant levels (25%, 50%, 75%) within the range.")
color                 quadLevelsColor            = input.color(color.new(color.purple, 50 )   , title=""                                   , group="Range Levels"          , inline="quad_style"      )
lib.LineStyleType     quadLevelsStyle            = input.enum(lib.LineStyleType.DASH            , title=""                                   , group="Range Levels"          , inline="quad_style"      )
int                   quadLevelsWidth            = input.int(1                                  , title=""                                   , group="Range Levels"          , inline="quad_style"      , minval=1)
bool                  quadLevelsEnhanceCE        = input.bool(true                              , title="Enhance C.E."                       , group="Range Levels"          , inline="quad_style"      , tooltip="Enhance C.E. by increasing its width.")
bool                  rangeLabelToggle           = input.bool(true                              , title="Show Labels"                        , group="Range Levels"          )
// Inputs for Projections
bool                  projectionsToggle          = input.bool(true                              , title="Enable"                             , group="Projections"                                      , tooltip="Show range projections")
float                 projectionsSTD             = input.float(0                                , title="Standard Deviations"                , group="Projections"          , inline="stdev"            , minval=0, maxval=10.0, step=0.5, tooltip="" + 
                                                                                                                                                                                                          "When Dynamic Levels are ENABLED, this is the max number of STDEV projections to display." +
                                                                                                                                                                                                          "The next projected level is plotted once price crosses an extreme level. " +
                                                                                                                                                                                                          "Set to 0 for no limit (default).\n\n" +
                                                                                                                                                                                                          "When Dynamic Levels are DISABLED, this is the fixed number of STDEV projections to display.")
bool                  projectionsDynamic         = input.bool(true                              , title="Dynamic Levels"                     , group="Projections"          , inline="stdev"            )
color                 projectionsColor           = input.color(color.new(color.purple, 50)    , title=""                                   , group="Projections"          , inline="projections_style")
lib.LineStyleType     projectionsStyle           = input.enum(lib.LineStyleType.DOTS            , title=""                                   , group="Projections"          , inline="projections_style")
int                   projectionsWidth           = input.int(1                                  , title=""                                   , group="Projections"          , inline="projections_style", minval=1)
bool                  projectionLabelToggle      = input.bool(true                              , title="Show Labels"                        , group="Projections"          , inline="projections_label")
ProjectionLabelType   labelsProjectionContent    = input.enum(ProjectionLabelType.stdev         , title=""                                   , group="Projections"          , inline="projections_label", tooltip="Choose what content to display on projection labels.")
// Inputs for Labels/Lines
lib.SessionExtendType lineExtension              = input.enum(lib.SessionExtendType.NEXT_SESSION, title="Extend Lines"                       , group="Lines and Labels"                                 , tooltip="" + 
                                                                                                                                                                                                          "Current Session: Lines terminate at the session end time\n\n" + 
                                                                                                                                                                                                          "Next Sessions: Lines extend up to the start of the next session\n\n" + 
                                                                                                                                                                                                          "Current Bar: Lines extend to the current bar, including all previous sessions")
color                 bracketColor               = input.color(color.black                    , title="Bracket Color"                      , group="Lines and Labels"     , inline="bracket"          )
int                   extendOffset               = input.int(5                                  , title="Offset"                             , group="Lines and Labels"                                 , minval=0, tooltip="Offset to extend ahead of current bar.")
string                labelsXPos                 = input.string("right"                         , title="Label Position"                     , group="Lines and Labels"                                 , options=["left", "center", "right"])
string                labelsYPos                 = input.string("top"                           , title=""                                   , group="Lines and Labels"     , inline="label"            , options=["top", "center", "bottom"])
color                 labelsColor                = input.color(color.black                    , title="Label Style"                        , group="Lines and Labels"     , inline="style"            )
lib.TextSizeType      labelsSize                 = input.enum(lib.TextSizeType.SMALL            , title=""                                   , group="Lines and Labels"     , inline="style"            )
// Misc
bool                  enableDebugLogs            = input.bool(false                             , title="Enable debug logs"                  , group="Misc")
 
// -- CONSTANTS, TYPES, METHODS, FUNCTIONS -- //
// ------------------------------------------ //
var lib.Debugger debugger = lib.Debugger.new()
debugger.enable(enableDebugLogs)
 
//@function Format the projection label with STDEV and price values
//@param stdev  
//@param price
formatProjectionLabel(float stdev, float price) =>
    result = switch labelsProjectionContent
        ProjectionLabelType.stdev => str.format("{0,number,0.0}", stdev)
        ProjectionLabelType.price => str.format("{0,number,#.00}", price)
        ProjectionLabelType.both => str.format("{0,number,0.0} ({1,number,#.00})", stdev, price)
 
type GroupLine
    float top        = na
    float bottom     = na
    int   startIndex = na
    line  topLine    = na
    line  bottomLine = na
    line  vertLine   = na
 
method init(GroupLine this, float top, float bottom, int startIndex, color lineColor) =>
    int x1 = startIndex
    int x2 = startIndex + BRACKET_WIDTH
    color c = bracketColor
 
    if not na(lineColor)
        c := lineColor
    
    this.topLine := line.new(x1, top, x2, top, xloc=xloc.bar_index, color=c)
    this.bottomLine := line.new(x1, bottom, x2, bottom, xloc=xloc.bar_index, color=c)
    this.vertLine := line.new(x2, top, x2, bottom, xloc=xloc.bar_index, color=c)
 
method updateRange(GroupLine this, float top = na, float bottom = na, int startIndex = na) =>
    if not na(top)
        this.top := top
        this.topLine.set_y1(top)
        this.topLine.set_y2(top)
        this.vertLine.set_y1(top)
    
    if not na(bottom)
        this.bottom := bottom
        this.bottomLine.set_y1(bottom)
        this.bottomLine.set_y2(bottom)
        this.vertLine.set_y2(bottom)
 
    if not na(startIndex)
        int x1 = startIndex
        int x2 = startIndex + BRACKET_WIDTH
 
        this.topLine.set_x1(x1)
        this.topLine.set_x2(x2)
        this.bottomLine.set_x1(x1)
        this.bottomLine.set_x2(x2)
        this.vertLine.set_x1(x2)
        this.vertLine.set_x2(x2)
 
method destroy(GroupLine this) =>
    this.topLine.delete()
    this.bottomLine.delete()
    this.vertLine.delete()
 
//@type Represents an opening range session
type OpeningRange
    // `true` for the very first bar update at the start of the session; `false` otherwise
    bool isNew = true
    // `true` once the session has ended and the bar state is confirmed (closed)
    bool isConfirmed = false
    // `true` once all drawings have been completed for the session and no further updates will be applied
    bool isFinal = false
    // bar_index of the start of the session
    int startIndex = na
    // time of the start of the session
    int startTime = na
    // bar_index of the end of the session
    int endIndex = na
    // time of the end of the session
    int endTime = na
    // opening price of the session
    float open_price = na
    // closing price of the session
    float close_price = na
    // lowest price within the range
    float range_low = na
    // highest price within the range
    float range_high = na
    // lowest swing low within the range
    float range_swing_low = na
    // highest swing high within the range
    float range_swing_high = na
    float dynamicLow = na
    float dynamicHigh = na
    bool qualified = true
    array<line> sessionLines = na
    array<lib.LineLabel> lines
    GroupLine group = na
 
//@method       Gets the range size
//@param this   (OpeningRange)
method rangeSize(OpeningRange this) => 
    rangeLevelsFromSwingToggle and not na(this.range_swing_high) and not na(this.range_swing_low)
      ? this.range_swing_high - this.range_swing_low
      : this.range_high - this.range_low
 
method canShowOption(OpeningRange this, bool optionToggle, bool minToggle) =>
    optionToggle and (
      minRangeTicks == 0 or // min ticks disabled
      this.rangeSize() >= minRangeTicks or  // range size satisfies limit
      (this.rangeSize() < minRangeTicks) and (optionToggle == minToggle) // range size below limit but option is set to display anyway
      )
 
//@method       Removes all drawn lines and labels for the range
//@param this   (OpeningRange)
method destroy(OpeningRange this) =>
    for l in this.lines
        l.destroy()
    
    if not na(this.group)
        this.group.destroy()
 
// -- VARIABLES -- //
// --------------- //
 
// Total session count (previous plus current)
var totalSessions = numPrevSessions + 1
//@variable Reference to all visible ranges
var array<OpeningRange> ranges = array.new<OpeningRange>(totalSessions)
//@variable References the most recent range, which may be newly forming and not yet closed.
var OpeningRange r = na
 
// Formatting
var string textSize   = lib.style_getTextSizeFromType(labelsSize)
var string textHAlign = text.align_right
var string textVAlign = text.align_bottom
 
// Validations
 
// Chart data is based on the 1m timeframe which we can calculate up to 15m, but anything beyond that
// we'll raise an error.
var int tf = timeframe.in_seconds(timeframe.period)
var array<string> tfs = str.split(VALID_PERIOD_SECONDS, ",")
if not tfs.includes(str.tostring(timeframe.in_seconds(timeframe.period)))
    runtime.error("[ICT ORP] Invalid timeframe. Valid options: 1s, 5s, 15s, 30s, 1m, 5m, 10m, 15m")
 
// Validate projection value against manual input to ensure it is in .5 increments
var bool isValidProjectionValue = ((projectionsSTD * 10) % 5) == 0
if not isValidProjectionValue
    runtime.error(str.format("[ICT ORP] Invalid Max Standard Deviation ({0}). Value must be in .5 increments.", projectionsSTD))
 
// Opening range sessions
var lib.Session lastSession = na
var bool sessionsConfigured = false
lib.Session currentSession = na
 
var lib.Session SESS_1 = lib.Session.new(MIDNIGHT_NAME  , "0000-0030" , midnightToggle).init()
//var lib.Session SESS_2 = lib.Session.new(LONDON_NAME    , "0130-0200" , londonToggle).init()
var lib.Session SESS_3 = lib.Session.new(NY_AM_NAME     , "0930-1000" , nyAmToggle).init()
var lib.Session SESS_4 = lib.Session.new(NY_PM_NAME     , "1330-1400" , nyPmToggle).init()
//var lib.Session SESS_5 = lib.Session.new(ASIA_NAME      , "2000-2030" , asiaToggle).init()
var lib.Session SESS_6 = lib.Session.new(USER_SESS1_NAME, userSession1, userSession1Toggle).init()
var lib.Session SESS_7 = lib.Session.new(USER_SESS2_NAME, userSession2, userSession2Toggle).init()
var lib.Session SESS_8 = lib.Session.new(USER_SESS3_NAME, userSession3, userSession3Toggle).init()
var array<lib.Session> sessions = array.new<lib.Session>()
 
// The loop below is expensive as-is so if a session isn't enabled, it shouldn't be checked
if barstate.isfirst
    if midnightToggle
        sessions.push(SESS_1)
    // if londonToggle
    //     sessions.push(SESS_2)
    if nyAmToggle
        sessions.push(SESS_3)
    if nyPmToggle
        sessions.push(SESS_4)
    // if asiaToggle
    //     sessions.push(SESS_5)
    if userSession1Toggle
        sessions.push(SESS_6)
    if userSession2Toggle
        sessions.push(SESS_7)
    if userSession3Toggle
        sessions.push(SESS_8)
 
// -- MAIN EXECUTION -- //
// -------------------- //
 
// Get the bar data for 1m
[_open, _high, _low, _close, _time, _bar, _isNewBar, _isConfirmedBar] = request.security_lower_tf(
  syminfo.tickerid,  
  timeframe.in_seconds(timeframe.period) > 60 ? "1" : "", 
  [open, high, low, close, time, bar_index, barstate.isnew, barstate.isconfirmed])
 
debugger.group("main")
for [i, val] in _time
    debugger.log("Getting security values ", lib.kv("_time size", _time.size()))
    __open = _open.get(i)
    __high = _high.get(i)
    __low = _low.get(i)
    __close = _close.get(i)
    __time = _time.get(i)
    __bar_index = _bar.get(i)
    __isNewBar = _isNewBar.get(i)
    __isConfirmedBar = _isConfirmedBar.get(i)
    bool isNewSession = false
 
    // Check if we're currently in a session, and update the last session if there's a change
    if __isNewBar
        debugger.group("session")
        for [name, sess] in sessions
            if sess.enabled and sess.isActive(__time)
                currentSession := sess
                debugger.log("Current session", sess.name)
                if na(lastSession) or lastSession.start < currentSession.start
                    // Copy the instance, otherwise reference will be set and the above condition on future script executions
                    // will never be true as we'd be comparing start times of the same session reference.
                    lastSession := currentSession.copy()
                    isNewSession := true
                    debugger.log("New session", lib.kv("name", sess.name))
                break
        debugger.groupEnd("session")
 
    // Create a new range if it is a new session, removing the oldest range if necessary
    if isNewSession
        debugger.log("New opening range")
        r := OpeningRange.new(startIndex=bar_index, startTime=currentSession.start, endTime=currentSession.end, open_price=__open)
        r.lines := array.new<lib.LineLabel>()
        r.sessionLines := array.new<line>()
        
        // Remove old range
        if (array.size(ranges) >= numPrevSessions)
            OpeningRange _r = array.pop(ranges)
 
            if not na(_r)
                _r.destroy()
 
        // Add new range
        array.unshift(ranges, r)
 
    // Determine if a range has yet been established. The will only be false until the first instance, then always
    // true. This condition's only purpose is to avoid the runtime error when the first bar is painted.
    debugger.log("Current range", str.tostring(not na(r)))
    if not na(r)
        bool extendLines     = false
        bool showOpenPrice   = r.canShowOption(openingPriceToggle, minRangeOP)
        bool showRangeHL     = r.canShowOption(rangeLevelsToggle, minRangeRL)
        bool showRangeQuads  = r.canShowOption(quadLevelsToggle, minRangeQL)
        bool showProjections = r.canShowOption(projectionsToggle, minRangePR)
        bool showBracket     = showRangeHL or showProjections
 
        debugger.log("Is confirmed", lib.kv("bar confirmed", __isConfirmedBar), lib.kv("range confirmed", r.isConfirmed))
        if __isConfirmedBar
            debugger.group("range")
            // Update the current range properties if it is still forming
            if not r.isConfirmed
                debugger.log("Updating current properties")
                r.isNew := isNewSession
                r.isConfirmed := r.endTime == __time
                r.endIndex := bar_index
                r.close_price := r.isConfirmed ? __close : na
                r.range_low := math.min(nz(r.range_low, __low), __low)
                r.range_high := math.max(nz(r.range_high, __low), __high)
 
                // Determine range high/low from swing points
                if rangeLevelsFromSwingToggle and __bar_index[2] >= r.startIndex
                    // swing high
                    if __high < __high[1] and __high[2] < __high[1] and __high[1] > nz(r.range_swing_high, __low[1])
                        r.range_swing_high := __high[1]
 
                    // swing low
                    if __low > __low[1] and __low[2] > __low[1] and __low[1] < nz(r.range_swing_low, __high[1])
                        r.range_swing_low := __low[1]
 
            var lib.LineLabel latestOpeningPriceLine = na
            float rangeSize = r.rangeSize()
            int endTime = r.startTime + 30 * 60 * 1000 // TODO calc based on the actual session time
 
            sT = r.startTime
            sI = r.startIndex
            eT = r.endTime
            eI = r.endIndex
            rH = not na(r.range_swing_high) ? r.range_swing_high : r.range_high
            rL = not na(r.range_swing_low) ? r.range_swing_low : r.range_low
 
            // Start of the new session/range
            if r.isNew
                // Draw session lines
                if sessionsToggle
                    debugger.log("Drawing session lines")
                    r.sessionLines.push(line.new(
                      x1=sT, y1=__open, x2=sT, y2=__open+1, extend=extend.both, xloc=xloc.bar_time,
                      color=sessionsColor, style=lib.style_getLineStyleFromType(sessionsStyle), width=sessionsWidth
                      ))
                    r.sessionLines.push(line.new(
                      x1=eT, y1=__open, x2=eT, y2=__open+1, extend=extend.both, xloc=xloc.bar_time,
                      color=sessionsColor, style=lib.style_getLineStyleFromType(sessionsStyle), width=sessionsWidth
                      ))
                        
                // Draw opening price line. This line draws as soon as the session opens since it is static for the range,
                // unlike the other render options which require the full range to be established before rendering.
                // We can disable this line at the end of the session if the min range size was not met.
                debugger.log("Drawing opening price")
                latestOpeningPriceLine := lib.LineLabel.new(
                  x=sI, y=__open, 
                  color=openingPriceColor, lineStyle=openingPriceStyle, width=openingPriceWidth,
                  label=lib.format_timeToString(sT), showLabel=openingPriceLabelToggle
                  ).draw()
                r.lines.push(latestOpeningPriceLine)
 
            // Ending of the session/range
            if r.isConfirmed and not r.isFinal
                debugger.log("Opening range ended")
                r.isFinal := true
                r.qualified := r.rangeSize() >= minRangeTicks
 
                // Create the bracket if there is a visible range or projections
                if showBracket
                    r.group := GroupLine.new()
                    r.group.init(top=rH, bottom=rL, startIndex=sI, lineColor=r.qualified ? bracketColor : minRangeColor)
 
                // Opening Price (remove if not qualified)
                if not showOpenPrice and not na(latestOpeningPriceLine)
                    latestOpeningPriceLine.destroy()
 
                // Range H/L Levels
                if showRangeHL
                    debugger.log("Drawing range low/high", lib.kv("low", rL), lib.kv("high", rH))
                    // Range low
                    r.lines.push(lib.LineLabel.new(
                      x=sI, y=rL, 
                      color=rangeLevelsColor, lineStyle=rangeLevelsStyle, width=rangeLevelsWidth,
                      label=str.tostring(RangeLabel.LOW), showLabel=rangeLabelToggle
                      ).draw())
                    // Range high
                    r.lines.push(lib.LineLabel.new(
                      x=sI, y=rH,
                      color=rangeLevelsColor, lineStyle=rangeLevelsStyle, width=rangeLevelsWidth,
                      label=str.tostring(RangeLabel.HIGH), showLabel=rangeLabelToggle
                      ).draw())
                
                // Range Quadrants 
                if showRangeQuads
                    float diff = rH - rL
                    float price25 = rL + (0.25 * diff)
                    float price50 = rL + (0.50 * diff)
                    float price75 = rL + (0.75 * diff)
                    int ceWidth = quadLevelsEnhanceCE ? quadLevelsWidth + 1 : quadLevelsWidth
 
                    debugger.log("Drawing quadrants", lib.kv("75%", price75), lib.kv("50%", price50), lib.kv("25%", price25))
 
                    // 25%
                    r.lines.push(lib.LineLabel.new(
                      x=sI, y=price25, 
                      color=quadLevelsColor, lineStyle=quadLevelsStyle, width=quadLevelsWidth,
                      label=str.tostring(RangeLabel.QUAD_25), showLabel=quadLevelsToggle
                      ).draw())
                    // 50% (C.E.)
                    r.lines.push(lib.LineLabel.new(
                      x=sI, y=price50, 
                      color=quadLevelsColor, lineStyle=quadLevelsStyle, width=ceWidth,
                      label=str.tostring(RangeLabel.QUAD_50), showLabel=quadLevelsToggle
                      ).draw())
                    // 75%
                    r.lines.push(lib.LineLabel.new(
                      x=sI, y=price75, 
                      color=quadLevelsColor, lineStyle=quadLevelsStyle, width=quadLevelsWidth,
                      label=str.tostring(RangeLabel.QUAD_75), showLabel=quadLevelsToggle
                      ).draw())
                
                // Projections
                debugger.group("projections")
                debugger.log("Can show projections", lib.kv("showProjections", showProjections))
                if showProjections
                    float priceLow = na
                    float priceHigh = na
 
                    // Minimum value of 0.5 is used since the user may input 0 for infinite dynamic levels
                    if not projectionsDynamic
                        for lvl = 1 to int(math.max(0.5, projectionsSTD) / 0.5)
                            priceLow := rL + (lvl * -0.5 * rangeSize)
                            priceHigh := rH + (lvl * 0.5 * rangeSize)
                            debugger.log("Drawing fixed projection", lib.kv(str.format("{0}", lvl * -0.5), priceLow), lib.kv(str.format("{0}", lvl * 0.5), priceHigh))
                            
                            r.lines.push(lib.LineLabel.new(
                              x=sI, y=priceLow, 
                              color=projectionsColor, lineStyle=projectionsStyle, width=projectionsWidth,
                              label=formatProjectionLabel(lvl * -0.5, priceLow), showLabel=projectionLabelToggle
                              ).draw())
                            r.lines.push(lib.LineLabel.new(
                              x=sI, y=priceHigh, 
                              color=projectionsColor, lineStyle=projectionsStyle, width=projectionsWidth,
                              label=formatProjectionLabel(lvl * 0.5, priceHigh), showLabel=projectionLabelToggle
                              ).draw())
 
                            // Extends the bracket to the projections
                            debugger.log("Extending fixed group line", lib.kv("top", priceHigh), lib.kv("bottom", priceLow))
                            r.group.updateRange(top=priceHigh, bottom=priceLow)
                    
                    // Set the initial dynamic level extremes
                    else
                        debugger.log("Setting initial dynamic high/low", lib.kv("high", rH), lib.kv("low", rL))
                        r.dynamicLow := rL
                        r.dynamicHigh := rH
                debugger.groupEnd("projections")
            debugger.groupEnd("range")                
 
        // TODO: this needs to be as efficient as possible since it will be evaluated on every bar update
        debugger.group("projections_dynamic")
        debugger.log("Dynamic projections enabled?", lib.kv("", showProjections and projectionsDynamic))
        if showProjections and projectionsDynamic
            float nextPriceLevel = na
            float nextLevel = na
            float rangeSize = r.rangeSize()
 
            // current price at or below the lowest level
            debugger.log("Is current low <= dynamic low", str.tostring(__low <= r.dynamicLow), lib.kv("low", __low), lib.kv("dynamic", r.dynamicLow))
            while __low <= r.dynamicLow
                nextPriceLevel := r.dynamicLow + (-0.5 * rangeSize)
                nextLevel := ((r.range_low - nextPriceLevel)/(rangeSize / 2)) * -0.5
                debugger.log("Calculated projected low", lib.kv("__low", __low), lib.kv("dynamicLow", r.dynamicLow), lib.kv("nextPriceLevel", nextPriceLevel))
                r.dynamicLow := nextPriceLevel
 
                if projectionsSTD == 0 or math.abs(nextLevel) <= math.max(0.5, math.abs(projectionsSTD))
                    debugger.log("Creating dynamic low line projection")
                    r.lines.push(lib.LineLabel.new(
                      x=r.startIndex, y=nextPriceLevel, 
                      color=projectionsColor, lineStyle=projectionsStyle, width=projectionsWidth,
                      label=formatProjectionLabel(nextLevel, nextPriceLevel), showLabel=projectionLabelToggle
                      ).draw())
                    
                    // Extends the bracket to the projections
                    debugger.log("Extending dynamic group line", lib.kv("bottom", nextPriceLevel))
                    r.group.updateRange(bottom=nextPriceLevel)
                    extendLines := true
 
            // current price at or above the highest level
            debugger.log("Is current high >= dynamic high", str.tostring(__high >= r.dynamicHigh), lib.kv("high", __high), lib.kv("dynamic", r.dynamicHigh))
            while __high >= r.dynamicHigh
                nextPriceLevel := r.dynamicHigh + (0.5 * rangeSize)
                nextLevel := ((nextPriceLevel - r.range_high)/(rangeSize / 2)) * 0.5
                debugger.log("Calculated projected high", lib.kv("__high", __high), lib.kv("dynamicHigh", r.dynamicHigh), lib.kv("nextPriceLevel", nextPriceLevel))
                r.dynamicHigh := nextPriceLevel
 
                if projectionsSTD == 0 or math.abs(nextLevel) <= math.max(0.5, math.abs(projectionsSTD))
                    debugger.log("Creating dynamic high line projection")
                    r.lines.push(lib.LineLabel.new(
                      x=r.startIndex, y=nextPriceLevel, 
                      color=projectionsColor, lineStyle=projectionsStyle, width=projectionsWidth,
                      label=formatProjectionLabel(nextLevel, nextPriceLevel), showLabel=projectionLabelToggle
                      ).draw())
                    
                    // Extends the bracket to the projections
                    debugger.log("Extending group line", lib.kv("top", nextPriceLevel))
                    r.group.updateRange(top=nextPriceLevel)
                    extendLines := true
        debugger.groupEnd("projections_dynamic")
 
        // Extend the levels for the range
        if barstate.isconfirmed
            debugger.group("extend_lines")
            [x2, done] = switch lineExtension
                lib.SessionExtendType.CURRENT_SESSION => [r.endIndex, __time > r.endTime]
                lib.SessionExtendType.NEXT_SESSION => [bar_index + extendOffset, false]
                lib.SessionExtendType.CURRENT_BAR => [bar_index + extendOffset, false]
            
            // Range lines need to factor in the gap between the bracket if applicable
            int BRACKET_OFFSET = BRACKET_GAP + BRACKET_WIDTH
            int x2WithGap = x2 - BRACKET_OFFSET
            
            debugger.log("Extend levels", lib.kv("type", str.tostring(lineExtension)), lib.kv("x2", x2), lib.kv("done", done))
            if not done //or extendLines
                for l in r.lines
                    l.extend(x2WithGap)
 
                if not na(r.group)
                    r.group.updateRange(startIndex=x2 - BRACKET_WIDTH)
 
            // Handle extending all previous ranges levels. We'll stack each range so they can be more easily distinguished.
            if lineExtension == lib.SessionExtendType.CURRENT_BAR
                // Iterate in reverse so the lines are stacked from oldest to newest
                int stackOffset = 0
                int groupOffset = 5
                int length = ranges.size()
                for int rI = length - 1 to 0
                    OpeningRange _r = ranges.get(rI)
                    stackOffset := stackOffset + groupOffset
                    debugger.log("Extending previous range lines", lib.kv("rI", rI), lib.kv("range na?", na(_r)), lib.kv("stackOffset", stackOffset))
                    if not na(_r)
                        for l in _r.lines
                            l.extend(x2WithGap + stackOffset)
 
                        if not na(_r.group)
                            _r.group.updateRange(startIndex=x2 + stackOffset)
            
            // Lines are extended up to the start of the next session
            else if lineExtension == lib.SessionExtendType.NEXT_SESSION
                // At the start of a new range, do the final extend for the previous range
                if r.isNew and array.size(ranges) > 1
                    OpeningRange prev = array.get(ranges, 1)
 
                    if not na(prev)
                        debugger.log("Terminate previous range levels", lib.kv("BRACKET_OFFSET", BRACKET_OFFSET))
                        for l in prev.lines
                            l.extend(r.startIndex - BRACKET_OFFSET - BRACKET_GAP)
                        
                        if not na(prev.group)
                            prev.group.updateRange(startIndex=r.startIndex - BRACKET_OFFSET)
            debugger.groupEnd("extend_lines")
debugger.groupEnd("main")
 
// Plot session labels
const string OPENING_RANGE_TITLE = "Opening Range\n"
int plotOffset = (30 / (timeframe.in_seconds(timeframe.period) / 60)) / 2 // Default to 30 mins
bool canPlotRangeLabels = false
 
if not na(currentSession)
    canPlotRangeLabels := sessionsToggle and sessionsLabelToggle and barstate.isnew and time == currentSession.start
 
 
plotchar(canPlotRangeLabels and currentSession.start == SESS_1.start
   , text=OPENING_RANGE_TITLE + MIDNIGHT_NAME  , location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)
// plotchar(canPlotRangeLabels and currentSession.start == SESS_2.start
//    , text=OPENING_RANGE_TITLE + LONDON_NAME    , location=location.top, color=color(na)
//    , textcolor=sessionsColor, offset=plotOffset)
plotchar(canPlotRangeLabels and currentSession.start == SESS_3.start
   , text=OPENING_RANGE_TITLE + NY_AM_NAME     , location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)
plotchar(canPlotRangeLabels and currentSession.start == SESS_4.start
   , text=OPENING_RANGE_TITLE + NY_PM_NAME     , location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)
// plotchar(canPlotRangeLabels and currentSession.start == SESS_5.start
//    , text=OPENING_RANGE_TITLE + ASIA_NAME      , location=location.top, color=color(na)
//    , textcolor=sessionsColor, offset=plotOffset)
plotchar(canPlotRangeLabels and currentSession.start == SESS_6.start
   , text=OPENING_RANGE_TITLE + USER_SESS1_NAME, location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)
plotchar(canPlotRangeLabels and currentSession.start == SESS_7.start
   , text=OPENING_RANGE_TITLE + USER_SESS2_NAME, location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)
plotchar(canPlotRangeLabels and currentSession.start == SESS_8.start
   , text=OPENING_RANGE_TITLE + USER_SESS3_NAME, location=location.top, color=color(na)
   , textcolor=sessionsColor, offset=plotOffset)

← 返回列表