Session & Levels

EVLabs · study · 376 行 · 点赞 23 · TradingView 原页

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

Pine Script

//@version=6
indicator("Session Highs, Lows and Previous Levels", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// ── Sessions ─────────────────────────────────────────────────────────────────
groupSessions = "Sessions"
 
sessionTimezone = input.string("Etc/UTC", "Session Time Zone", group=groupSessions)
 
showAsia = input.bool(true, "Show Asia", group=groupSessions)
asiaSession = input.session("0000-0600", "Asia Session", group=groupSessions)
 
showLondon = input.bool(true, "Show London", group=groupSessions)
londonSession = input.session("0700-1200", "London Session", group=groupSessions)
 
showNewYork = input.bool(true, "Show New York", group=groupSessions)
newYorkSession = input.session("1300-1700", "New York Session", group=groupSessions)
 
showSessionBoxes = input.bool(true, "Show Session Boxes", group=groupSessions)
boxBorderWidth = input.int(1, "Box Border Width", minval=1, maxval=4, group=groupSessions)
sessionNameOffsetATR = input.float(0.25, "Session Name Offset (ATR)", minval=0.0, step=0.05, group=groupSessions)
 
// ── Previous period levels ────────────────────────────────────────────────────
groupPrevious = "Previous Period Levels"
 
showPreviousDay = input.bool(true, "Show Previous Day High / Low", group=groupPrevious)
showPreviousWeek = input.bool(true, "Show Previous Week High / Low", group=groupPrevious)
showPreviousMonth = input.bool(true, "Show Previous Month High / Low", group=groupPrevious)
 
// ── Display ───────────────────────────────────────────────────────────────────
groupDisplay = "Display"
 
lineWidth = input.int(1, "Level Line Width", minval=1, maxval=4, group=groupDisplay)
maxActiveLevels = input.int(150, "Maximum Active Levels", minval=20, maxval=450, group=groupDisplay)
showSessionStatsTable = input.bool(true, "Show Recent Session Stats", group=groupDisplay)
 
// ── Active level storage ──────────────────────────────────────────────────────
var line[] activeLines = array.new_line()
var label[] activeLabels = array.new_label()
var float[] activePrices = array.new_float()
var bool[] activeIsHigh = array.new_bool()
 
// ── Recent session statistics ─────────────────────────────────────────────────
var string[] recentSessionNames = array.new_string()
var float[] recentSessionRanges = array.new_float()
var float[] recentSessionChanges = array.new_float()
 
var table sessionStatsTable = table.new(
     position.top_right,
     3,
     4,
     frame_color=color.gray,
     frame_width=1,
     border_color=color.new(color.gray, 60),
     border_width=1)
 
// ── Functions ─────────────────────────────────────────────────────────────────
f_addLevel(float price, bool isHigh, string levelName, color levelColor, int startBar) =>
    if not na(price)
        newLine = line.new(
             x1=startBar,
             y1=price,
             x2=bar_index,
             y2=price,
             xloc=xloc.bar_index,
             extend=extend.none,
             color=levelColor,
             width=lineWidth,
             style=line.style_dashed)
 
        newLabel = label.new(
             x=bar_index,
             y=price,
             text=levelName,
             xloc=xloc.bar_index,
             style=label.style_label_left,
             color=levelColor,
             textcolor=color.white,
             size=size.tiny)
 
        array.push(activeLines, newLine)
        array.push(activeLabels, newLabel)
        array.push(activePrices, price)
        array.push(activeIsHigh, isHigh)
 
        if array.size(activeLines) > maxActiveLevels
            line.delete(array.shift(activeLines))
            label.delete(array.shift(activeLabels))
            array.shift(activePrices)
            array.shift(activeIsHigh)
 
f_recordSession(string sessionName, float sessionOpen, float sessionClose, float sessionHigh, float sessionLow) =>
    if not na(sessionOpen) and sessionOpen != 0 and not na(sessionClose)
        rangePercent = (sessionHigh - sessionLow) / sessionOpen * 100
        changePercent = (sessionClose - sessionOpen) / sessionOpen * 100
 
        array.unshift(recentSessionNames, sessionName)
        array.unshift(recentSessionRanges, rangePercent)
        array.unshift(recentSessionChanges, changePercent)
 
        if array.size(recentSessionNames) > 3
            array.pop(recentSessionNames)
            array.pop(recentSessionRanges)
            array.pop(recentSessionChanges)
 
f_formatPercent(float value) =>
    (value > 0 ? "+" : "") + str.tostring(value, "#.##") + "%"
 
// ── Session state ─────────────────────────────────────────────────────────────
asiaActive = not na(time(timeframe.period, asiaSession, sessionTimezone))
londonActive = not na(time(timeframe.period, londonSession, sessionTimezone))
newYorkActive = not na(time(timeframe.period, newYorkSession, sessionTimezone))
 
asiaStarted = asiaActive and not asiaActive[1]
asiaEnded = not asiaActive and asiaActive[1]
 
londonStarted = londonActive and not londonActive[1]
londonEnded = not londonActive and londonActive[1]
 
newYorkStarted = newYorkActive and not newYorkActive[1]
newYorkEnded = not newYorkActive and newYorkActive[1]
 
var float asiaOpen = na
var float asiaClose = na
var float asiaHigh = na
var float asiaLow = na
 
var float londonOpen = na
var float londonClose = na
var float londonHigh = na
var float londonLow = na
 
var float newYorkOpen = na
var float newYorkClose = na
var float newYorkHigh = na
var float newYorkLow = na
 
var box asiaBox = na
var box londonBox = na
var box newYorkBox = na
 
// ── Asia session box and range ────────────────────────────────────────────────
if asiaStarted
    asiaOpen := open
    asiaClose := close
    asiaHigh := high
    asiaLow := low
    asiaBox := na
 
    if showAsia and showSessionBoxes
        asiaBox := box.new(
             left=bar_index,
             top=high,
             right=bar_index,
             bottom=low,
             xloc=xloc.bar_index,
             border_color=color.blue,
             border_width=boxBorderWidth,
             bgcolor=color.new(color.blue, 100))
else if asiaActive
    asiaClose := close
    asiaHigh := math.max(asiaHigh, high)
    asiaLow := math.min(asiaLow, low)
 
    if showAsia and showSessionBoxes and not na(asiaBox)
        box.set_right(asiaBox, bar_index)
        box.set_top(asiaBox, asiaHigh)
        box.set_bottom(asiaBox, asiaLow)
 
// ── London session box and range ──────────────────────────────────────────────
if londonStarted
    londonOpen := open
    londonClose := close
    londonHigh := high
    londonLow := low
    londonBox := na
 
    if showLondon and showSessionBoxes
        londonBox := box.new(
             left=bar_index,
             top=high,
             right=bar_index,
             bottom=low,
             xloc=xloc.bar_index,
             border_color=color.orange,
             border_width=boxBorderWidth,
             bgcolor=color.new(color.orange, 100))
else if londonActive
    londonClose := close
    londonHigh := math.max(londonHigh, high)
    londonLow := math.min(londonLow, low)
 
    if showLondon and showSessionBoxes and not na(londonBox)
        box.set_right(londonBox, bar_index)
        box.set_top(londonBox, londonHigh)
        box.set_bottom(londonBox, londonLow)
 
// ── New York session box and range ───────────────────────────────────────────
if newYorkStarted
    newYorkOpen := open
    newYorkClose := close
    newYorkHigh := high
    newYorkLow := low
    newYorkBox := na
 
    if showNewYork and showSessionBoxes
        newYorkBox := box.new(
             left=bar_index,
             top=high,
             right=bar_index,
             bottom=low,
             xloc=xloc.bar_index,
             border_color=color.purple,
             border_width=boxBorderWidth,
             bgcolor=color.new(color.purple, 100))
else if newYorkActive
    newYorkClose := close
    newYorkHigh := math.max(newYorkHigh, high)
    newYorkLow := math.min(newYorkLow, low)
 
    if showNewYork and showSessionBoxes and not na(newYorkBox)
        box.set_right(newYorkBox, bar_index)
        box.set_top(newYorkBox, newYorkHigh)
        box.set_bottom(newYorkBox, newYorkLow)
 
// ── Record completed sessions ─────────────────────────────────────────────────
if asiaEnded
    f_recordSession("Asia", asiaOpen, asiaClose, asiaHigh, asiaLow)
 
if londonEnded
    f_recordSession("London", londonOpen, londonClose, londonHigh, londonLow)
 
if newYorkEnded
    f_recordSession("New York", newYorkOpen, newYorkClose, newYorkHigh, newYorkLow)
 
// ── Completed session levels and names ────────────────────────────────────────
if asiaEnded and showAsia
    f_addLevel(asiaHigh, true, "Asia High", color.blue, bar_index[1])
    f_addLevel(asiaLow, false, "Asia Low", color.blue, bar_index[1])
 
    if showSessionBoxes and not na(asiaBox)
        label.new(
             x=int(math.round((box.get_left(asiaBox) + box.get_right(asiaBox)) / 2.0)),
             y=asiaLow - ta.atr(14) * sessionNameOffsetATR,
             text="Asia Session",
             xloc=xloc.bar_index,
             yloc=yloc.price,
             style=label.style_none,
             textcolor=color.blue,
             size=size.small,
             textalign=text.align_center)
 
if londonEnded and showLondon
    f_addLevel(londonHigh, true, "London High", color.orange, bar_index[1])
    f_addLevel(londonLow, false, "London Low", color.orange, bar_index[1])
 
    if showSessionBoxes and not na(londonBox)
        label.new(
             x=int(math.round((box.get_left(londonBox) + box.get_right(londonBox)) / 2.0)),
             y=londonLow - ta.atr(14) * sessionNameOffsetATR,
             text="London Session",
             xloc=xloc.bar_index,
             yloc=yloc.price,
             style=label.style_none,
             textcolor=color.orange,
             size=size.small,
             textalign=text.align_center)
 
if newYorkEnded and showNewYork
    f_addLevel(newYorkHigh, true, "New York High", color.purple, bar_index[1])
    f_addLevel(newYorkLow, false, "New York Low", color.purple, bar_index[1])
 
    if showSessionBoxes and not na(newYorkBox)
        label.new(
             x=int(math.round((box.get_left(newYorkBox) + box.get_right(newYorkBox)) / 2.0)),
             y=newYorkLow - ta.atr(14) * sessionNameOffsetATR,
             text="New York Session",
             xloc=xloc.bar_index,
             yloc=yloc.price,
             style=label.style_none,
             textcolor=color.purple,
             size=size.small,
             textalign=text.align_center)
 
// ── Previous day, week and month levels ───────────────────────────────────────
previousDayHigh = request.security(
     syminfo.tickerid, "D", high[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
previousDayLow = request.security(
     syminfo.tickerid, "D", low[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
previousWeekHigh = request.security(
     syminfo.tickerid, "W", high[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
previousWeekLow = request.security(
     syminfo.tickerid, "W", low[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
previousMonthHigh = request.security(
     syminfo.tickerid, "M", high[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
previousMonthLow = request.security(
     syminfo.tickerid, "M", low[1],
     gaps=barmerge.gaps_off,
     lookahead=barmerge.lookahead_on)
 
if timeframe.change("D") and showPreviousDay
    f_addLevel(previousDayHigh, true, "PDH", color.red, bar_index)
    f_addLevel(previousDayLow, false, "PDL", color.red, bar_index)
 
if timeframe.change("W") and showPreviousWeek
    f_addLevel(previousWeekHigh, true, "PWH", color.teal, bar_index)
    f_addLevel(previousWeekLow, false, "PWL", color.teal, bar_index)
 
if timeframe.change("M") and showPreviousMonth
    f_addLevel(previousMonthHigh, true, "PMH", color.fuchsia, bar_index)
    f_addLevel(previousMonthLow, false, "PML", color.fuchsia, bar_index)
 
// ── Extend levels until price breaks them ─────────────────────────────────────
if array.size(activeLines) > 0
    for i = array.size(activeLines) - 1 to 0
        currentLine = array.get(activeLines, i)
        currentLabel = array.get(activeLabels, i)
        currentPrice = array.get(activePrices, i)
        isHighLevel = array.get(activeIsHigh, i)
 
        line.set_x2(currentLine, bar_index)
        label.set_x(currentLabel, bar_index)
 
        levelInvalidated = isHighLevel ? high > currentPrice : low < currentPrice
 
        if levelInvalidated
            line.set_x2(currentLine, bar_index)
            label.set_x(currentLabel, bar_index)
 
            array.remove(activeLines, i)
            array.remove(activeLabels, i)
            array.remove(activePrices, i)
            array.remove(activeIsHigh, i)
 
// ── Recent session statistics table ───────────────────────────────────────────
if barstate.islast
    if showSessionStatsTable
        headerColor = color.new(color.black, 0)
        cellColor = color.new(color.black, 15)
 
        table.cell(sessionStatsTable, 0, 0, "Session", text_color=color.white, bgcolor=headerColor)
        table.cell(sessionStatsTable, 1, 0, "Range", text_color=color.white, bgcolor=headerColor)
        table.cell(sessionStatsTable, 2, 0, "Change", text_color=color.white, bgcolor=headerColor)
 
        for row = 0 to 2
            if row < array.size(recentSessionNames)
                sessionName = array.get(recentSessionNames, row)
                rangeValue = array.get(recentSessionRanges, row)
                changeValue = array.get(recentSessionChanges, row)
 
                rangeColor = rangeValue >= 0 ? color.lime : color.red
                changeColor = changeValue >= 0 ? color.lime : color.red
 
                table.cell(sessionStatsTable, 0, row + 1, sessionName, text_color=color.white, bgcolor=cellColor)
                table.cell(sessionStatsTable, 1, row + 1, f_formatPercent(rangeValue), text_color=rangeColor, bgcolor=cellColor)
                table.cell(sessionStatsTable, 2, row + 1, f_formatPercent(changeValue), text_color=changeColor, bgcolor=cellColor)
            else
                table.cell(sessionStatsTable, 0, row + 1, "—", text_color=color.gray, bgcolor=cellColor)
                table.cell(sessionStatsTable, 1, row + 1, "—", text_color=color.gray, bgcolor=cellColor)
                table.cell(sessionStatsTable, 2, row + 1, "—", text_color=color.gray, bgcolor=cellColor)
    else
        table.clear(sessionStatsTable, 0, 0, 2, 3)

← 返回列表