本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RundumEntspannt | ChartBloom
//@version=6
indicator("[ChartBloom] Session Time Highlighter", overlay = true, max_lines_count = 500, behind_chart = true)
// ## ╔══════════════════════════════════════════════════════════════╗
// ## ║ ▸ INPUTS ║
// ## ╚══════════════════════════════════════════════════════════════╝ {
GENERAL = "//// GENERAL"
S1 = "//// SESSION 1"
S2 = "//// SESSION 2"
S3 = "//// SESSION 3"
S4 = "//// SESSION 4"
// Shared tooltips. Inline rows display the rightmost input's tooltip.
DAY_HELP = "Set preferred Timezone for Midnight. At Midnight all Future Sessions get Plotet. Session time zones are independent."
PREVIEW_HELP = "Calendar days including the latest chart day. 1 = current day; 5 = current day + 4. (Hidden weekends still count)"
WEEKEND_HELP = "Off: hide Saturday and Sunday in each session's time zone. Weekdays follow the session settings. Holidays are not filtered."
ZONE_HELP = "Set Session Timewindow and Timezone. Equal times = 24 hours; Earlier end = overnight."
ASIA_HELP = ZONE_HELP
GAP_HELP = ZONE_HELP
INVERT_HELP = "Off: highlight inside the session. On: highlight outside it. Sessions shorter than the chart timeframe are hidden in both modes."
dayCity = input.string("Chicago", "Calendar day time zone", options = ["Chicago", "New York", "London", "Berlin", "UTC", "Dubai", "Mumbai", "Bangkok", "Singapore", "Hong Kong", "Shanghai", "Taipei", "Seoul", "Tokyo", "Sydney"], tooltip = DAY_HELP, group = GENERAL)
futureDays = input.int(5, "Preview days (including current day)", minval = 1, maxval = 60, tooltip = PREVIEW_HELP, group = GENERAL)
showWeekends= input.bool(true, "Show Saturdays and Sundays", tooltip = WEEKEND_HELP, group = GENERAL)
enabled1 = input.bool(false, "Enabled", group = S1)
hours1 = input.session("0900-1600", "Session 1", inline = "time1", group = S1)
city1 = input.string("Tokyo", "Time zone", options = ["Chicago", "New York", "London", "Berlin", "UTC", "Dubai", "Mumbai", "Bangkok", "Singapore", "Hong Kong", "Shanghai", "Taipei", "Seoul", "Tokyo", "Sydney"], inline = "time1", tooltip = ASIA_HELP, group = S1)
invert1 = input.bool(false, "Highlight outside session", tooltip = INVERT_HELP, group = S1)
color1 = input.color(color.new(color.orange, 85), "Color", group = S1)
enabled2 = input.bool(false, "Enabled", group = S2)
hours2 = input.session("0800-1630", "Session 2", inline = "time2", group = S2)
city2 = input.string("London", "Time zone", options = ["Chicago", "New York", "London", "Berlin", "UTC", "Dubai", "Mumbai", "Bangkok", "Singapore", "Hong Kong", "Shanghai", "Taipei", "Seoul", "Tokyo", "Sydney"], inline = "time2", tooltip = ZONE_HELP, group = S2)
invert2 = input.bool(false, "Highlight outside session", tooltip = INVERT_HELP, group = S2)
color2 = input.color(color.new(color.blue, 85), "Color", group = S2)
enabled3 = input.bool(true, "Enabled", group = S3)
hours3 = input.session("0930-1600", "Session 3", inline = "time3", group = S3)
city3 = input.string("New York", "Time zone", options = ["Chicago", "New York", "London", "Berlin", "UTC", "Dubai", "Mumbai", "Bangkok", "Singapore", "Hong Kong", "Shanghai", "Taipei", "Seoul", "Tokyo", "Sydney"], inline = "time3", tooltip = ZONE_HELP, group = S3)
invert3 = input.bool(false, "Highlight outside session", tooltip = INVERT_HELP, group = S3)
color3 = input.color(color.new(color.purple, 85), "Color", group = S3)
enabled4 = input.bool(false, "Enabled", group = S4)
hours4 = input.session("1600-2000", "Session 4", inline = "time4", group = S4)
city4 = input.string("New York", "Time zone", options = ["Chicago", "New York", "London", "Berlin", "UTC", "Dubai", "Mumbai", "Bangkok", "Singapore", "Hong Kong", "Shanghai", "Taipei", "Seoul", "Tokyo", "Sydney"], inline = "time4", tooltip = GAP_HELP, group = S4)
invert4 = input.bool(false, "Highlight outside session", tooltip = INVERT_HELP, group = S4)
color4 = input.color(color.new(color.teal, 85), "Color", group = S4)
//}
// ## ╔══════════════════════════════════════════════════════════════╗
// ## ║ ▸ FUNCTIONS ║
// ## ╚══════════════════════════════════════════════════════════════╝ {
f_timezone(string city) =>
switch city
"Chicago" => "America/Chicago"
"New York" => "America/New_York"
"London" => "Europe/London"
"UTC" => "Etc/UTC"
"Dubai" => "Asia/Dubai"
"Mumbai" => "Asia/Kolkata"
"Bangkok" => "Asia/Bangkok"
"Singapore" => "Asia/Singapore"
"Hong Kong" => "Asia/Hong_Kong"
"Shanghai" => "Asia/Shanghai"
"Taipei" => "Asia/Taipei"
"Seoul" => "Asia/Seoul"
"Tokyo" => "Asia/Tokyo"
"Sydney" => "Australia/Sydney"
=> "Europe/Berlin"
f_clockMinutes(string hours, int offset) =>
int(str.tonumber(str.substring(hours, offset, offset + 2))) * 60 + int(str.tonumber(str.substring(hours, offset + 2, offset + 4)))
f_visible(bool enabled, int startMinutes, int endMinutes) =>
rawDuration = (endMinutes - startMinutes + 1440) % 1440
duration = rawDuration == 0 ? 1440 : rawDuration
enabled and timeframe.in_seconds() <= duration * 60
// Project future boundaries onto the nominal chart bar grid. [a,b) highlights segments whose left bar opens at or after a and before b.
f_barCenter(int pointTime, int anchorTime, int barMs) =>
steps = int(math.ceil(float(pointTime - anchorTime) / barMs))
anchorTime + steps * barMs
// Historical membership uses the bar's opening time. Use a chart timeframe that aligns with the chosen session times.
f_sessionBounds(int referenceTime, int startMinutes, int endMinutes, string tz) =>
startHour = int(startMinutes / 60)
startMinute = startMinutes % 60
endHour = int(endMinutes / 60)
endMinute = endMinutes % 60
overnight = endMinutes <= startMinutes ? 1 : 0
localYear = year(referenceTime, tz)
localMonth = month(referenceTime, tz)
localDay = dayofmonth(referenceTime, tz)
localDate = localYear * 10000 + localMonth * 100 + localDay
// Each of the four calls has its own cache. The full date key handles trading gaps and changes of month or year.
var int cachedDate = na
var int todayStart = na
var int todayEnd = na
var int previousStart = na
var int previousEnd = na
if na(cachedDate) or localDate != cachedDate
todayStart := timestamp(tz, localYear, localMonth, localDay, startHour, startMinute)
todayEnd := timestamp(tz, localYear, localMonth, localDay + overnight, endHour, endMinute)
previousStart := timestamp(tz, localYear, localMonth, localDay - 1, startHour, startMinute)
previousEnd := timestamp(tz, localYear, localMonth, localDay - 1 + overnight, endHour, endMinute)
cachedDate := localDate
usePrevious = referenceTime < todayStart
sessionStart = usePrevious ? previousStart : todayStart
sessionEnd = usePrevious ? previousEnd : todayEnd
[sessionStart, sessionEnd]
f_allowedDay(int referenceTime, string tz, bool weekends) =>
allowed = true
if not weekends
weekday = dayofweek(referenceTime, tz)
allowed := weekday != dayofweek.saturday and weekday != dayofweek.sunday
allowed
f_highlighted(bool visible, int startMinutes, int endMinutes, string tz, bool inverted, bool weekends) =>
highlighted = false
if visible and f_allowedDay(time, tz, weekends)
[sessionStart, sessionEnd] = f_sessionBounds(time, startMinutes, endMinutes, tz)
inside = time >= sessionStart and time < sessionEnd
highlighted := inverted ? not inside : inside
highlighted
// Only the temporary preview uses line objects; history does not need them.
var borders = array.new<line>()
var fills = array.new<linefill>()
// Each pool slot contains one highlighted window with two boundary lines.
// Reusing objects preserves their drawing order. Set all coordinates on every update so the preview also remains correct after Pine rollback.
f_updateWindow(int index, int leftCenter, int rightCenter, color fillColor, float y1, float y2) =>
if index < array.size(fills)
leftLine = array.get(borders, index * 2)
rightLine = array.get(borders, index * 2 + 1)
line.set_xy1(leftLine, leftCenter, y1)
line.set_xy2(leftLine, leftCenter, y2)
line.set_xy1(rightLine, rightCenter, y1)
line.set_xy2(rightLine, rightCenter, y2)
linefill.set_color(array.get(fills, index), fillColor)
else
leftLine = line.new(x1 = leftCenter, y1 = y1, x2 = leftCenter, y2 = y2, xloc = xloc.bar_time, extend = extend.both, color = color.new(fillColor, 100))
rightLine = line.new(x1 = rightCenter, y1 = y1, x2 = rightCenter, y2 = y2, xloc = xloc.bar_time, extend = extend.both, color = color.new(fillColor, 100))
array.push(borders, leftLine)
array.push(borders, rightLine)
array.push(fills, linefill.new(leftLine, rightLine, fillColor))
f_trimWindows(int keepCount) =>
while array.size(fills) > keepCount
linefill.delete(array.pop(fills))
line.delete(array.pop(borders))
line.delete(array.pop(borders))
f_drawSession(int firstIndex, bool visible, int originalStart, int originalEnd, string tz, bool inverted, color fillColor, int windowStart, int windowEnd, int cutoff, int gridAnchor, int barMs, int previewDays, bool weekends, float y1, float y2) =>
nextIndex = firstIndex
// Inverted highlighting covers the gap from the session end to the next session start. A 24-hour session has no such gap.
if visible and not (inverted and originalStart == originalEnd)
startHour = int(originalStart / 60)
startMinute = originalStart % 60
endHour = int(originalEnd / 60)
endMinute = originalEnd % 60
overnight = endHour * 60 + endMinute <= startHour * 60 + startMinute ? 1 : 0
baseYear = year(windowStart, tz)
baseMonth = month(windowStart, tz)
baseDay = dayofmonth(windowStart, tz)
leftBound = math.max(windowStart, cutoff)
cycleStart = timestamp(tz, baseYear, baseMonth, baseDay - 1, startHour, startMinute)
// Include adjacent local days for time zone offsets and overnight sessions.
// Use calendar dates: daylight saving days may contain 23 or 25 hours.
// Include one extra ending date for historical time zone rule changes.
// Only windows that overlap the preview horizon allocate objects.
// Daily cycles are disjoint: at most previewDays + 2 can overlap the horizon in the supported zones. Maximum: (60 + 2) * 4 * 2 = 496 lines.
for offsetDay = -1 to previewDays + 1
cycleEnd = timestamp(tz, baseYear, baseMonth, baseDay + offsetDay + overnight, endHour, endMinute)
nextStart = timestamp(tz, baseYear, baseMonth, baseDay + offsetDay + 1, startHour, startMinute)
// History switches cycles at the next start as well. Clipping here prevents overlaps caused by DST timestamp normalization.
activeEnd = math.max(cycleStart, math.min(cycleEnd, nextStart))
startTime = inverted ? activeEnd : cycleStart
endTime = inverted ? nextStart : activeEnd
// Filter actual local weekend dates, not just the session start day.
// A window crosses at most one local midnight, so the weekend mask can shorten it without splitting it into multiple windows.
if not weekends
startAllowed = f_allowedDay(startTime, tz, false)
endAllowed = f_allowedDay(endTime, tz, false)
if not startAllowed and not endAllowed
endTime := startTime
else if startAllowed != endAllowed
nextMidnight = timestamp(tz, year(startTime, tz), month(startTime, tz), dayofmonth(startTime, tz) + 1, 0, 0)
if startAllowed
endTime := math.min(endTime, nextMidnight)
else
startTime := math.max(startTime, nextMidnight)
// Clip to the configured preview horizon. History ends at cutoff and the preview begins there. Both use bar centers exclusively.
leftTime = math.max(startTime, leftBound)
rightTime = math.min(endTime, windowEnd)
if rightTime > leftTime
leftCenter = f_barCenter(leftTime, gridAnchor, barMs)
rightCenter = f_barCenter(rightTime, gridAnchor, barMs)
if rightCenter > leftCenter
f_updateWindow(nextIndex, leftCenter, rightCenter, fillColor, y1, y2)
nextIndex += 1
// Reuse the already calculated nextStart for the following cycle.
cycleStart := nextStart
nextIndex
// Runtime ERROR Warning
if barstate.isfirst and (not timeframe.isintraday or timeframe.isticks or (not chart.is_standard and not chart.is_heikinashi))
runtime.error("Please use a time-based intraday chart, such as standard 1-minute candles.")
//}
// ## ╔══════════════════════════════════════════════════════════════╗
// ## ║ ▸ CALCULATE SESSION PLOT AREAS ║
// ## ╚══════════════════════════════════════════════════════════════╝ {
// The fill color on bar i applies to the segment from bar i-1 to bar i.
// Use the previous bar's session state for that historical segment.
// The preview starts at the current bar center using the current state.
chartBarMs = int(timeframe.in_seconds() * 1000)
// Share the parsed session inputs between history and preview.
tz1 = f_timezone(city1)
tz2 = f_timezone(city2)
tz3 = f_timezone(city3)
tz4 = f_timezone(city4)
start1 = f_clockMinutes(hours1, 0)
end1 = f_clockMinutes(hours1, 5)
start2 = f_clockMinutes(hours2, 0)
end2 = f_clockMinutes(hours2, 5)
start3 = f_clockMinutes(hours3, 0)
end3 = f_clockMinutes(hours3, 5)
start4 = f_clockMinutes(hours4, 0)
end4 = f_clockMinutes(hours4, 5)
visible1 = f_visible(enabled1, start1, end1)
visible2 = f_visible(enabled2, start2, end2)
visible3 = f_visible(enabled3, start3, end3)
visible4 = f_visible(enabled4, start4, end4)
highlighted1 = f_highlighted(visible1, start1, end1, tz1, invert1, showWeekends)
highlighted2 = f_highlighted(visible2, start2, end2, tz2, invert2, showWeekends)
highlighted3 = f_highlighted(visible3, start3, end3, tz3, invert3, showWeekends)
highlighted4 = f_highlighted(visible4, start4, end4, tz4, invert4, showWeekends)
// Hidden plots do not affect the price scale.
// Price-relative bounds avoid the rendering issues with too large Numbers like +/-1e20. Use 100 times the running maximum absolute price, with a one-tick minimum.
// Symmetric bounds also cover negative prices and crossings through zero.
barMagnitude = math.max(math.max(math.abs(nz(high, 0.0)), math.abs(nz(low, 0.0))), syminfo.mintick)
fillRadius = ta.max(barMagnitude) * 100.0
pTop = plot(fillRadius, title = "Upper fill boundary", display = display.none, editable = false)
pBottom = plot(-fillRadius, title = "Lower fill boundary", display = display.none, editable = false)
fill(pTop, pBottom, color = visible1 and highlighted1[1] ? color1 : na, title = "Session 1 history", editable = false, fillgaps = false)
fill(pTop, pBottom, color = visible2 and highlighted2[1] ? color2 : na, title = "Session 2 history", editable = false, fillgaps = false)
fill(pTop, pBottom, color = visible3 and highlighted3[1] ? color3 : na, title = "Session 3 history", editable = false, fillgaps = false)
fill(pTop, pBottom, color = visible4 and highlighted4[1] ? color4 : na, title = "Session 4 history", editable = false, fillgaps = false)
if barstate.islast
dayTz = f_timezone(dayCity)
referenceTime = time
referenceYear = year(referenceTime, dayTz)
referenceMonth = month(referenceTime, dayTz)
referenceDay = dayofmonth(referenceTime, dayTz)
todayStart = timestamp(dayTz, referenceYear, referenceMonth, referenceDay, 0, 0)
previewEnd = timestamp(dayTz, referenceYear, referenceMonth, referenceDay + futureDays, 0, 0)
cutoff = time
y1 = math.max(nz(close, 1.0), syminfo.mintick)
y2 = y1 + math.max(syminfo.mintick, math.abs(y1) * 0.001)
usedWindows = f_drawSession(0, visible1, start1, end1, tz1, invert1, color1, todayStart, previewEnd, cutoff, time, chartBarMs, futureDays, showWeekends, y1, y2)
usedWindows := f_drawSession(usedWindows, visible2, start2, end2, tz2, invert2, color2, todayStart, previewEnd, cutoff, time, chartBarMs, futureDays, showWeekends, y1, y2)
usedWindows := f_drawSession(usedWindows, visible3, start3, end3, tz3, invert3, color3, todayStart, previewEnd, cutoff, time, chartBarMs, futureDays, showWeekends, y1, y2)
usedWindows := f_drawSession(usedWindows, visible4, start4, end4, tz4, invert4, color4, todayStart, previewEnd, cutoff, time, chartBarMs, futureDays, showWeekends, y1, y2)
f_trimWindows(usedWindows)
//}