本页源码来自 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/
// © evawpd141
//@version=6
indicator("YURI Clock Range Engine", "YURI CRE", overlay = false, precision = 1)
// How wide the last stretch of bars is, ranked twice: once against the same point
// of the session on previous sessions, and once against its own recent readings
// with the clock left in. The first number is the reading. The second is here to
// be subtracted from it.
//
// The span itself is the highest high minus the lowest low of the last N minutes,
// divided by the midpoint of that span and multiplied by 10,000, so it reads in
// basis points and a symbol that has doubled in price since last year still
// produces numbers on the same scale as it did before.
//
// Raw, that number is mostly a clock. On sixty sessions of five minute bars on a
// Nasdaq index fund the median 45 minute span ran 72.5 bps at 10:10 and 21.1 bps
// at 15:30, a factor of 3.4 across the day; on an S&P index fund over the same
// window it was 33.6 bps against 12.8 bps. So an absolute span tells you the time
// of day first and what the session is doing second, and a rank taken over a
// rolling window of bars inherits that: on the Nasdaq fund a rank against the last
// 200 readings put the bar in its bottom fifth on none of the 10:20 bars and on
// 54% of the 14:30 bars.
//
// Ranking today's span against the span at the same slot of previous sessions
// takes the clock out, because every number in the comparison was measured at the
// same time of day. What is left is the part that belongs to today: this stretch
// of the session is tight, or wide, for this hour.
//
// Both ranks are of one quantity, so the first question is whether they are the
// same number twice. They are not, and it was checked rather than assumed: the two
// disagree by up to 92 points, they land on the same value on under 2% of bars,
// and their rank correlation is 0.57 on the Nasdaq fund and 0.65 on the S&P fund.
// The folded comparison, distance from the middle against distance from the
// middle, comes out at 0.28 and 0.32, so one is not a mirror of the other either.
//
// The gap between them is the interesting part, because the two ranks differ only
// in which readings they are compared against. Everything else, the window, the
// bar, the arithmetic, is shared. So the difference is the part of the ordinary
// rank that was the hour: it correlates 0.71 and 0.68 with time of day on the two
// funds, and its median runs from -59 points at 10:10 to +14 points at 14:30.
// Time of day on its own accounts for 60% and 54% of the gap's variance, so a
// large gap is mostly a statement about what hour it is. The gap's standard
// deviation is 27.1 points on the first fund and 25.0 on the second, and once
// the hour is taken out it drops to 17.2 and 17.0. That remainder is today.
//
// Dividing the span by a day length ATR does not do the same job. That ratio still
// carried a factor of 3.1 between its quietest and busiest slot on the Nasdaq
// fund, because a trailing average taken over a whole day is flat across the day
// by construction and cannot subtract a shape it does not have.
//
// What the clock rank does not remove is drift in the volatility regime. The
// comparison is against the last nineteen sessions, so on a stretch where
// volatility is falling the recent sessions are quieter than the ones they are
// ranked against and the rank sits low more often than a fifth of the time. On
// the measured window the share of bars in the bottom fifth ran from 18% to 39%
// across slots on the Nasdaq fund, against 20% under a flat distribution, while
// the clockless rank ran from 0% to 54% across the same slots. The clock is taken
// out. The regime is not, and it is not meant to be.
//
// A span carries no sign. The high and the low are both in it and nothing here
// looks at which one came first or where the close sits between them, so no
// reading in this script points up or down. There is no entry rule, no exit rule
// and no alert.
//
// The forming bar moves: its span includes the bar's own high and low so far, and
// both ranks move with it. The comparison buffers are written only when a bar
// closes, so a bar that has closed contributes one fixed reading and later bars do
// not rewrite it.
// Window -----------------------------------------------------------------------
winMinutes = input.int(45, "Window the span is measured over, minutes", minval = 10, maxval = 240, group = "Window", tooltip = "Set in minutes rather than bars so the same setting means the same stretch of the session on a 1, 5 or 15 minute chart. Converted to a whole number of bars, which is what the high and the low are actually taken over.")
rthOnly = input.bool(true, "Regular hours only", group = "Window", tooltip = "Off counts pre and post market bars, which makes the session longer and moves every slot.")
// Clock comparison ---------------------------------------------------------------
lookbackDays = input.int(20, "Sessions to compare against", minval = 5, maxval = 30, group = "Clock comparison", tooltip = "One row of the buffer per session, today included, so the pool a reading is ranked against holds one fewer than this. Short on purpose: the reference should be the regime the chart is in now.")
minSample = input.int(10, "Sessions needed before it reads", minval = 3, maxval = 29, group = "Clock comparison")
// Clockless comparison -----------------------------------------------------------
rollN = input.int(200, "Readings the clockless rank is taken over", minval = 50, maxval = 400, group = "Clockless comparison", tooltip = "Counted in readings rather than bars, because the span has no reading in the first minutes of a session. On five minute bars 200 readings is about three sessions; on fifteen minute bars it is about eight. This is the rank the clock is still in, and it is here to be compared against the other one.")
// Thresholds ---------------------------------------------------------------------
narrowPct = input.int(20, "Rank that counts as narrow for the hour", minval = 1, maxval = 45, group = "Thresholds")
widePct = input.int(80, "Rank that counts as wide for the hour", minval = 55, maxval = 99, group = "Thresholds")
holdMins = input.int(20, "Minutes a state must hold", minval = 1, maxval = 120, group = "Thresholds", tooltip = "Consecutive bars share most of the window they are measured over, so a state that flips is flipping on the newest bar alone. The default is under half the default window. In minutes so it means the same thing on any intraday chart.")
// Display -------------------------------------------------------------------------
showClockless = input.bool(true, "Draw the clockless rank", group = "Display")
showFill = input.bool(true, "Shade the gap between the two", group = "Display")
showBg = input.bool(true, "Shade the named states", group = "Display")
showTable = input.bool(true, "Show readout", group = "Display")
// A slot is a bar's place in the session, counted from the first bar that feeds a
// reading. The ceiling below is one slot per minute of a full day, which is the
// longest session any feed can hand over. A chart that runs past it stops reading
// rather than folding its late slots back onto its early ones.
int MAXSLOTS = 1440
// Refusals, in the order they are reported, and the first is the one that would
// otherwise pass unnoticed.
//
// On a non standard chart, Heikin Ashi, Renko, Kagi, Line Break, Point and Figure
// or Range, the high and the low are constructions rather than traded extremes.
// Every other test here would pass: the timeframe is intraday, the session clock
// runs, the buffer fills, and the status line would read ok while the whole
// comparison was built on prices nothing traded at.
//
// Seconds and tick charts are refused for one reason. The slot is a whole number
// of bars into the session computed from a bar length in minutes that is floored
// at one, so every bar printed inside the same minute lands in the same slot and
// the later one overwrites the earlier one in the buffer. On a 30 second chart
// that is two bars. On a tick chart it is however many bars the tape produced
// that minute.
//
// A chart whose bars are too coarse for the window is refused by name rather than
// clamped. At one bar the span is that bar's own high minus its own low, which is
// a different measurement wearing this one's label.
bool stdOk = chart.is_standard
bool intradayOk = timeframe.isintraday
bool tfGranOk = not timeframe.isseconds and not timeframe.isticks
float tfMin = math.max(1.0, timeframe.in_seconds(timeframe.period) / 60.0)
int winBars = int(math.floor(winMinutes / tfMin))
bool winOk = winBars >= 2
bool chartOk = stdOk and intradayOk and tfGranOk and winOk
// Time constants are entered in minutes and turned into bars here. Entered in bars
// they would cover a different stretch of the clock on every chart, which is the
// one thing this script cannot afford.
int holdBars = math.max(1, int(math.round(holdMins / tfMin)))
// The span. Both calls sit at the top level and run on every bar, because a ta call
// reached only on some bars does not keep the history it needs. The window is
// guarded below by a count of bars inside the session, not here.
int spanLen = math.max(2, winBars)
float hiN = ta.highest(high, spanLen)
float loN = ta.lowest(low, spanLen)
float midN = (hiN + loN) / 2.0
float spanBps = chartOk and not na(midN) and midN > 0.0 ? (hiN - loN) / midN * 10000.0 : na
// Session clock. The day boundary is taken from the exchange trading day and not
// from the market hours flag switching on. A feed delivered without any out of
// hours bars reports market hours on every bar it has, which leaves that flag
// nothing to switch; the trading day turns over regardless.
bool counting = rthOnly ? session.ismarket : true
bool newDay = ta.change(time_tradingday) != 0
var int sessionStart = na
var int rowPtr = -1
var bool sessionOpen = false
var int barsToday = 0
if newDay
sessionOpen := false
bool newSession = counting and not sessionOpen
var matrix<float> hist = matrix.new<float>(lookbackDays, MAXSLOTS, na)
if newSession
sessionOpen := true
sessionStart := time
barsToday := 0
rowPtr := (rowPtr + 1) % lookbackDays
for c = 0 to MAXSLOTS - 1
matrix.set(hist, rowPtr, c, na)
if counting
barsToday := barsToday + 1
int slot = na
if not na(sessionStart)
slot := int(math.floor((time - sessionStart) / 60000.0 / tfMin))
// The window has to sit inside today's session, and the test is a count of bars
// rather than a count of minutes. Before the session has printed spanLen bars, the
// highest and the lowest reach back past the open into the previous session, and
// the span then measures the overnight gap. Counting bars rather than clock time
// also survives a halt, where the clock runs on and the bars do not.
bool windowInside = barsToday >= spanLen
bool slotOk = chartOk and counting and windowInside and rowPtr >= 0 and not na(slot) and slot >= 0 and slot < MAXSLOTS and not na(spanBps) and spanBps > 0.0
// The span is reported only on a bar the ranks will read. Before the window is
// inside the session the arithmetic still produces a number, and that number is
// mostly the overnight gap, so it is withheld from the data window and the table
// rather than shown next to a status line explaining that it does not count.
float spanR = slotOk ? spanBps : na
float typBps = na
float clockPct = na
int sample = 0
if slotOk
array<float> colv = matrix.col(hist, slot)
array<float> vals = array.new<float>()
for i = 0 to array.size(colv) - 1
// Skip the row this session is writing into. Once the rows have wrapped
// once, that row holds today, and a reading ranked against itself sits one
// place higher than it earned.
if i != rowPtr
float v = array.get(colv, i)
if not na(v)
array.push(vals, v)
sample := array.size(vals)
if sample >= minSample
typBps := array.median(vals)
int below = 0
for i = 0 to sample - 1
if array.get(vals, i) < spanBps
below += 1
clockPct := below * 100.0 / sample
// The clockless rank, over a ring of the readings themselves rather than a window
// of bars. A window of bars would be part holes: the span has no reading in the
// first bars of every session, and those holes sit at one end of the day rather
// than spread through it.
var array<float> ring = array.new_float()
float rollPct = na
if slotOk and array.size(ring) >= rollN
int n = array.size(ring)
int belowR = 0
for i = 0 to n - 1
if array.get(ring, i) < spanBps
belowR += 1
rollPct := belowR * 100.0 / n
// Both stores take their value after both ranks have been read, and only from a
// bar that has closed. A scalar is put back as a forming bar reprices; a
// collection keeps whatever was placed in it, so a value stored mid bar would
// outlive the price that produced it. Waiting costs nothing, because neither pool
// is allowed to hold the reading it ranks in any case: the loop above skips
// today's row, and the ring is appended to only once its rank has been taken.
if slotOk and barstate.isconfirmed
matrix.set(hist, rowPtr, slot, spanBps)
array.push(ring, spanBps)
if array.size(ring) > rollN
while array.size(ring) > rollN
array.shift(ring)
float ratio = not na(clockPct) and not na(typBps) and typBps > 0.0 ? spanBps / typBps : na
float gap = not na(clockPct) and not na(rollPct) ? clockPct - rollPct : na
string rawState = na(clockPct) ? "no read" : clockPct <= narrowPct ? "narrow" : clockPct >= widePct ? "wide" : "ordinary"
// Hysteresis, so the label does not change every time a percentile crosses a line
// by one point and back. A candidate has to be the raw read on holdBars bars
// running before it takes over, and every open clears the label, since what it
// describes is the session in progress.
var string slotState = "no read"
var int held = 0
if newSession
slotState := "no read"
held := 0
if rawState == "no read"
slotState := "no read"
held := 0
else if rawState == slotState
held := 0
else if rawState == rawState[1]
held += 1
else
held := 1
if held >= holdBars
slotState := rawState
held := 0
color stateColor = slotState == "narrow" ? color.aqua : slotState == "wide" ? color.orange : slotState == "ordinary" ? color.gray : color.gray
// Plots ---------------------------------------------------------------------------
pClock = plot(clockPct, "Rank for this time of day", color.new(color.fuchsia, 0), 2)
pRoll = plot(showClockless ? rollPct : na, "Rank ignoring the clock", color.new(color.gray, 0), 1)
// One bright line against a grey reference, rather than two lines of equal
// weight. The reading is the clock rank; the clockless rank is the thing it is
// measured against, and the shading between them is the difference. The shading
// carries no sign colour, because the sign of the gap says which way the hour
// leans and not which way the session does.
fill(pClock, pRoll, showFill and showClockless and not na(gap) ? color.new(color.gray, 88) : na)
// Fixed levels. They stay at 20, 50 and 80 when the thresholds are moved and they
// stay drawn on a chart the script refuses, where every series and every value cell
// is empty.
hline(50, "Middle", color.new(color.gray, 75), hline.style_dotted)
hline(80, "Fixed 80 line", color.new(color.gray, 50), hline.style_dashed)
hline(20, "Fixed 20 line", color.new(color.gray, 50), hline.style_dashed)
bgcolor(showBg and (slotState == "narrow" or slotState == "wide") ? color.new(stateColor, 90) : na, title = "Named states")
plot(spanR, "Span (bps of its midpoint)", display = display.data_window)
plot(typBps, "Typical span at this slot (bps)", display = display.data_window)
plot(ratio, "Span against typical", display = display.data_window)
plot(gap, "Clock rank minus clockless rank", display = display.data_window)
plot(slotOk ? sample * 1.0 : na, "Sessions in the pool", display = display.data_window)
plot(slotOk ? slot * 1.0 : na, "Slot", display = display.data_window)
// Table -----------------------------------------------------------------------------
// Every cell carries its own guard, so a refused chart, a session that has not
// printed enough bars yet and a thin pool each empty exactly the cells they
// invalidate.
string spanTxt = na(spanR) ? "-" : str.tostring(spanR, "0.0") + " bps over " + str.tostring(spanLen) + " bars"
string clockTxt = na(clockPct) ? "-" : (slotState == "no read" ? "forming" : slotState) + ", percentile " + str.tostring(clockPct, "0") + " against " + str.tostring(sample) + " sessions"
string typTxt = na(ratio) ? "-" : str.tostring(ratio, "0.00") + "x the median span at this slot, " + str.tostring(typBps, "0.0") + " bps"
string rollTxt = na(rollPct) ? "-" : "percentile " + str.tostring(rollPct, "0") + " of the last " + str.tostring(array.size(ring)) + " readings"
string gapTxt = na(gap) ? "-" : gap == 0.0 ? "the two agree on this bar" : gap > 0.0 ? "+" + str.tostring(gap, "0") + " points above the clockless rank, mostly the hour" : str.tostring(gap, "0") + " points below the clockless rank, mostly the hour"
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not intradayOk ? "needs an intraday chart" : not tfGranOk ? "needs a chart of one minute or more" : not winOk ? "window is shorter than two bars on this chart" : not counting ? "outside the counting window" : na(slot) or slot >= MAXSLOTS ? "no session clock" : not windowInside ? "window not inside the session yet, " + str.tostring(barsToday) + " of " + str.tostring(spanLen) + " bars" : na(clockPct) ? "warming up, " + str.tostring(sample) + " of " + str.tostring(minSample) + " sessions" : na(rollPct) ? "clock rank only, ring holds " + str.tostring(array.size(ring)) + " of " + str.tostring(rollN) : "ok"
if showTable and barstate.islast
var table t = table.new(position.top_right, 2, 6, border_width = 1)
table.cell(t, 0, 0, "Span now", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 0, spanTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 1, "For this time of day", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 1, clockTxt, text_color = color.white, bgcolor = color.new(stateColor, 25), text_size = size.small)
table.cell(t, 0, 2, "Against a typical session", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 2, typTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 3, "Ignoring the clock", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 3, rollTxt, text_color = color.white, bgcolor = color.new(color.gray, 85), text_size = size.small)
table.cell(t, 0, 4, "Difference the clock makes", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 4, gapTxt, text_color = color.white, bgcolor = color.new(color.gray, 85), text_size = size.small)
table.cell(t, 0, 5, "Status", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 5, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)