本页源码来自 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 Opening Range Engine", "YURI ORE", overlay = true)
// The high and the low of the first stretch of a session is one of the oldest
// drawings there is, and drawing it answers almost nothing: on the default
// settings price leaves that box on 98% of sessions, so "it broke out" is close
// to a description of every day. What this keeps is the part the box does not
// carry.
//
// the ledger One record per completed session on the loaded chart: how wide
// the range was as a percent of the price it opened at, whether
// price ever traded outside it afterwards, whether it closed back
// inside once it had, whether the session's last close finished
// outside, and how many minutes after the range closed the first
// excursion happened. That list is kept as the chart runs and
// none of it is recoverable from today's box.
// the group Today's range is put in the narrower or the wider half of that
// ledger, by the ledger's own median width, and the frequencies
// printed are that half's, with the count they came from and a
// standard error beside each one.
// the clock Today's first excursion in minutes after the range closed,
// against that half's median.
//
// The conditioning is measured rather than asserted, and the measurement is not
// as tidy as a script usually admits. On SPY, one hour bars, 727 completed
// sessions from 2023-10 to 2026-09 at a 60 minute range: sessions in the
// narrower half finished outside the range 71.2% of the time against 58.7% for
// the wider half, a gap of 12.5 points against a pooled standard error of 3.5.
// Whether price left the box at all separates the same way and less usefully,
// 99.5% against 96.4%, because the answer is almost always yes.
//
// Then the same measurement on the most recent 500 of those sessions, which is
// as many as this engine's default ledger will hold: 68.0% against 60.4%, a gap of
// 7.6 points against a pooled error of 4.3. That is 1.8 standard errors and it is
// not a separation. So the conditioning is not noise on the longest sample
// available and it is not stable enough to lean on, and both of those are true at
// once. Reading the first number without the second is the mistake this engine is
// built to make harder.
//
// Windows of 60 sessions say the same thing louder. Those windows overlap, so
// their count is not a sample size: cut into blocks that do not overlap there are
// 12 of them, the gap runs from -26.7 to +26.7 points, and 2 of the 12 point the
// other way round. The median of those short windows is +13.3 against the full
// run's +12.5, so a short window is not a systematic overstatement; it scatters,
// and it scatters far enough to land in either direction. A hundred sessions of
// an opening range measurement can come out anywhere in that spread, which is why
// the sample size and the standard error sit next to every frequency here instead
// of being implied.
//
// The range length is the one free parameter here and the separation does not
// survive changing it. On the same 727 sessions an hourly chart can express only
// three range spans, since every setting between one and two hours lands on the
// same two bars. At the first of them, 60 minutes, the gap is 12.5 points or 3.55
// standard errors; at the second, 120 minutes, it is 3.7
// points or 1.00; at 180 it is 5.7 points or 1.55. On the most recent 500
// sessions the longer two come out level, 127 of 250 against 127 of 250 and 103
// against 103. So what is quoted above is a property of this symbol, at this
// range length, over this stretch of history. Nothing was tuned to find it, since
// 60 minutes was fixed as the first hour before any of this was measured, and it
// is reported because a reader who changes that setting should know the evidence
// does not travel with it.
//
// One of the three does not separate at all, and it is printed anyway. Closing
// back inside after an excursion came out at 60.2% in the narrow half and 63.7%
// in the wide one, a difference of one standard error, which is no difference.
// The width group tells you nothing about it on this history and the file says so
// rather than quietly dropping the row.
//
// Neither is the width group a restatement of the ledger. Spearman between a
// session's width rank and its first excursion delay is +0.12 on that history and
// +0.05 on a pooled three symbol five minute ledger; against the three stored
// flags it runs -0.04 to -0.14. A line of 0.8 was set before any of it was drawn.
//
// What this will not do is say which side of the range anything is likely to go,
// or that a frequency is a probability. No side is stored. A session that finished
// outside is recorded as having finished outside and not as having finished above,
// because storing the side is the first step to printing a direction and there is
// nothing here that would earn one. There is no entry, no exit, no stop, no filter
// and no alert.
//
// On timing. Nothing is requested from another symbol or another timeframe, so
// there is no external calendar to sync and no lookahead to disable. Every number
// comes from the bars on the chart. The bar that is forming moves as it forms and
// settles when it closes; a bar that has closed is not rewritten afterwards. The
// ledger gains a session on the first confirmed bar of the next one, so today's
// session is never part of the history today is read against.
// Opening range ---------------------------------------------------------------
rangeMinutes = input.int(60, "Opening range length, minutes", minval = 5, maxval = 240, step = 5, group = "Opening range", tooltip = "Measured from the first bar of the trading day as the chart's exchange defines it, which on a symbol that trades around the clock is not a market open. The table prints the clock times it actually used.")
// Ledger ----------------------------------------------------------------------
maxSessions = input.int(500, "Sessions the ledger holds", minval = 20, maxval = 2000, group = "Ledger", tooltip = "Oldest out first once the list is full. A chart rarely loads this many intraday sessions, so it is usually a ceiling rather than a setting.")
minSessions = input.int(40, "Completed sessions before the ledger reads", minval = 20, maxval = 500, group = "Ledger", tooltip = "The ledger is split in half by its own median width, so this is twice the smallest group worth printing a frequency for. At 40 each half holds about 20 and a frequency near half carries a standard error of about 11 points.")
// Display ---------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showRange = input.bool(true, "Draw the opening range", group = "Display")
showFill = input.bool(true, "Tint the range by its width group", group = "Display")
// A clock string from a timestamp, in the exchange's own timezone. HH:mm pads
// both halves, so an hour of 9 and a minute of 5 come back as 09:05 rather than
// 9:5. This was hand-rolled from hour() and minute() first; it is formatted
// instead because the argument here is a stored timestamp rather than the
// built-in time, and str.format_time taking a stored timestamp is a form that
// already appears in sibling engines while hour() of one does not.
f_clk(int _t) =>
str.format_time(_t, "HH:mm", syminfo.timezone)
// The standard error of a share, in percentage points. The ledger's sessions are
// separate days and are treated as independent here, which is the assumption this
// number rests on and is weaker than it looks: volatility clusters, so consecutive
// sessions are not the independent draws a binomial error assumes, and the true
// error is the larger of the two.
f_se(float _p, int _n) =>
_n > 0 ? math.sqrt(math.max(_p * (1.0 - _p), 0.0) / _n) * 100.0 : na
// The chart type is checked first because it is the only refusal here whose cause
// is invisible in the chart's settings. A Heikin Ashi, Renko, Kagi, Line Break,
// Point and Figure or Range chart draws all four of a bar's prices from its own
// rule, and this file reads all four: the box is the highs and the lows, its
// width divides that box by the session's first open, and two of the three
// stored outcomes are decided by a close. The chart would
// still be intraday, the bars would still be short enough, and the status line
// would still have said ok.
bool stdOk = chart.is_standard
// The chart has to be intraday and its bar has to be shorter than the range, or
// there is no range to build. The seconds and ticks tests are both needed,
// because timeframe.isintraday is true on either and neither has a bar length
// this file can work with: a seconds chart would build the range out of thousands
// of bars for no gain, and a tick chart has no length in minutes at all, so the
// bar length test below would be comparing against a value the conversion has
// nothing to return. The bar length test is the one that catches a daily chart
// too, but it is tested after the intraday test so that the message names the
// real problem rather than the arithmetic.
bool tfIntra = timeframe.isintraday and not timeframe.isseconds and not timeframe.isticks
float barMin = timeframe.in_seconds() / 60.0
bool barFits = barMin <= rangeMinutes
bool tfOk = stdOk and tfIntra and barFits
// A session boundary taken from session.ismarket turning on goes missing on a feed
// that carries no out-of-session bars: such a feed is in-session on every bar it
// has, so that transition does not occur there and the range is never built. The
// trading day rolling over is a boundary that exists on both kinds of feed, which
// is why it is the one used here. On the first bar of the chart there is no
// previous day to change from, and that bar starts a session whose beginning is
// out of view.
float ttdChg = ta.change(time_tradingday)
bool newDay = bar_index == 0 or (not na(ttdChg) and ttdChg != 0)
// Today's session -------------------------------------------------------------
var int dayStart = na
var float rngHi = na
var float rngLo = na
var float rngOpen = na
var int rngBars = 0
var int postBars = 0
var bool rngDone = false
var bool leftRng = false
var bool backIn = false
var float firstDly = na
var float lastClose = na
var bool clean = false
// The ledger. Five lists written and trimmed together, so index i is the same
// session in all five. The delay list holds na for a session that never left the
// range, which keeps the alignment rather than shortening one list.
var array<float> ldgW = array.new<float>()
var array<float> ldgLeft = array.new<float>()
var array<float> ldgBack = array.new<float>()
var array<float> ldgEnd = array.new<float>()
var array<float> ldgDly = array.new<float>()
var int ldgSkip = 0
var int ldgEndMs = na
// A) The day boundary. The previous session is committed here and the new one is
// started. Arrays are not rolled back between the ticks of a forming bar the way
// scalars are, so the write waits for the bar to close; the scalars above are
// restored to their previous-bar values on every recalculation, so on the tick
// that does confirm the bar they still hold the finished session. The reset runs
// on every tick, which is correct: it only ever rebuilds from the same bars.
if newDay
if tfOk and barstate.isconfirmed and clean
if rngDone and rngBars >= 1 and not na(rngOpen) and rngOpen > 0.0 and not na(rngHi) and not na(rngLo)
array.push(ldgW, (rngHi - rngLo) / rngOpen * 100.0)
array.push(ldgLeft, leftRng ? 1.0 : 0.0)
array.push(ldgBack, backIn ? 1.0 : 0.0)
array.push(ldgEnd, not na(lastClose) and (lastClose > rngHi or lastClose < rngLo) ? 1.0 : 0.0)
array.push(ldgDly, firstDly)
ldgEndMs := time[1]
if array.size(ldgW) > maxSessions
array.shift(ldgW)
array.shift(ldgLeft)
array.shift(ldgBack)
array.shift(ldgEnd)
array.shift(ldgDly)
else
// A session whose range never finished. It is counted rather than
// dropped silently, because on a long range setting a short trading
// day produces exactly this and the count is the only way to see it.
ldgSkip += 1
dayStart := time
rngHi := na
rngLo := na
rngOpen := open
rngBars := 0
postBars := 0
rngDone := false
leftRng := false
backIn := false
firstDly := na
lastClose := close
// The session that is open on the first bar of the chart began before the
// chart did, so its range is whatever part of it loaded. It is never
// ledgered. Every session after it starts on a boundary this script saw.
clean := bar_index > 0
// B) The session itself. The range window is closed on the clock rather than
// counted in bars, so the same setting means the same span of time whatever the
// chart's bar length is. Bar time is the bar's opening time, so a bar is in the
// range when it opened inside the window; a bar that opens inside and closes
// after it is still a range bar, and the table prints the span the bars actually
// covered next to the span that was asked for.
int rngEndMs = na(dayStart) ? na : dayStart + rangeMinutes * 60000
if tfOk and not na(rngEndMs)
if time < rngEndMs
rngHi := na(rngHi) ? high : math.max(rngHi, high)
rngLo := na(rngLo) ? low : math.min(rngLo, low)
rngBars += 1
else if rngBars >= 1
rngDone := true
postBars += 1
if not leftRng
if high > rngHi or low < rngLo
leftRng := true
firstDly := (time - rngEndMs) / 60000.0
else if close >= rngLo and close <= rngHi
backIn := true
lastClose := close
float wPct = rngDone and not na(rngHi) and not na(rngLo) and not na(rngOpen) and rngOpen > 0.0 ? (rngHi - rngLo) / rngOpen * 100.0 : na
// C) The read. Everything below is a function of the ledger and of today's width,
// and neither changes again once the range has closed, so it is computed once per
// session on the bar the range finishes rather than on every bar of the day. The
// loops read arrays and call nothing from ta.*, so living inside a branch costs
// them no history; that is the reason it is safe here and would not be for a
// moving average.
bool rngJustDone = rngDone and not rngDone[1]
int ldgN = array.size(ldgW)
var float wRank = na
var float medW = na
var bool wideNow = false
var int grpN = 0
var int grpLeftN = 0
var float shLeft = na
var float shBack = na
var float shEnd = na
var float medDly = na
var bool readOk = false
if newDay
wRank := na
medW := na
wideNow := false
grpN := 0
grpLeftN := 0
shLeft := na
shBack := na
shEnd := na
medDly := na
readOk := false
if tfOk and rngJustDone and not na(wPct) and ldgN >= minSessions
// The split is the ledger's own median, which is arithmetic rather than a
// level anybody chose. A width exactly on the median goes to the narrow side,
// and so does every ledger entry equal to it, so the two sides use the same
// rule and the halves stay the halves.
medW := array.median(ldgW)
wideNow := wPct > medW
int le = 0
for i = 0 to ldgN - 1
if array.get(ldgW, i) <= wPct
le += 1
wRank := le * 100.0 / ldgN
array<float> dly = array.new<float>()
int cAll = 0
int cLeft = 0
int cBack = 0
int cEnd = 0
for i = 0 to ldgN - 1
if (array.get(ldgW, i) > medW) == wideNow
cAll += 1
if array.get(ldgLeft, i) > 0.5
cLeft += 1
if array.get(ldgBack, i) > 0.5
cBack += 1
float d = array.get(ldgDly, i)
if not na(d)
array.push(dly, d)
if array.get(ldgEnd, i) > 0.5
cEnd += 1
grpN := cAll
grpLeftN := cLeft
if cAll > 0
shLeft := cLeft * 1.0 / cAll
shEnd := cEnd * 1.0 / cAll
readOk := true
if cLeft > 0
shBack := cBack * 1.0 / cLeft
if array.size(dly) > 0
medDly := array.median(dly)
bool live = tfOk and rngDone and not na(wPct)
// Every reason there is no read gets named, in the order the reasons are tested.
// The four chart refusals come first, then the two things that are simply not
// ready yet, because a chart this cannot read is wrong before anything has had a
// chance to warm up. The chart type leads them, because when two things are
// wrong at once it is the built bars that a reader would not otherwise spot.
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not timeframe.isintraday ? "needs an intraday chart" : timeframe.isseconds or timeframe.isticks ? "needs a chart measured in minutes, not seconds or ticks" : not barFits ? "one bar is longer than the opening range, shorten the bar or lengthen the range" : not rngDone ? "the opening range for this session is still building" : na(wPct) ? "no opening range on this session" : ldgN < minSessions ? "warming up, " + str.tostring(ldgN) + " of " + str.tostring(minSessions) + " completed sessions" : not readOk ? "no completed sessions in this width group yet" : "ok"
color grpCol = not readOk ? color.gray : wideNow ? color.orange : color.blue
// The range itself. linebr so the two lines break between sessions instead of
// being joined across the overnight gap by a straight segment that was never a
// level. Both inherit the refusals through live.
pH = plot(showRange and live ? rngHi : na, "Opening range high", color.new(color.gray, 20), 1, plot.style_linebr)
pL = plot(showRange and live ? rngLo : na, "Opening range low", color.new(color.gray, 20), 1, plot.style_linebr)
// Orange when today's range is in the wider half of the ledger, blue when it is
// in the narrower half. Uncoloured while the ledger cannot say which, rather than
// defaulting to one of them.
fill(pH, pL, showFill and live and readOk ? (wideNow ? color.new(color.orange, 88) : color.new(color.blue, 88)) : na)
// Every one of these is gated. Four are arithmetic on inputs or on a counter and
// would otherwise survive a refused chart carrying a plausible looking number,
// which is the failure worth writing out rather than assuming away. On a refused
// chart there is nothing left standing but the fixed labels in the table's left
// column, and every value beside them is a dash.
plot(live ? wPct : na, "Range width, percent of open", display = display.data_window)
plot(live ? wRank : na, "Width percentile in the ledger", display = display.data_window)
plot(live and readOk ? (wideNow ? 1.0 : 0.0) : na, "Wider half of the ledger", display = display.data_window)
plot(live and readOk ? shLeft * 100.0 : na, "Group, left the range", display = display.data_window)
plot(live and readOk ? shBack * 100.0 : na, "Group, closed back inside", display = display.data_window)
plot(live and readOk ? shEnd * 100.0 : na, "Group, finished outside", display = display.data_window)
plot(live and readOk ? grpN * 1.0 : na, "Sessions in the group", display = display.data_window)
plot(live ? firstDly : na, "Minutes to the first excursion today", display = display.data_window)
plot(live and readOk ? medDly : na, "Group median minutes to first excursion", display = display.data_window)
plot(tfOk ? ldgN * 1.0 : na, "Sessions in the ledger", display = display.data_window)
plot(tfOk ? ldgSkip * 1.0 : na, "Sessions with no complete range", display = display.data_window)
plot(live ? rngBars * 1.0 : na, "Bars in the range", display = display.data_window)
plot(live ? postBars * 1.0 : na, "Bars since the range closed", display = display.data_window)
// Format strings are "0" and "0.00" rather than "#", which suppresses a lone zero
// and would print a percentile cell reading "p" with nothing after it. An exact
// zero is reachable on the width percentile, on the delay, and on all three
// frequencies.
// Two spans, and they disagree whenever the bar length does not divide the range:
// a 75 minute range on an hourly chart asks for 75 and gets two bars covering
// 120. Both are printed with a label on each, because the unlabelled pair reads
// like a contradiction rather than like the approximation it is.
string rngTxt = not live ? "-" : f_clk(dayStart) + " to " + f_clk(rngEndMs) + " " + syminfo.timezone + ", asked for " + str.tostring(rangeMinutes) + " min, " + str.tostring(rngBars) + (rngBars == 1 ? " bar" : " bars") + " covered " + str.tostring(rngBars * barMin, "0") + " min"
string boxTxt = not live ? "-" : str.tostring(rngHi, format.mintick) + " / " + str.tostring(rngLo, format.mintick) + " " + str.tostring(wPct, "0.00") + "% of the open"
string rnkTxt = not live ? "-" : na(wRank) ? "ledger holds " + str.tostring(ldgN) + " of " + str.tostring(minSessions) : "p" + str.tostring(wRank, "0") + " of " + str.tostring(ldgN) + " sessions, " + (wideNow ? "wider half" : "narrower half")
string lftTxt = not live or not readOk ? "-" : str.tostring(shLeft * 100.0, "0") + "% of " + str.tostring(grpN) + " sessions, SE " + str.tostring(f_se(shLeft, grpN), "0.0")
string bckTxt = not live or not readOk ? "-" : na(shBack) ? "none of the group left the range" : str.tostring(shBack * 100.0, "0") + "% of the " + str.tostring(grpLeftN) + " that left, SE " + str.tostring(f_se(shBack, grpLeftN), "0.0")
string endTxt = not live or not readOk ? "-" : str.tostring(shEnd * 100.0, "0") + "% of " + str.tostring(grpN) + " sessions, SE " + str.tostring(f_se(shEnd, grpN), "0.0")
string dlyTxt = not live ? "-" : (na(firstDly) ? "not yet outside today" : "today " + str.tostring(firstDly, "0") + " min after the range") + (na(medDly) ? "" : ", group median " + str.tostring(medDly, "0") + " min")
// ldgEndMs is overwritten on every commit, so it is the most recent session's
// final bar and not a property the whole ledger shares. Sessions do not all end
// at the same clock: a half day ends earlier, and if the most recent session is
// one of those, a cell claiming the ledger as a whole would be wrong about
// almost all of it. The cell claims only the session it holds the clock for.
string ldgTxt = not tfOk ? "-" : str.tostring(ldgN) + " sessions" + (na(ldgEndMs) ? "" : ", the last one read to its final bar at " + f_clk(ldgEndMs)) + (ldgSkip > 0 ? ", " + str.tostring(ldgSkip) + " with no complete range" : "")
if showTable and barstate.islast
var table t = table.new(position.top_right, 2, 9, border_width = 1)
table.cell(t, 0, 0, "Opening range", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 0, rngTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 1, "High / low / width", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 1, boxTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 2, "Width in the ledger", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 2, rnkTxt, text_color = color.white, bgcolor = color.new(grpCol, 80), text_size = size.small)
table.cell(t, 0, 3, "Left the range", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 3, lftTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 4, "Closed back inside", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 4, bckTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 5, "Finished outside", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 5, endTxt, text_color = color.white, bgcolor = color.new(grpCol, 80), text_size = size.small)
table.cell(t, 0, 6, "First outside", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 6, dlyTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 7, "Ledger", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 7, ldgTxt, text_color = color.gray, text_size = size.small)
table.cell(t, 0, 8, "Status", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 8, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)