本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// IMPLIED DAILY RANGE — US CASH SESSION
// Two thin lines for the US cash session (09:30-16:00 New York):
// anchor +/- k x expected move, expected move = anchor x IV / 100 / sqrt(252).
// IV is the last daily close of a Cboe volatility index BEFORE the day
// (VIX1D, VIX9D, VIX, VXN or VXD), so the lines are known at the open and
// never repaint. Anchor: previous cash close (default) or today's cash open.
//
// A single text line at the chart edge (bottom by default) measures the lines on the loaded chart
// history: completed days, share of days whose cash close stayed inside the
// lines (normal-distribution reference 68.3 % for k = 1), share of days whose
// whole cash session (high and low) stayed inside, and actual vs expected size
// = sum |close - anchor| / (sum expected move x sqrt(2/pi)). For a correctly
// sized normal forecast that ratio is 1.0; below 1 the implied move was too big.
//
// The lines show the expected SIZE of the day, not turning points.
//
// Chart timeframes: 1D (each bar is one day; on cash indices and ETFs that is
// the cash session), or intraday timeframes that divide 30 minutes (for CFDs
// and futures, where the cash session is cut out of the 23-hour day).
//
// MIT License, see LICENSE in the repository. Not financial advice.
indicator("Implied Daily Range — US Cash Session", shorttitle = "Implied Range", overlay = true)
//---- inputs -----------------------------------------------------------
grpLine = "Lines"
srcIn = input.string("Auto", "Implied volatility", options = ["Auto", "VIX1D", "VIX9D", "VIX", "VXN", "VXD"], group = grpLine,
tooltip = "Cboe volatility index used for the expected move. Auto: VXN on Nasdaq-100 symbols, VXD on Dow symbols, VIX1D otherwise (S&P 500). VIX1D is the 1-day index, VIX9D 9 days, VIX/VXN/VXD 30 days.")
anchorIn = input.string("Previous cash close", "Anchor", options = ["Previous cash close", "Today's cash open"], group = grpLine,
tooltip = "Centre of the lines. The implied move is a close-to-close measure, so the previous cash close is the matching anchor. With the open as anchor the overnight gap is not part of the measured move.")
kMult = input.float(1.0, "Width (x expected move)", minval = 0.1, maxval = 5.0, step = 0.25, group = grpLine)
lineCol = input.color(color.new(#7E8A9A, 0), "Line color", group = grpLine)
lineW = input.int(1, "Line width", minval = 1, maxval = 4, group = grpLine)
grpStat = "Measurement (text line)"
showText = input.bool(true, "Show text line", group = grpStat)
textPos = input.string("Bottom center", "Text position", options = ["Bottom center", "Bottom left", "Bottom right", "Top center", "Top right"], group = grpStat,
tooltip = "Top left is where TradingView shows the legend and the values under the cursor, so the default is the bottom edge.")
statFrom = input.time(timestamp("2000-01-01T00:00:00"), "Count days from", group = grpStat)
statTo = input.time(timestamp("2099-12-31T00:00:00"), "Count days until", group = grpStat)
textCol = input.color(color.new(#7E8A9A, 0), "Text color", group = grpStat)
//---- constants & checks -----------------------------------------------
TZ = "America/New_York"
SESSION = "0930-1600"
SQRT252 = math.sqrt(252.0)
MEAN_ABS = math.sqrt(2.0 / math.pi) // E|Z| for a standard normal
bool isDaily = timeframe.isdaily and timeframe.multiplier == 1
bool okIntra = timeframe.isintraday and 1800 % timeframe.in_seconds() == 0
if not isDaily and not okIntra
runtime.error("Use 1D, or an intraday timeframe that divides 30 minutes (for example 1, 5, 15 or 30 minutes).")
//---- volatility source ------------------------------------------------
autoSource() =>
string t = str.upper(syminfo.ticker)
string r = str.upper(syminfo.root)
string d = str.upper(syminfo.description)
bool nas = str.contains(t, "NDX") or str.contains(t, "NAS") or str.contains(t, "US100") or str.contains(t, "USTEC") or str.contains(t, "NDQ") or t == "QQQ" or r == "NQ" or r == "MNQ" or str.contains(d, "NASDAQ 100") or str.contains(d, "NASDAQ-100")
bool dow = str.contains(t, "DJI") or str.contains(t, "US30") or str.contains(t, "WS30") or str.contains(t, "DJ30") or t == "DIA" or r == "YM" or r == "MYM" or str.contains(d, "DOW JONES")
bool spx = str.contains(t, "SPX") or str.contains(t, "US500") or str.contains(t, "SP500") or str.contains(t, "USA500") or t == "SPY" or r == "ES" or r == "MES" or str.contains(d, "S&P 500")
[nas ? "VXN" : dow ? "VXD" : "VIX1D", nas or dow or spx]
[autoSrc, autoKnown] = autoSource()
string src = srcIn == "Auto" ? autoSrc : srcIn
bool fallback = srcIn == "Auto" and not autoKnown
string ivSym = "CBOE:" + src
// Last daily close of the volatility index BEFORE the current day.
// close[1] with lookahead_on is the standard non-repainting pattern. One guard:
// if the index has no daily bar for today yet (live session before its first
// print, or a day it does not trade), the bar returned is an earlier day that
// closed before this chart bar opened, so its own close is the last known value.
// The choice is made by time, so it can never pick a close from the future.
[ivTc, ivC, ivC1] = request.security(ivSym, "D", [time_close, close, close[1]], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
bool ivToday = not na(ivTc) and ivTc > time // the index has a daily bar for this day
float ivPrev = na(ivTc) or ivTc > time ? ivC1 : ivC
//---- statistics state --------------------------------------------------
var int nDays = 0
var int nCloseIn = 0
var int nRangeIn = 0
var float sumAbs = 0.0
var float sumEm = 0.0
var int firstDay = na
//---- per-day levels ----------------------------------------------------
var float dAnchor = na // anchor of the current / last session
var float dEm = na // expected move (k = 1) of the current / last session
var float dHi = na
var float dLo = na
var float dClose = na
var int dTime = na
var bool dOpen = false // session started cleanly and is not booked yet
var bool dIvSeen = false // the volatility index traded on this day (no US holiday)
var float lastSessClose = na
bool inSess = not na(time(timeframe.period, SESSION, TZ))
int ymd = year(time, TZ) * 10000 + month(time, TZ) * 100 + dayofmonth(time, TZ)
bool newSess = inSess and (not inSess[1] or ymd != ymd[1])
int sessEnd = timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ), 16, 0)
float upper = na
float lower = na
// day to book on this bar (at most one per bar)
bool bookIt = false
float bA = na
float bEm = na
float bC = na
float bH = na
float bL = na
int bT = na
if isDaily
float a = anchorIn == "Previous cash close" ? close[1] : open
float em = a * ivPrev / 100.0 / SQRT252
dAnchor := a
dEm := em
if not na(em)
upper := a + kMult * em
lower := a - kMult * em
if barstate.isconfirmed and ivToday
bookIt := true
bA := a
bEm := em
bC := close
bH := high
bL := low
bT := time
else
// session ended without a 16:00 bar (early close, data gap): book it now
if dOpen and (newSess or not inSess)
bookIt := dIvSeen
bA := dAnchor
bEm := dEm
bC := dClose
bH := dHi
bL := dLo
bT := dTime
dOpen := false
if newSess
bool startOk = hour(time, TZ) == 9 and minute(time, TZ) == 30
float a = anchorIn == "Previous cash close" ? lastSessClose : open
dAnchor := a
dEm := a * ivPrev / 100.0 / SQRT252
dHi := high
dLo := low
dTime := time
dOpen := startOk and not na(dEm)
dIvSeen := false
if inSess
dHi := math.max(dHi, high)
dLo := math.min(dLo, low)
dClose := close
lastSessClose := close
dIvSeen := dIvSeen or ivToday
if not na(dEm)
upper := dAnchor + kMult * dEm
lower := dAnchor - kMult * dEm
// the bar that ends at 16:00 completes the day
if dOpen and time_close >= sessEnd and barstate.isconfirmed
bookIt := dIvSeen
bA := dAnchor
bEm := dEm
bC := dClose
bH := dHi
bL := dLo
bT := dTime
dOpen := false
if bookIt and bT >= statFrom and bT <= statTo and not na(bA) and not na(bEm) and bEm > 0
nDays += 1
nCloseIn += math.abs(bC - bA) <= kMult * bEm ? 1 : 0
nRangeIn += bH <= bA + kMult * bEm and bL >= bA - kMult * bEm ? 1 : 0
sumAbs += math.abs(bC - bA)
sumEm += bEm
if na(firstDay)
firstDay := bT
plot(upper, "Upper line", color = lineCol, linewidth = lineW, style = plot.style_steplinebr)
plot(lower, "Lower line", color = lineCol, linewidth = lineW, style = plot.style_steplinebr)
//---- text line (plain text, no background) ----------------------------
string tPos = switch textPos
"Bottom left" => position.bottom_left
"Bottom right" => position.bottom_right
"Top center" => position.top_center
"Top right" => position.top_right
=> position.bottom_center
var table tb = table.new(tPos, 1, 1, frame_width = 0, border_width = 0)
pct(int x, int n) =>
n > 0 ? str.tostring(100.0 * x / n, "0.0") + " %" : "n/a"
if showText and barstate.islast
string anc = anchorIn == "Previous cash close" ? "prev close" : "open"
string s = src + (fallback ? " (Auto: symbol not recognised, S&P 500 used)" : "") + " | ±" + str.tostring(kMult, "0.0#") + " EM from " + anc
if not na(dEm)
s += " | current day ±" + str.tostring(kMult * dEm, format.mintick)
if nDays > 0
string normRef = kMult == 1.0 ? " (normal 68.3 %)" : ""
s += " | " + str.tostring(nDays) + " days since " + str.format_time(firstDay, "yyyy-MM-dd", TZ)
s += " | close inside " + pct(nCloseIn, nDays) + normRef
s += " | session inside " + pct(nRangeIn, nDays)
s += " | actual/expected " + (sumEm > 0 ? str.tostring(sumAbs / (sumEm * MEAN_ABS), "0.00") : "n/a")
if nDays < 100
s += " | fewer than 100 days, not robust"
else
s += na(ivPrev) ? " | no data for " + ivSym : " | no completed day yet"
if isDaily and (syminfo.type == "cfd" or syminfo.type == "futures")
s += " | daily bar is not the cash session, use an intraday chart"
table.cell(tb, 0, 0, s, text_color = textCol, text_size = size.small)