本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0
// © cfdtools
//
// Hour-of-Day Volatility Profile
// Measures how far price typically travels in each clock hour of the day (in the
// time zone you choose), using the last N completed days of each hour. A table
// ranks the 24 hours, marks the current hour, and compares the range traded so
// far in the current hour with its typical range. Optional shading marks bars in
// historically active hours, and an alert fires when the current hour's range
// reaches a chosen multiple of its typical range.
// Every average only uses hours that had already finished on that bar, so
// historical values are not revised later.
indicator("Hour-of-Day Volatility Profile", shorttitle = "Hourly Vol Profile", overlay = true)
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
GRP_DATA = "Measurement"
GRP_TBL = "Table"
GRP_HL = "Shading & alerts"
tzIn = input.string("Etc/UTC", "Time zone", options = ["Exchange", "Etc/UTC", "Europe/London", "Europe/Berlin", "America/New_York", "America/Chicago", "Asia/Dubai", "Asia/Kolkata", "Asia/Singapore", "Asia/Tokyo", "Australia/Sydney"], group = GRP_DATA, tooltip = "Clock used to group bars into hours. 'Exchange' uses the symbol's own exchange time zone.")
lookback = input.int(60, "Samples per hour (days)", minval = 5, maxval = 500, group = GRP_DATA, tooltip = "How many completed occurrences of each hour are averaged. Older samples drop out as new ones arrive.")
rangeMode = input.string("High - Low", "Range measure", options = ["High - Low", "True range (includes gap)"], group = GRP_DATA, tooltip = "High - Low: the distance between the highest high and lowest low inside the hour. True range: also includes any gap from the previous hour's close.")
unitMode = input.string("Price", "Units", options = ["Price", "% of price"], group = GRP_DATA, tooltip = "% of price keeps hours comparable when the price level has changed a lot during the lookback.")
skipPartial = input.bool(true, "Ignore incomplete hours", group = GRP_DATA, tooltip = "Skips hours that do not contain the full number of chart bars, such as the hour a market opens or closes mid-hour, or hours with missing bars.")
minSamples = input.int(10, "Minimum samples to use an hour", minval = 1, group = GRP_DATA)
showTable = input.bool(true, "Show table", group = GRP_TBL)
tblPosIn = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Middle left", "Bottom left"], group = GRP_TBL)
tblTxtIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = GRP_TBL)
hideEmpty = input.bool(true, "Hide hours without enough samples", group = GRP_TBL, tooltip = "Hides hours when the market is closed or that have fewer samples than the minimum.")
coolCol = input.color(#3D5A80, "Quiet hour color", group = GRP_TBL)
hotCol = input.color(#E07A3F, "Active hour color", group = GRP_TBL)
nowCol = input.color(#F2C94C, "Current hour marker", group = GRP_TBL)
showBg = input.bool(false, "Shade bars in active hours", group = GRP_HL)
activeMult = input.float(1.25, "Active hour threshold (x mean of all hours)", minval = 0.1, step = 0.05, group = GRP_HL, tooltip = "An hour counts as active when its average range is at least this multiple of the average across all hours with enough samples.")
bgCol = input.color(color.new(#E07A3F, 88), "Shade color", group = GRP_HL)
alertMult = input.float(1.5, "Alert when current hour reaches (x typical)", minval = 0.1, step = 0.1, group = GRP_HL)
// ─────────────────────────────────────────────────────────────────────────────
// Setup
// ─────────────────────────────────────────────────────────────────────────────
string tz = tzIn == "Exchange" ? syminfo.timezone : tzIn
int tfSec = timeframe.in_seconds()
bool tfOk = timeframe.isintraday and tfSec > 0 and tfSec <= 3600 and 3600 % tfSec == 0
int expected = tfOk ? int(3600 / tfSec) : 1
bool isPct = unitMode == "% of price"
var matrix<float> samples = matrix.new<float>(24, lookback, na)
var array<float> sums = array.new<float>(24, 0.0)
var array<int> counts = array.new<int>(24, 0)
var array<int> heads = array.new<int>(24, 0)
// Add one completed-hour sample to the rolling window of hour h.
pushSample(int h, float v) =>
int c = array.get(counts, h)
int pos = array.get(heads, h)
if c >= lookback
array.set(sums, h, array.get(sums, h) - matrix.get(samples, h, pos))
else
array.set(counts, h, c + 1)
matrix.set(samples, h, pos, v)
array.set(sums, h, array.get(sums, h) + v)
array.set(heads, h, (pos + 1) % lookback)
// Average range of hour h, or na when there are not enough samples.
hourAvg(int h) =>
int c = array.get(counts, h)
c >= minSamples and c > 0 ? array.get(sums, h) / c : na
toUnits(float rng, float ref) =>
isPct ? (ref > 0 ? rng / ref * 100.0 : na) : rng
fmt(float v) =>
na(v) ? "-" : isPct ? str.tostring(v, "0.000") + "%" : str.tostring(v, format.mintick)
hourLabel(int h) =>
(h < 10 ? "0" : "") + str.tostring(h) + ":00"
// ─────────────────────────────────────────────────────────────────────────────
// Group bars into clock hours
// ─────────────────────────────────────────────────────────────────────────────
int hr = hour(time, tz)
int dy = dayofmonth(time, tz)
bool newBucket = barstate.isfirst or hr != hr[1] or dy != dy[1]
var int bHour = na
var float bHigh = na
var float bLow = na
var float bClose = na
var float bPrevClose = na
var int bBars = 0
var bool bIsFirst = true
if tfOk
if newBucket
// Finalise the hour that just ended.
if not na(bHour) and not bIsFirst and (not skipPartial or bBars >= expected)
float hi = rangeMode == "High - Low" ? bHigh : math.max(bHigh, nz(bPrevClose, bHigh))
float lo = rangeMode == "High - Low" ? bLow : math.min(bLow, nz(bPrevClose, bLow))
float val = toUnits(hi - lo, bClose)
if not na(val)
pushSample(bHour, val)
bIsFirst := na(bHour)
bPrevClose := bClose
bHour := hr
bHigh := high
bLow := low
bBars := 1
else
bHigh := math.max(bHigh, high)
bLow := math.min(bLow, low)
bBars += 1
bClose := close
// Range traded so far in the current (unfinished) hour.
float curHi = rangeMode == "High - Low" ? bHigh : math.max(bHigh, nz(bPrevClose, bHigh))
float curLo = rangeMode == "High - Low" ? bLow : math.min(bLow, nz(bPrevClose, bLow))
float curVal = tfOk and not na(bHour) ? toUnits(curHi - curLo, close) : na
float typNow = tfOk and not na(bHour) ? hourAvg(bHour) : na
float ratioNow = not na(curVal) and not na(typNow) and typNow > 0 ? curVal / typNow : na
// Mean, min and max of the hourly averages.
float meanAll = na
float minAvg = na
float maxAvg = na
if tfOk
float tot = 0.0
int n = 0
for h = 0 to 23
float a = hourAvg(h)
if not na(a)
tot += a
n += 1
minAvg := na(minAvg) ? a : math.min(minAvg, a)
maxAvg := na(maxAvg) ? a : math.max(maxAvg, a)
meanAll := n > 0 ? tot / n : na
// ─────────────────────────────────────────────────────────────────────────────
// Shading, data window and alerts
// ─────────────────────────────────────────────────────────────────────────────
bool isActive = tfOk and not na(typNow) and not na(meanAll) and typNow >= activeMult * meanAll
bgcolor(showBg and isActive ? bgCol : na, title = "Active hour shading")
plot(ratioNow * 100.0, "Current hour range (% of typical)", display = display.data_window)
plot(typNow, "Typical range for this hour", display = display.data_window)
bool hotNow = not na(ratioNow) and ratioNow >= alertMult
bool hotStart = hotNow and (newBucket or not hotNow[1])
alertcondition(hotStart, "Hour range above typical", "{{ticker}}: the current hour's range has reached the alert multiple of its typical range for this hour.")
// ─────────────────────────────────────────────────────────────────────────────
// Table
// ─────────────────────────────────────────────────────────────────────────────
string tblPos = switch tblPosIn
"Middle right" => position.middle_right
"Bottom right" => position.bottom_right
"Top left" => position.top_left
"Middle left" => position.middle_left
"Bottom left" => position.bottom_left
=> position.top_right
string tblTxt = switch tblTxtIn
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
color TBL_BG = color.new(#131722, 5)
color TBL_HEAD = color.new(#2A2E39, 0)
color TBL_TXT = color.new(#D1D4DC, 0)
var table tbl = table.new(tblPos, 5, 29, bgcolor = TBL_BG, frame_color = TBL_HEAD, frame_width = 1, border_color = TBL_HEAD, border_width = 1)
cellTxt(int col, int row, string txt, color tCol, color bg) =>
table.cell(tbl, col, row, txt, text_color = tCol, bgcolor = bg, text_size = tblTxt, text_halign = text.align_center)
if barstate.islast and showTable
table.clear(tbl, 0, 0, 4, 28)
if not tfOk
cellTxt(0, 0, "Hour-of-Day Volatility Profile: use an intraday chart of 1 hour or less\nwhose timeframe divides an hour evenly (1, 5, 15, 30 or 60 minutes).", TBL_TXT, TBL_BG)
else
cellTxt(0, 0, "Hourly volatility · " + tz + " · last " + str.tostring(lookback) + " days", TBL_TXT, TBL_HEAD)
table.merge_cells(tbl, 0, 0, 4, 0)
cellTxt(0, 1, "Hour", TBL_TXT, TBL_HEAD)
cellTxt(1, 1, "Avg range", TBL_TXT, TBL_HEAD)
cellTxt(2, 1, "Profile", TBL_TXT, TBL_HEAD)
cellTxt(3, 1, "vs mean", TBL_TXT, TBL_HEAD)
cellTxt(4, 1, "Days", TBL_TXT, TBL_HEAD)
float top = not na(maxAvg) and not na(minAvg) and maxAvg > minAvg ? maxAvg : nz(minAvg) + 1e-10
float bot = nz(minAvg)
int row = 2
for h = 0 to 23
float a = hourAvg(h)
int cnt = array.get(counts, h)
if not (hideEmpty and na(a))
bool isNow = h == bHour
string lbl = (isNow ? "▶ " : "") + hourLabel(h)
cellTxt(0, row, lbl, isNow ? color.black : TBL_TXT, isNow ? nowCol : TBL_HEAD)
if na(a)
cellTxt(1, row, "-", TBL_TXT, TBL_BG)
cellTxt(2, row, "", TBL_TXT, TBL_BG)
cellTxt(3, row, "-", TBL_TXT, TBL_BG)
else
color heat = color.from_gradient(a, bot, top, coolCol, hotCol)
int nBars = int(math.round(nz(a / maxAvg) * 10))
nBars := math.max(0, math.min(10, nBars))
string barTxt = str.repeat("█", nBars) + str.repeat("░", 10 - nBars)
cellTxt(1, row, fmt(a), color.white, color.new(heat, 20))
cellTxt(2, row, barTxt, heat, TBL_BG)
cellTxt(3, row, na(meanAll) or meanAll == 0 ? "-" : str.tostring(a / meanAll * 100.0, "0") + "%", TBL_TXT, TBL_BG)
cellTxt(4, row, str.tostring(cnt), TBL_TXT, TBL_BG)
row += 1
if row == 2
cellTxt(0, row, "Collecting data: each hour needs " + str.tostring(minSamples) + " completed samples.", TBL_TXT, TBL_BG)
table.merge_cells(tbl, 0, row, 4, row)
row += 1
// Current hour versus its typical range.
string nowTxt = "Now " + (na(bHour) ? "-" : hourLabel(bHour)) + ": " + fmt(curVal) + " so far" + (na(ratioNow) ? " (no typical value yet)" : " = " + str.tostring(ratioNow * 100.0, "0") + "% of typical " + fmt(typNow))
cellTxt(0, row, nowTxt, color.black, nowCol)
table.merge_cells(tbl, 0, row, 4, row)
row += 1
// Three most active hours.
int b1 = -1
int b2 = -1
int b3 = -1
float v1 = na
float v2 = na
float v3 = na
for h = 0 to 23
float a = hourAvg(h)
if not na(a)
if na(v1) or a > v1
b3 := b2
v3 := v2
b2 := b1
v2 := v1
b1 := h
v1 := a
else if na(v2) or a > v2
b3 := b2
v3 := v2
b2 := h
v2 := a
else if na(v3) or a > v3
b3 := h
v3 := a
string topTxt = "Most active: " + (b1 >= 0 ? hourLabel(b1) : "-") + (b2 >= 0 ? ", " + hourLabel(b2) : "") + (b3 >= 0 ? ", " + hourLabel(b3) : "")
cellTxt(0, row, topTxt, TBL_TXT, TBL_HEAD)
table.merge_cells(tbl, 0, row, 4, row)