本页源码来自 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/
// © Strikeline
//@version=6
indicator("Options Expected Move Bands [Strikeline]", shorttitle = "Expected Move [Strikeline]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_polylines_count = 20)
TZ = "America/New_York"
DAY = 86400000
G1 = "Expiration"
expMode = input.string("Weekly", "Expiration", options = ["0DTE", "Weekly", "Monthly"], group = G1, tooltip = "0DTE: today's close. Weekly: this Friday. Monthly: the third Friday of the month. All at 16:00 New York. Market holidays are not adjusted.")
srcMode = input.string("Auto", "Volatility source", options = ["Auto", "VIX family", "Historical volatility", "Manual"], group = G1, tooltip = "Auto: VIX1D / VIX9D / VIX for SPX-SPY (matched to the expiration), VXN for NDX-QQQ, RVX for RUT-IWM; historical volatility for everything else.")
hvLen = input.int(20, "Historical volatility lookback (days)", minval = 5, maxval = 252, group = G1)
manualIv = input.float(20.0, "Manual IV (%)", minval = 1, maxval = 300, step = 0.5, group = G1)
stepIn = input.string("Auto", "Strike step", options = ["Auto", "0.5", "1", "2.5", "5", "10", "25"], group = G1, tooltip = "Used to show the nearest listed strikes at the ±1σ edges.")
G2 = "Display"
showCycle = input.bool(true, "Cycle bands (fixed when the cycle starts)", group = G2)
showCone = input.bool(true, "Live cone (move left from now to expiration)", group = G2)
show2 = input.bool(true, "Show ±2σ", group = G2)
histN = input.int(4, "Previous cycles to keep", minval = 0, maxval = 20, group = G2)
upCol = input.color(#2DD4BF, "Upper", group = G2)
dnCol = input.color(#F59E5B, "Lower", group = G2)
midCol = input.color(#8A94A3, "Anchor / cone", group = G2)
showDash = input.bool(false, "Show dashboard", group = G2, tooltip = "The full table of numbers. Off by default to keep the chart clean; the reading line gives the short version.")
dashPos = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G2)
readOn = input.bool(true, "Show reading", group = G2, tooltip = "One plain-language line on the chart that says what is happening. A description of the chart, not a trade signal.")
readLang = input.string("English", "Reading language", options = ["English", "Arabic", "Spanish", "Turkish"], group = G2)
readPos = input.string("Under the legend", "Reading position", options = ["Under the legend", "Bottom left", "Bottom right", "Top right"], group = G2)
readGap = input.int(8, "Legend lines to skip", minval = 0, maxval = 20, group = G2, tooltip = "Under the legend: empty lines above the reading so it sits below the chart's indicator list. Raise it if the reading covers the legend or another reading, lower it if there is a gap.")
// ── Calendar helpers (New York 16:00 closes) ──
closeOn(int t) => timestamp(TZ, year(t, TZ), month(t, TZ), dayofmonth(t, TZ), 16, 0)
addDays(int t, int n) => closeOn(t + n * DAY)
isWeekday(int t) =>
d = dayofweek(t, TZ)
d != dayofweek.saturday and d != dayofweek.sunday
weekdaysAfter(int fromT, int toT) =>
int n = 0
int d = fromT
while d < toT
d := addDays(d, 1)
if isWeekday(d)
n += 1
n
thirdFriday(int y, int m) =>
first = timestamp(TZ, y, m, 1, 16, 0)
off = (dayofweek.friday - dayofweek(first, TZ) + 7) % 7
timestamp(TZ, y, m, 1 + off + 14, 16, 0)
tday = time_tradingday
todayClose = timestamp(TZ, year(tday, "UTC"), month(tday, "UTC"), dayofmonth(tday, "UTC"), 16, 0)
wkExp = addDays(todayClose, (dayofweek.friday - dayofweek(todayClose, TZ) + 7) % 7)
y0 = year(todayClose, TZ)
m0 = month(todayClose, TZ)
tf0 = thirdFriday(y0, m0)
moExp = todayClose <= tf0 ? tf0 : thirdFriday(m0 == 12 ? y0 + 1 : y0, m0 == 12 ? 1 : m0 + 1)
expiry = expMode == "0DTE" ? todayClose : expMode == "Weekly" ? wkExp : moExp
// ── Volatility ──
root = syminfo.root
isSpx = root == "SPY" or root == "SPX" or root == "ES" or root == "MES" or root == "SPXW" or root == "SPX500"
isNdx = root == "QQQ" or root == "NDX" or root == "NQ" or root == "MNQ"
isRut = root == "IWM" or root == "RUT" or root == "RTY" or root == "M2K"
hasFamily = isSpx or isNdx or isRut
famSym = isSpx ? (expMode == "0DTE" ? "CBOE:VIX1D" : expMode == "Weekly" ? "CBOE:VIX9D" : "CBOE:VIX") : isNdx ? "CBOE:VXN" : isRut ? "CBOE:RVX" : "CBOE:VIX"
prevDayClose = request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)
hvPrev = request.security(syminfo.tickerid, "D", ta.stdev(math.log(close / close[1]), hvLen)[1] * math.sqrt(252) * 100, lookahead = barmerge.lookahead_on)
hvNow = request.security(syminfo.tickerid, "D", ta.stdev(math.log(close / close[1]), hvLen) * math.sqrt(252) * 100)
famPrev = request.security(famSym, "D", close[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
famNow = request.security(famSym, "D", close, ignore_invalid_symbol = true)
vixPrev = request.security("CBOE:VIX", "D", close[1], lookahead = barmerge.lookahead_on)
vixNow = request.security("CBOE:VIX", "D", close)
pick(float fam, float vix, float hv) =>
famV = nz(fam, vix)
switch srcMode
"Manual" => manualIv
"Historical volatility" => hv
"VIX family" => famV
=> hasFamily ? famV : hv
famName = na(famPrev) ? "VIX" : str.replace(famSym, "CBOE:", "")
srcName = switch srcMode
"Manual" => "Manual IV"
"Historical volatility" => "HV " + str.tostring(hvLen) + "d"
"VIX family" => famName
=> hasFamily ? famName : "HV " + str.tostring(hvLen) + "d"
ivPrev = pick(famPrev, vixPrev, hvPrev)
ivNow = pick(famNow, vixNow, hvNow)
autoStep(float p) =>
r = syminfo.root
r == "SPY" or r == "QQQ" or r == "IWM" or r == "DIA" ? 1.0 : r == "SPX" or r == "SPXW" or r == "RUT" ? 5.0 : r == "NDX" ? 10.0 : p < 25 ? 0.5 : p < 100 ? 1.0 : p < 250 ? 2.5 : p < 1000 ? 5.0 : 10.0
step = stepIn == "Auto" ? autoStep(close) : str.tonumber(stepIn)
callStrike(float v) => math.ceil(v / step) * step
putStrike(float v) => math.floor(v / step) * step
lvlColor(float m) => m > 0 ? upCol : m < 0 ? dnCol : midCol
// ── Cycle bands: fixed at the first bar of each expiration cycle ──
newCycle = not na(expiry[1]) and expiry != expiry[1] and not na(prevDayClose) and not na(ivPrev)
var float cAnchor = na
var float cSig = na
var float cIv = na
var float cHigh = na
var float cLow = na
var int cExp = na
var int cDays = na
var box cBox = na
var array<line> cLines = array.new<line>()
var array<float> cMults = array.new<float>()
var array<label> cLbls = array.new<label>()
var array<box> oldBoxes = array.new<box>()
var array<line> oldLines = array.new<line>()
var array<int> oldCounts = array.new<int>()
if newCycle
if not na(cBox)
if histN > 0
box.set_bgcolor(cBox, color.new(upCol, 96))
oldBoxes.push(cBox)
for [i, l] in cLines
line.set_color(l, color.new(lvlColor(cMults.get(i)), 70))
oldLines.push(l)
oldCounts.push(cLines.size())
else
box.delete(cBox)
for l in cLines
line.delete(l)
cBox := na
cLines.clear()
cMults.clear()
for lb in cLbls
label.delete(lb)
cLbls.clear()
while oldCounts.size() > histN
box.delete(oldBoxes.shift())
n = oldCounts.shift()
if n > 0
for k = 1 to n
line.delete(oldLines.shift())
cAnchor := prevDayClose
cIv := ivPrev
cExp := expiry
cDays := 1 + weekdaysAfter(todayClose, expiry)
cSig := cAnchor * cIv / 100 * math.sqrt(cDays / 252.0)
cHigh := high
cLow := low
if showCycle
cBox := box.new(time, cAnchor + cSig, cExp, cAnchor - cSig, xloc = xloc.bar_time, border_width = 0, bgcolor = color.new(upCol, 92))
for m in array.from(-2.0, -1.0, 0.0, 1.0, 2.0)
if math.abs(m) == 2 and not show2
continue
lv = cAnchor + m * cSig
st = m == 0 ? line.style_dashed : math.abs(m) == 2 ? line.style_dotted : line.style_solid
cLines.push(line.new(time, lv, cExp, lv, xloc = xloc.bar_time, color = lvlColor(m), width = math.abs(m) == 1 ? 2 : 1, style = st))
cMults.push(m)
string txt = m == 0 ? "Anchor " + str.tostring(lv, format.mintick) : (m > 0 ? "+" : "−") + str.tostring(math.abs(m), "#") + "σ " + str.tostring(lv, format.mintick)
if m == 1
txt += " · strike " + str.tostring(callStrike(lv), "#.##")
if m == -1
txt += " · strike " + str.tostring(putStrike(lv), "#.##")
cLbls.push(label.new(cExp, lv, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = lvlColor(m), size = size.small))
else if not na(cAnchor)
cHigh := math.max(cHigh, high)
cLow := math.min(cLow, low)
// ── Live cone: the move still priced in from now until expiration ──
var array<polyline> cones = array.new<polyline>()
var label coneLbl = na
float remDays = na
float liveSig = na
if barstate.islast
for p in cones
polyline.delete(p)
cones.clear()
label.delete(coneLbl)
frac = math.max(0.0, math.min(1.0, (todayClose - timenow) / (390 * 60000.0)))
remDays := frac + weekdaysAfter(todayClose, expiry)
liveSig := close * ivNow / 100 * math.sqrt(remDays / 252.0)
if showCone and remDays > 0 and not na(ivNow)
k = close * ivNow / 100
ts = array.new<int>()
es = array.new<float>()
ts.push(time)
es.push(0.0)
if frac > 0 and todayClose > time
for j = 1 to 4
ts.push(time + int((todayClose - time) * j / 4))
es.push(frac * j / 4)
int d = todayClose
float acc = frac
while d < expiry
d := addDays(d, 1)
if isWeekday(d)
acc += 1
ts.push(d)
es.push(acc)
up1 = array.new<chart.point>()
dn1 = array.new<chart.point>()
up2 = array.new<chart.point>()
dn2 = array.new<chart.point>()
for [i, t] in ts
w = k * math.sqrt(es.get(i) / 252.0)
up1.push(chart.point.from_time(t, close + w))
dn1.push(chart.point.from_time(t, close - w))
up2.push(chart.point.from_time(t, close + 2 * w))
dn2.push(chart.point.from_time(t, close - 2 * w))
poly = up1.copy()
for i = dn1.size() - 1 to 0
poly.push(dn1.get(i))
cones.push(polyline.new(poly, closed = true, xloc = xloc.bar_time, line_color = color.new(midCol, 40), fill_color = color.new(midCol, 88), line_style = line.style_dotted))
if show2
cones.push(polyline.new(up2, xloc = xloc.bar_time, line_color = color.new(upCol, 50), line_style = line.style_dotted))
cones.push(polyline.new(dn2, xloc = xloc.bar_time, line_color = color.new(dnCol, 50), line_style = line.style_dotted))
coneLbl := label.new(expiry, close + liveSig, "Live ±1σ " + str.tostring(close - liveSig, format.mintick) + " – " + str.tostring(close + liveSig, format.mintick), xloc = xloc.bar_time, style = label.style_label_lower_left, color = color.new(color.black, 100), textcolor = midCol, size = size.small)
// ── Alerts ──
alertcondition(ta.crossover(high, cAnchor + cSig), "Above cycle +1σ", "{{ticker}} moved above the +1σ expected move (Expected Move Bands)")
alertcondition(ta.crossunder(low, cAnchor - cSig), "Below cycle −1σ", "{{ticker}} moved below the −1σ expected move (Expected Move Bands)")
alertcondition(ta.crossover(high, cAnchor + 2 * cSig), "Above cycle +2σ", "{{ticker}} moved above +2σ (Expected Move Bands)")
alertcondition(ta.crossunder(low, cAnchor - 2 * cSig), "Below cycle −2σ", "{{ticker}} moved below −2σ (Expected Move Bands)")
// ── Dashboard ──
pos = dashPos == "Top right" ? position.top_right : dashPos == "Bottom right" ? position.bottom_right : dashPos == "Top left" ? position.top_left : position.bottom_left
var table dash = table.new(pos, 2, 10, bgcolor = color.new(#0B0E11, 5), border_color = color.new(#1F2630, 0), border_width = 1)
cell(int r, string k, string v, color c) =>
table.cell(dash, 0, r, k, text_color = #8A94A3, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, r, v, text_color = c, text_size = size.small, text_halign = text.align_right)
if showDash and barstate.islast and not na(cSig)
posSig = (close - cAnchor) / cSig
usedPct = (cHigh - cLow) / (2 * cSig) * 100
left = remDays > 0 ? str.tostring(remDays, "0.0") + " trading days left" : "expired · next cycle next session"
table.cell(dash, 0, 0, "Expected Move · " + expMode, text_color = #E6EAF0, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 0, "[Strikeline]", text_color = upCol, text_size = size.small, text_halign = text.align_right)
cell(1, "Expiration", str.format_time(cExp, "EEE dd MMM", TZ) + " · " + left, #E6EAF0)
cell(2, "Volatility", srcName + " " + str.tostring(cIv, "0.0") + "% (now " + str.tostring(ivNow, "0.0") + "%)", #E6EAF0)
cell(3, "Cycle move (1σ)", "±" + str.tostring(cSig, format.mintick) + " (" + str.tostring(cSig / cAnchor * 100, "0.00") + "%) over " + str.tostring(cDays) + "d", #E6EAF0)
cell(4, "Cycle range", str.tostring(cAnchor - cSig, format.mintick) + " – " + str.tostring(cAnchor + cSig, format.mintick), #E6EAF0)
cell(5, "Strikes at ±1σ", "P " + str.tostring(putStrike(cAnchor - cSig), "#.##") + " / C " + str.tostring(callStrike(cAnchor + cSig), "#.##"), #E6EAF0)
cell(6, "Move left (1σ)", remDays > 0 ? "±" + str.tostring(liveSig, format.mintick) + " (" + str.tostring(liveSig / close * 100, "0.00") + "%)" : "—", #E6EAF0)
cell(7, "Price now", (posSig >= 0 ? "+" : "") + str.tostring(posSig, "0.00") + "σ", posSig >= 0 ? upCol : dnCol)
cell(8, "Range used", str.tostring(usedPct, "#") + "% of ±1σ", usedPct >= 100 ? dnCol : #E6EAF0)
ernT = earnings.future_time
if not na(ernT) and ernT > timenow
ern = int(ernT)
nd = weekdaysAfter(todayClose, closeOn(ern))
when = str.format_time(ern, "EEE dd MMM", TZ) + " · " + (nd == 0 ? "today" : "in " + str.tostring(nd) + "d")
if ern <= cExp
cell(9, "⚠ Earnings before expiry", when + " · real IV likely higher", dnCol)
else
cell(9, "Next earnings", when + " · after this expiry", #8A94A3)
else
table.clear(dash, 0, 9, 1, 9)
// ── Reading ──
iso(string t) => "" + t + ""
tx(string en, string ar, string es, string tr) => readLang == "Arabic" ? "" + ar : readLang == "Spanish" ? es : readLang == "Turkish" ? tr : en
embReading(float ps, float used, float days, bool ernBefore) =>
bool up = ps >= 0
float a = math.abs(ps)
string sg = up ? "+" : "−"
string u = str.tostring(math.min(used, 999), "#") + "%"
string dl = str.tostring(days, "0.0")
string l1 = str.tostring(cAnchor + (up ? 1 : -1) * cSig, format.mintick)
string l2 = str.tostring(cAnchor + (up ? 2 : -2) * cSig, format.mintick)
string rd = ""
color rc = #E6EAF0
if days <= 0
rd := tx("This cycle has expired; the next one starts next session.", "الدورة انتهت، والدورة الجاية تبدأ الجلسة القادمة.", "Este ciclo ha vencido; el siguiente empieza en la próxima sesión.", "Bu döngünün vadesi doldu; sonraki döngü bir sonraki seansta başlar.")
rc := #8A94A3
else if a >= 2
rd := tx("Beyond " + sg + "2σ for this expiration: a rare move.", "برا " + iso(sg + "2σ") + " لهالانتهاء: حركة نادرة.", "Más allá de " + sg + "2σ para este vencimiento: un movimiento raro.", "Bu vade için " + sg + "2σ ötesinde: nadir bir hareket.")
rc := #F87171
else if a >= 1
rd := tx("Outside the expected move (" + sg + "1σ) with " + dl + " days left; next edge " + sg + "2σ at " + l2 + ".", "برا الحركة المتوقعة (" + iso(sg + "1σ") + ") وباقي " + iso(dl) + " يوم؛ الحد التالي " + iso(sg + "2σ") + " عند " + iso(l2) + ".", "Fuera del movimiento esperado (" + sg + "1σ) con " + dl + " días restantes; siguiente borde " + sg + "2σ en " + l2 + ".", "Beklenen hareketin dışında (" + sg + "1σ), " + dl + " gün kaldı; sonraki sınır " + sg + "2σ: " + l2 + ".")
rc := #E8C547
else if a >= 0.8
rd := tx("Near the edge of the expected move: " + sg + "1σ at " + l1 + ", " + dl + " days left.", "قريب من حد الحركة المتوقعة: " + iso(sg + "1σ") + " عند " + iso(l1) + "، وباقي " + iso(dl) + " يوم.", "Cerca del borde del movimiento esperado: " + sg + "1σ en " + l1 + ", quedan " + dl + " días.", "Beklenen hareketin sınırına yakın: " + sg + "1σ: " + l1 + ", " + dl + " gün kaldı.")
else
rd := tx("Inside the expected move to expiration: " + u + " used, " + dl + " days left.", "داخل الحركة المتوقعة لين الانتهاء: انستهلك " + iso(u) + "، وباقي " + iso(dl) + " يوم.", "Dentro del movimiento esperado hasta el vencimiento: usado " + u + ", quedan " + dl + " días.", "Vadeye kadar beklenen hareketin içinde: " + u + " kullanıldı, " + dl + " gün kaldı.")
if ernBefore and days > 0
rd += tx(" Earnings before expiry: the real move can be bigger.", " وفيه أرباح قبل الانتهاء: الحركة الفعلية ممكن تكون أكبر.", " Resultados antes del vencimiento: el movimiento real puede ser mayor.", " Vadeden önce bilanço var: gerçek hareket daha büyük olabilir.")
[rd, rc]
eErn = earnings.future_time
eErnB = not na(eErn) and eErn > timenow and int(eErn) <= cExp
// reading line: its own small box, shown even when the dashboard is off
rpos = readPos == "Bottom left" ? position.bottom_left : readPos == "Bottom right" ? position.bottom_right : readPos == "Top right" ? position.top_right : position.top_left
rgap = readPos == "Under the legend" ? readGap : 0
var table rtab = table.new(rpos, 1, 21)
if readOn and barstate.islast and not na(cSig) and cSig > 0
[rd, rc] = embReading((close - cAnchor) / cSig, (cHigh - cLow) / (2 * cSig) * 100, remDays, eErnB)
if rgap > 0
for r = 0 to rgap - 1
table.cell(rtab, 0, r, " ", text_size = size.normal)
table.cell(rtab, 0, rgap, readLang == "Arabic" ? "" + iso("Expected Move") + " · " + rd : "Expected Move · " + rd, text_color = rc, text_size = size.normal, text_halign = text.align_left, bgcolor = color.new(#0B0E11, 10))