本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RajeevNaik
// Sdevlog v2 — each bar's move measured in standard deviations of the move that implied volatility expects.
// IV source: India VIX (live), a VIX-scaled proxy for stocks, the symbol's own realised volatility, or a manual IV.
//@version=6
indicator('Sdevlog v2', shorttitle = 'Sdevlog')
// ============================================================
// INPUTS
// ============================================================
gI = 'Implied volatility'
ivSrc = input.string('India VIX', 'IV source', options = ['India VIX', 'VIX × stock/Nifty HV (stock proxy)', 'Realised HV20', 'Manual'], group = gI, tooltip = 'India VIX is Nifty 30-day IV. For a stock, use the proxy (VIX scaled by how much more or less volatile the stock has been than Nifty) or type the ATM IV from the option chain as Manual.', display = display.none)
vixSym = input.symbol('NSE:INDIAVIX', 'VIX symbol', group = gI, display = display.none)
niftySym = input.symbol('NSE:NIFTY', 'Nifty symbol (for the proxy)', group = gI, display = display.none)
ivManual = input.float(14.0, 'Manual ATM IV (%)', minval = 0.1, step = 0.5, group = gI, display = display.none)
hvLen = input.int(20, 'HV length', minval = 5, group = gI, display = display.none)
gS = 'Session'
days = input.int(252, 'Trading days per year', minval = 1, group = gS, display = display.none)
sessMin = input.int(375, 'Session minutes per day (NSE 09:15–15:30 = 375)', minval = 1, group = gS, display = display.none)
skipGap = input.bool(true, 'Intraday: measure first bar of the day from its open (ignore overnight gap)', group = gS, display = display.none)
gD = 'Display'
viewMode = input.string('Candles (high / low / close)', 'Show each bar as', options = ['Candles (high / low / close)', 'Columns (close only)'], group = gD, display = display.none, tooltip = 'Candles: body from 0 to the close in σ, wicks to the bar high and low in σ.')
markOn = input.string('Close', 'Spike markers on', options = ['Close', 'High / low (wicks)'], group = gD, display = display.none, tooltip = 'Close = only bars that CLOSED beyond the level. High / low = any bar that touched it during the bar.')
lvl1 = input.float(2.0, 'Level 1 (σ)', step = 0.5, group = gD, display = display.none)
lvl2 = input.float(3.0, 'Level 2 (σ)', step = 0.5, group = gD, display = display.none)
showPanel = input.bool(true, 'Show panel', group = gD, display = display.none)
l1Col = input.color(color.new(color.yellow, 0), 'Level 1 line colour', group = gD, display = display.none)
l1Width = input.int(2, 'Level 1 line width', minval = 1, maxval = 4, group = gD, display = display.none)
show1 = input.bool(true, 'Show faint ±1σ lines', group = gD, display = display.none)
// ============================================================
// BARS PER YEAR (works on any timeframe)
// ============================================================
tfMin = timeframe.in_seconds() / 60.0
barsPerYear = timeframe.isintraday ? days * sessMin / tfMin : timeframe.isdaily ? days / timeframe.multiplier : timeframe.isweekly ? 52.0 / timeframe.multiplier : 12.0 / timeframe.multiplier
// ============================================================
// IV
// ============================================================
// realised volatility of the last COMPLETED day (annualised %), so it never repaints
f_hvPrev() =>
hv = ta.stdev(math.log(close / close[1]), hvLen) * math.sqrt(252) * 100
hv[1]
vix = request.security(vixSym, timeframe.period, close)
// HVs on daily data so the ratio is the same on every chart timeframe
hvStock = request.security(syminfo.tickerid, 'D', f_hvPrev(), lookahead = barmerge.lookahead_on)
hvNifty = request.security(niftySym, 'D', f_hvPrev(), lookahead = barmerge.lookahead_on)
proxy = vix * hvStock / hvNifty
ivPct = switch ivSrc
'India VIX' => vix
'VIX × stock/Nifty HV (stock proxy)' => proxy
'Realised HV20' => hvStock
=> ivManual
iv = nz(ivPct, ivManual) / 100
// ============================================================
// MOVE IN SIGMAS
// ============================================================
sigBar = iv / math.sqrt(barsPerYear) // expected 1σ log move for one bar
newDay = timeframe.isintraday and dayofmonth(time, 'Asia/Kolkata') != dayofmonth(time[1], 'Asia/Kolkata')
base = skipGap and newDay ? open : close[1]
ret = math.log(close / base)
sdch = sigBar > 0 ? ret / sigBar : na
hiS = sigBar > 0 ? math.log(high / base) / sigBar : na // furthest up the bar reached, in σ
loS = sigBar > 0 ? math.log(low / base) / sigBar : na // furthest down the bar reached, in σ
oneSigPts = close * sigBar // 1σ move per bar, in points
daySig = close * iv / math.sqrt(days) // 1σ move per day, in points
weekSig = close * iv * math.sqrt(5.0 / days) // 1σ move per week, in points
// ============================================================
// PLOTS
// ============================================================
col = sdch >= lvl2 ? color.lime : sdch >= lvl1 ? color.new(color.lime, 30) : sdch > 0 ? color.new(color.lime, 65) : sdch <= -lvl2 ? color.red : sdch <= -lvl1 ? color.new(color.red, 30) : color.new(color.red, 65)
isCandle = viewMode == 'Candles (high / low / close)'
plot(isCandle ? na : sdch, 'Move (σ)', col, 2, plot.style_columns)
candleCol = sdch >= 0 ? color.new(color.lime, sdch >= lvl1 ? 0 : 40) : color.new(color.red, sdch <= -lvl1 ? 0 : 40)
plotcandle(isCandle ? 0.0 : na, isCandle ? hiS : na, isCandle ? loS : na, isCandle ? sdch : na, 'Bar range (σ)', candleCol, wickcolor = color.new(color.gray, 20), bordercolor = candleCol)
hline(0, 'Zero', color.new(color.gray, 50), hline.style_solid)
hline(lvl2, '+L2', color.new(color.green, 30), hline.style_dashed)
hline(-lvl2, '-L2', color.new(color.green, 30), hline.style_dashed)
// Level 1 (default 2σ): bold line right across the pane
hline(lvl1, '+L1', l1Col, hline.style_dashed, l1Width)
hline(-lvl1, '-L1', l1Col, hline.style_dashed, l1Width)
hline(1, '+1σ', show1 ? color.new(color.gray, 70) : color.new(color.gray, 100), hline.style_dotted)
hline(-1, '-1σ', show1 ? color.new(color.gray, 70) : color.new(color.gray, 100), hline.style_dotted)
// right-edge tags: level and what it means in points for one bar
var label tagUp = na
var label tagDn = na
if barstate.islast
label.delete(tagUp)
label.delete(tagDn)
pts = str.tostring(lvl1 * oneSigPts, '#')
tagUp := label.new(bar_index + 3, lvl1, '+' + str.tostring(lvl1) + 'σ (+' + pts + ' pts/bar)', style = label.style_label_left, color = color.new(color.black, 100), textcolor = l1Col, size = size.small)
tagDn := label.new(bar_index + 3, -lvl1, '-' + str.tostring(lvl1) + 'σ (-' + pts + ' pts/bar)', style = label.style_label_left, color = color.new(color.black, 100), textcolor = l1Col, size = size.small)
useWick = markOn == 'High / low (wicks)'
up2 = useWick ? hiS >= lvl2 : ta.crossover(sdch, lvl2)
dn2 = useWick ? loS <= -lvl2 : ta.crossunder(sdch, -lvl2)
up1 = (useWick ? hiS >= lvl1 : ta.crossover(sdch, lvl1)) and not up2
dn1 = (useWick ? loS <= -lvl1 : ta.crossunder(sdch, -lvl1)) and not dn2
plotshape(up2, 'Spike up L2', shape.xcross, location.top, color.white, size = size.small)
plotshape(dn2, 'Spike down L2', shape.xcross, location.bottom, color.white, size = size.small)
plotshape(up1, 'Spike up L1', shape.circle, location.top, color.blue, size = size.tiny)
plotshape(dn1, 'Spike down L1', shape.circle, location.bottom, color.blue, size = size.tiny)
// data-window values
plot(ivPct, 'IV used (%)', display = display.data_window)
plot(oneSigPts, '1σ per bar (pts)', display = display.data_window)
plot(daySig, '1σ per day (pts)', display = display.data_window)
plot(hiS, 'Bar high (σ)', display = display.data_window)
plot(loS, 'Bar low (σ)', display = display.data_window)
// ============================================================
// ALERTS
// ============================================================
alertcondition(up2, 'Spike up beyond L2', '{{ticker}} bar beyond +L2σ (IV-based)')
alertcondition(dn2, 'Spike down beyond L2', '{{ticker}} bar beyond -L2σ (IV-based)')
alertcondition(up1 or up2, 'Spike up beyond L1', '{{ticker}} bar move beyond +L1σ (IV-based)')
alertcondition(dn1 or dn2, 'Spike down beyond L1', '{{ticker}} bar move beyond -L1σ (IV-based)')
// ============================================================
// PANEL
// ============================================================
var table tb = table.new(position.top_right, 2, 6, border_width = 1, border_color = color.new(color.gray, 60))
f_row(r, k, v) =>
table.cell(tb, 0, r, k, text_color = color.white, bgcolor = color.new(color.black, 15), text_size = size.small, text_halign = text.align_left)
table.cell(tb, 1, r, v, text_color = color.white, bgcolor = color.new(color.black, 30), text_size = size.small, text_halign = text.align_right)
if showPanel and barstate.islast
srcTxt = ivSrc == 'India VIX' ? 'India VIX' : ivSrc == 'Manual' ? 'Manual' : ivSrc == 'Realised HV20' ? 'HV20' : 'VIX proxy'
f_row(0, 'IV (' + srcTxt + ')', str.tostring(ivPct, '0.00') + '%' + (na(ivPct) ? ' → manual' : ''))
f_row(1, 'This bar', str.tostring(sdch, '+0.00;-0.00') + ' σ')
f_row(2, 'This bar high / low', str.tostring(hiS, '+0.00;-0.00') + ' / ' + str.tostring(loS, '+0.00;-0.00') + ' σ')
f_row(3, '1σ per bar', str.tostring(oneSigPts, '#.##') + ' pts')
f_row(4, '1σ per day', '±' + str.tostring(daySig, '#.##') + ' pts')
f_row(5, '1σ per week', '±' + str.tostring(weekSig, '#.##') + ' pts')