本页源码来自 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 Strike Probability Map [Strikeline]", shorttitle = "Strike Odds [Strikeline]", overlay = true, max_lines_count = 60, max_labels_count = 60)
// v0.1: the chance, priced by the options market, that price reaches each strike before expiration.
// Volatility comes from the stock's own at-the-money straddle (call + put at the strike nearest to price):
// straddle ≈ 0.8 × price × σ√T, so the straddle alone gives the move priced in until expiration.
// If there are no option prices, it falls back to the volatility index (VIX1D for SPY/SPX, VXN for QQQ/NDX,
// RVX for IWM, VIX for the rest) or the stock's 20-day historical volatility for single stocks.
// Close beyond: P(price finishes past the strike at expiration), lognormal, no drift.
// Touch: the chance price trades at the strike at least once before expiration, about twice the close-beyond chance.
// The market's pricing, not a forecast. Real moves have fatter tails. Free option data on TradingView is delayed ~15-20 minutes.
TZ = "America/New_York"
DAY = 86400000
G1 = "Contracts"
expMode = input.string("Nearest", "Expiration", options = ["Nearest", "Weekly", "Monthly"], group = G1, tooltip = "Nearest: today for SPY/QQQ/IWM/SPX (daily expirations); the next Monday, Wednesday or Friday for the big stocks with those expirations (AAPL, MSFT, NVDA, TSLA, AMZN, META, GOOGL, AVGO, AMD, MU, INTC, IBIT, XLF, SMH); this Friday for other stocks. Weekly: this Friday. Monthly: third Friday. Holidays are not adjusted.")
viewIn = input.string("Key levels", "Strikes shown", options = ["Key levels", "All strikes"], group = G1, tooltip = "Key levels: three strikes each side. Likely: about a 50% chance to touch. Stretch: about 1 in 3 to touch. Edge: the first strike with under 10% to finish in the money. All strikes: every listed strike in the range, with both numbers.")
nSide = input.int(5, "Strikes each side", minval = 2, maxval = 10, group = G1)
spanIn = input.float(2.0, "Range to cover (× expected move)", minval = 1.0, maxval = 3.0, step = 0.5, group = G1, tooltip = "The strikes shown spread over this many expected moves each side, using listed strikes.")
stepIn = input.string("Auto", "Listed strike spacing", options = ["Auto", "0.5", "1", "2.5", "5", "10", "25"], group = G1, tooltip = "Spacing of listed strikes, used to find the at-the-money straddle and to round the strikes shown.")
rootIn = input.string("", "Option root (optional)", group = G1, tooltip = "Leave empty. Auto uses the chart symbol, and SPXW for SPX.")
G2 = "Show"
showMode = input.string("Touch and close", "Numbers", options = ["Touch and close", "Touch only", "Close only"], group = G2, tooltip = "Touch: the chance price trades at the strike before expiration. Close: the chance it finishes beyond it (the option ends in the money).")
labSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G2)
callCol = input.color(#2DD4BF, "Strikes above (calls)", group = G2)
putCol = input.color(#F59E5B, "Strikes below (puts)", group = G2)
showDash = input.bool(false, "Show dashboard", group = G2, tooltip = "Where the volatility comes from and the move priced in. Off by default to keep the chart clean.")
dashPos = input.string("Bottom right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G2)
readOn = input.bool(false, "Show reading", group = G2, tooltip = "One plain-language line on the chart. A description of what options price, 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(6, "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.")
// ── Calendar ──
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
nextWeekday(int t) =>
int d = addDays(t, 1)
while not isWeekday(d)
d := addDays(d, 1)
d
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)
afterClose = timenow >= todayClose
baseClose = afterClose ? nextWeekday(todayClose) : todayClose
root = syminfo.root
dailyExp = root == "SPY" or root == "QQQ" or root == "IWM" or root == "SPX"
mwfExp = str.contains(" AAPL MSFT NVDA TSLA AMZN META GOOGL GOOG AVGO AMD MU INTC IBIT XLF SMH ", " " + root + " ")
dw0 = dayofweek(baseClose, TZ)
mwfDay = addDays(baseClose, dw0 == dayofweek.tuesday or dw0 == dayofweek.thursday ? 1 : 0)
wkExp = addDays(baseClose, (dayofweek.friday - dw0 + 7) % 7)
y0 = year(baseClose, TZ)
m0 = month(baseClose, TZ)
tf0 = thirdFriday(y0, m0)
moExp = baseClose <= tf0 ? tf0 : thirdFriday(m0 == 12 ? y0 + 1 : y0, m0 == 12 ? 1 : m0 + 1)
expiry = expMode == "Nearest" ? (dailyExp ? baseClose : mwfExp ? mwfDay : wkExp) : expMode == "Weekly" ? wkExp : moExp
// Trading minutes left until the expiration close (390 per session)
minsLeft() =>
float todayPart = afterClose ? 0.0 : math.min(390.0, math.max(0.0, (todayClose - timenow) / 60000.0))
todayPart + 390.0 * weekdaysAfter(todayClose, expiry)
// ── Strikes and option symbols (OPRA:ROOTyyMMddC123.0) ──
autoStep(float p) =>
root == "SPY" or root == "QQQ" or root == "IWM" or root == "DIA" ? 1.0 : root == "SPX" ? 5.0 : root == "NDX" ? 10.0 : p < 25 ? 0.5 : p < 100 ? 1.0 : p < 250 ? 2.5 : p < 1000 ? 5.0 : 10.0
optRoot = rootIn != "" ? rootIn : root == "SPX" ? "SPXW" : root
optSym(float strike, string side) => "OPRA:" + optRoot + str.format_time(expiry, "yyMMdd", TZ) + side + str.tostring(strike, "0.0")
// ── Volatility sources ──
RTH = ticker.modify(syminfo.tickerid, session.regular)
hv20 = request.security(RTH, "D", ta.stdev(math.log(close / close[1]), 20) * math.sqrt(252) * 100, lookahead = barmerge.lookahead_off)
isIdx = dailyExp or root == "NDX" or root == "DIA"
volSym = root == "SPY" or root == "SPX" ? (expMode == "Nearest" ? "CBOE:VIX1D" : "CBOE:VIX") : root == "QQQ" or root == "NDX" ? "CBOE:VXN" : root == "IWM" ? "CBOE:RVX" : "CBOE:VIX"
volIdx = request.security(volSym, "D", close, ignore_invalid_symbol = true)
// ATM straddle, picked once on the last historical bar (a NEW option symbol cannot be requested on realtime bars)
var float aK = na
var string sC = na
var string sP = na
atEnd = barstate.islastconfirmedhistory or barstate.islast
if atEnd and na(sC)
step = stepIn == "Auto" ? autoStep(close) : str.tonumber(stepIn)
aK := math.round(close / step) * step
sC := optSym(aK, "C")
sP := optSym(aK, "P")
float oC = na
float oP = na
if atEnd and not na(sC)
oC := request.security(sC, "D", close, ignore_invalid_symbol = true)
oP := request.security(sP, "D", close, ignore_invalid_symbol = true)
// ── Normal distribution ──
ncdf(float x) =>
z = math.abs(x) / math.sqrt(2.0)
t = 1.0 / (1.0 + 0.3275911 * z)
e = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * math.exp(-z * z)
x >= 0 ? 0.5 * (1.0 + e) : 0.5 * (1.0 - e)
// chance of finishing beyond k (above for k > s, below for k < s); sd = σ√T as a fraction
pBeyond(float s, float k, float sd) =>
z = (math.log(s / k) - 0.5 * sd * sd) / sd
k >= s ? ncdf(z) : 1.0 - ncdf(z)
pTouch(float s, float k, float sd) => math.min(1.0, 2.0 * pBeyond(s, k, sd))
// ── Expected move until expiration ──
mL = minsLeft()
yrs = mL / (390.0 * 252.0)
strad = oC + oP
sdOpt = strad > 0 ? strad / (0.8 * close) : na
ivFall = isIdx or na(hv20) ? volIdx : hv20
sdFall = ivFall / 100 * math.sqrt(yrs)
useOpt = not na(sdOpt) and sdOpt > 0
sd = useOpt ? sdOpt : sdFall
srcTxt = useOpt ? "straddle " + str.tostring(aK, "#.##") + " C+P " + str.tostring(strad, "0.00") : isIdx or na(hv20) ? str.replace(volSym, "CBOE:", "") + " " + str.tostring(volIdx, "0.0") + "%" : "20-day HV " + str.tostring(hv20, "0.0") + "%"
emPts = sd * close
pct(float p) => p >= 0.995 ? ">99%" : p < 0.01 ? "<1%" : str.tostring(p * 100, "0") + "%"
lsz = labSize == "Tiny" ? size.tiny : labSize == "Normal" ? size.normal : size.small
float kUp10 = na
float kDn10 = na
float kUp30 = na
float kDn30 = na
float kUp50 = na
float kDn50 = na
if barstate.islast and not na(sd) and sd > 0
step2 = stepIn == "Auto" ? autoStep(close) : str.tonumber(stepIn)
for j = 1 to 400
ku = math.ceil(close / step2) * step2 + (j - 1) * step2
if na(kUp50) and ku > close and pTouch(close, ku, sd) < 0.50
kUp50 := ku
if na(kUp30) and pTouch(close, ku, sd) < 0.30
kUp30 := ku
if na(kUp10) and pBeyond(close, ku, sd) < 0.10
kUp10 := ku
kd = math.floor(close / step2) * step2 - (j - 1) * step2
if na(kDn50) and kd < close and pTouch(close, kd, sd) < 0.50
kDn50 := kd
if na(kDn30) and pTouch(close, kd, sd) < 0.30
kDn30 := kd
if na(kDn10) and pBeyond(close, kd, sd) < 0.10
kDn10 := kd
if not na(kUp10) and not na(kDn10) and not na(kUp30) and not na(kDn30) and not na(kUp50) and not na(kDn50)
break
// ── Draw ──
var array<label> lbs = array.new<label>()
var array<line> lns = array.new<line>()
roleTx(int r) =>
ar = readLang == "Arabic"
r == 0 ? (ar ? "هدف" : "likely") : r == 1 ? (ar ? "بعيد" : "stretch") : (ar ? "حد" : "edge")
drawK(float k, string txt, int tr) =>
up = k > close
col = up ? callCol : putCol
lns.push(line.new(bar_index + 2, k, bar_index + 6, k, color = color.new(col, tr), width = 3))
lbs.push(label.new(bar_index + 6, k, txt, style = label.style_label_left, color = color.new(#0B0E11, 30), textcolor = color.new(col, math.min(tr, 40)), size = lsz))
keyK(float k, int role) =>
if not na(k) and k > 0
up = k > close
num = role == 2 ? pct(pBeyond(close, k, sd)) + " close" : pct(pTouch(close, k, sd)) + " touch"
drawK(k, str.tostring(k, "#.##") + (up ? "C" : "P") + " · " + roleTx(role) + " · " + num, role == 0 ? 10 : role == 1 ? 30 : 50)
if barstate.islast
for l in lbs
label.delete(l)
lbs.clear()
for l in lns
line.delete(l)
lns.clear()
if not na(sd) and sd > 0 and mL > 0
if viewIn == "Key levels"
keyK(kUp50, 0)
keyK(kUp30 == kUp50 ? na : kUp30, 1)
keyK(kUp10 == kUp30 or kUp10 == kUp50 ? na : kUp10, 2)
keyK(kDn50, 0)
keyK(kDn30 == kDn50 ? na : kDn30, 1)
keyK(kDn10 == kDn30 or kDn10 == kDn50 ? na : kDn10, 2)
else
step = stepIn == "Auto" ? autoStep(close) : str.tonumber(stepIn)
dStep = step * math.max(1, math.round(spanIn * emPts / (nSide * step)))
kAtm = math.round(close / dStep) * dStep
for i = -nSide to nSide
k = kAtm + i * dStep
if k <= 0 or math.abs(k - close) < 0.15 * dStep
continue
up = k > close
pb = pBeyond(close, k, sd)
pt = pTouch(close, k, sd)
tr = 85 - int(math.min(1.0, pt) * 75)
txt = str.tostring(k, "#.##") + (up ? "C " : "P ") + (showMode == "Close only" ? "" : "touch " + pct(pt)) + (showMode == "Touch and close" ? " · " : "") + (showMode == "Touch only" ? "" : "close " + pct(pb))
drawK(k, txt, tr)
// ── 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, 7, bgcolor = color.new(#0B0E11, 5), border_color = #1F2630, 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
table.cell(dash, 0, 0, "Strike Probability Map", text_color = #E6EAF0, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 0, "[Strikeline]", text_color = callCol, text_size = size.small, text_halign = text.align_right)
cell(1, "Expiration", str.format_time(expiry, "EEE dd MMM", TZ) + " · " + str.tostring(mL / 390.0, "0.0") + " sessions left", #E6EAF0)
cell(2, "Volatility from", na(sd) ? "no data" : srcTxt, useOpt ? #E6EAF0 : #E8C547)
cell(3, "Move priced in", na(sd) ? "—" : "±" + str.tostring(emPts, format.mintick) + " (" + str.tostring(sd * 100, "0.00") + "%)", #E6EAF0)
cell(4, "30% touch strikes", na(kUp30) ? "—" : str.tostring(kDn30, "#.##") + "P · " + str.tostring(kUp30, "#.##") + "C", #E6EAF0)
cell(5, "Under 10% to finish ITM", na(kUp10) ? "—" : "≤ " + str.tostring(kDn10, "#.##") + "P · ≥ " + str.tostring(kUp10, "#.##") + "C", #E6EAF0)
cell(6, "Data", useOpt ? "OPRA · free data delayed ~15 min" : "no option prices: index / HV estimate", #8A94A3)
// ── Reading ──
iso(string t) => "" + t + ""
tx(string en, string ar, string es, string tr) => readLang == "Arabic" ? "" + ar : readLang == "Spanish" ? es : readLang == "Turkish" ? tr : en
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
string rd = ""
color rc = #E6EAF0
if na(sd) or sd <= 0
rd := tx("No volatility data for this symbol yet.", "ما فيه بيانات تذبذب لهذا الرمز لين الحين.", "Aún no hay datos de volatilidad para este símbolo.", "Bu sembol için henüz volatilite verisi yok.")
rc := #8A94A3
else if mL <= 0
rd := tx("This expiration has ended. The next session's contracts load after a reload.", "هذا الانتهاء خلص. عقود الجلسة الجاية تطلع بعد تحديث الشارت.", "Este vencimiento terminó. Los contratos de la próxima sesión cargan al recargar.", "Bu vade bitti. Sonraki seansın kontratları yenilemeden sonra yüklenir.")
rc := #8A94A3
else
d = str.format_time(expiry, "dd MMM", TZ)
u10 = str.tostring(kUp10, "#.##")
d10 = str.tostring(kDn10, "#.##")
u30 = str.tostring(kUp30, "#.##")
d30 = str.tostring(kDn30, "#.##")
rd := tx("Options price about a 1-in-3 chance to touch " + u30 + " or " + d30 + " by " + d + ". Calls from " + u10 + " and puts from " + d10 + " have under 10% to finish in the money.", "الأوبشن يسعّر فرصة تقريباً 1 من 3 إن السعر يلمس " + iso(u30) + " أو " + iso(d30) + " قبل " + iso(d) + ". الكول من " + iso(u10) + " والبوت من " + iso(d10) + " فرصتها أقل من " + iso("10%") + " تنتهي رابحة.", "Las opciones descuentan cerca de 1 entre 3 de tocar " + u30 + " o " + d30 + " antes del " + d + ". Calls desde " + u10 + " y puts desde " + d10 + " tienen menos del 10% de terminar dentro del dinero.", "Opsiyonlar " + d + " tarihine kadar " + u30 + " veya " + d30 + " seviyesine dokunma şansını yaklaşık 3'te 1 fiyatlıyor. " + u10 + " ve üstü call'lar ile " + d10 + " ve altı put'ların para içinde bitme şansı %10'un altında.")
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("Strike Odds") + " · " + rd : "Strike Odds · " + rd, text_color = rc, text_size = size.normal, text_halign = text.align_left, bgcolor = color.new(#0B0E11, 10))