Options Vision

OptionsVisionPro · study · 324 行 · 点赞 35 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// Options Vision — intraday option HOD-breakout signals on TradingView's own data (OPRA option prices),
// with VWAP, EMAs and key levels. No outside data: everything is computed live in the script.
indicator("Options Vision", shorttitle = "OptVision", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
G1 = "On the price chart"
iVwap = input.bool(true, "VWAP", group = G1)
iEma9 = input.bool(true, "EMA 9", group = G1)
iEma20 = input.bool(false, "EMA 20", group = G1)
iLevels = input.bool(true, "Levels — PDC, PDH / PDL, premarket, HOD", group = G1)
G3 = "Live HOD signals (TradingView option prices, 1-minute chart)"
iLive = input.bool(true, "Live HOD signals", group = G3)
iHodN = input.int(2, "Signal on HOD break #", minval = 1, group = G3)
iWin = input.session("0935-1600", "Entry window (ET)", group = G3)
iGate = input.bool(true, "SPY gate (calls only above SPY's running average, puts only below)", group = G3)
iDays = input.int(5, "Days of live signals", minval = 1, maxval = 5, group = G3)
G4 = "Option flow bubbles (TradingView option volume, 1-minute chart)"
iBub = input.bool(true, "Flow bubbles (latest session)", group = G4)
iBubMin = input.float(100000, "Bubble when a strike trades ≥ $ in one minute", minval = 10000, step = 25000, group = G4)
iBubX = input.float(4, "…and ≥ this × the session's average strike-minute (0 = off)", minval = 0, step = 0.5, group = G4,
     tooltip = "Scales the bar to each stock: SPY / QQQ same-day options trade $100K+ almost every minute")
 
C_UP = #33d69f
C_DOWN = #ff6b7a
C_VIOLET = #b48cff
C_BLUE = #5aa9ff
C_GOLD = #f0c35a
C_SLATE = #94a3b8
C_TEXT = #8290a3
DEEP_ITM_PCT = 3.0
NY = "America/New_York"
 
// ---------------------------------------------------------------- VWAP / EMA (RTH, typical price, per day)
rth = not na(time(timeframe.period, "0930-1600", NY))
newDay = dayofmonth(time, NY) != dayofmonth(time[1], NY)
var float pv = 0.0
var float vv = 0.0
if newDay
    pv := 0.0
    vv := 0.0
if rth
    pv += hlc3 * volume
    vv += volume
vwap = rth and vv > 0 ? pv / vv : na
plot(iVwap ? vwap : na, "VWAP", C_VIOLET, 2, plot.style_linebr)
plot(iEma9 ? ta.ema(close, 9) : na, "EMA 9", C_BLUE, 1)
plot(iEma20 ? ta.ema(close, 20) : na, "EMA 20", C_GOLD, 1)
 
// ---------------------------------------------------------------- levels
regT = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
extT = ticker.new(syminfo.prefix, syminfo.ticker, session.extended)
[pdc, pdh, pdl] = request.security(regT, "D", [close[1], high[1], low[1]], lookahead = barmerge.lookahead_on)
hod = request.security(regT, "D", high, lookahead = barmerge.lookahead_on)
f_pm() =>
    var float h = na
    var float l = na
    if dayofmonth(time, "America/New_York") != dayofmonth(time[1], "America/New_York")
        h := na
        l := na
    if not na(time("1", "0400-0930", "America/New_York"))
        h := na(h) ? high : math.max(h, high)
        l := na(l) ? low : math.min(l, low)
    [h, l]
[pmh, pml] = request.security(extT, "1", f_pm())
 
var edgeLabels = array.new<label>()
// a price-line title: Pine can't pin text to the chart's right edge (no pixel positions, and box text
// stays in the unextended box), so the tag starts just right of the last candle, in the right margin; the value
// itself is on the price axis (plots with display.price_scale at the end)
edgeTag(float price, string txt, color col) =>
    edgeLabels.push(label.new(bar_index + 2, price, txt, style = label.style_label_left, color = color(na), textcolor = col, size = size.small))
var lvLines = array.new<line>()
// candle range on screen: levels outside it are skipped, so they never stretch the price scale and squash the
// candles (on CHARTS, price lines don't move the scale either)
var float vHi = na
var float vLo = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
    vHi := na(vHi) ? high : math.max(vHi, high)
    vLo := na(vLo) ? low : math.min(vLo, low)
lvAdd(float price, string title, color col, string style) =>
    if not na(price) and price <= vHi + (vHi - vLo) * 0.03 and price >= vLo - (vHi - vLo) * 0.03
        lvLines.push(line.new(bar_index - 1, price, bar_index, price, extend = extend.both, color = col, width = 1, style = style))
        edgeTag(price, title, col)
 
// ---------------------------------------------------------------- live option HOD signals (TradingView option prices)
// Each day: ATM call + put struck at the 09:30 open (grid $1 SPY/QQQ, $2.50 under $500, else $5), this
// week's Friday expiry. A break = a minute close at a new premium high after a minute that was not a high;
// break #N inside the entry window fires the signal (once per side per day). SPY gate: calls only while
// SPY's last minute close >= its average close since 09:30, puts only below. Uses option TRADE prices
// (TradingView has no option bid / ask for scripts), so a break needs a printed trade.
strikeStep(float p) =>
    syminfo.ticker == "SPY" or syminfo.ticker == "QQQ" ? 1.0 : p < 500 ? 2.5 : 5.0
optTicker(int expT, string right, float k) =>
    y = year(expT, "America/New_York") % 100
    m = month(expT, "America/New_York")
    d = dayofmonth(expT, "America/New_York")
    "OPRA:" + syminfo.ticker + (y < 10 ? "0" : "") + str.tostring(y) + (m < 10 ? "0" : "") + str.tostring(m) + (d < 10 ? "0" : "") + str.tostring(d) + right + str.tostring(k, "0.0##")
liveOn = iLive and timeframe.period == "1" and time >= timenow - iDays * 86400000 * 7 / 5
var string callSym = ""
var string putSym = ""
var string callLab = ""
var string putLab = ""
var string expLab = ""
if liveOn and rth and (newDay or not rth[1])
    st = strikeStep(open)
    k = math.round(open / st) * st
    dow = dayofweek(time, NY)
    expT = time + (6 - dow) * 86400000
    callSym := optTicker(expT, "C", k)
    putSym := optTicker(expT, "P", k)
    callLab := str.tostring(k) + "C"
    expLab := str.format_time(expT, "EEE MM/dd", NY)
    putLab := str.tostring(k) + "P"
cRaw = request.security(callSym == "" ? syminfo.tickerid : callSym, "1", close, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
pRaw = request.security(putSym == "" ? syminfo.tickerid : putSym, "1", close, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
// until the first open sets the symbols the requests return the stock itself; an ATM weekly is far below spot
cPx = callSym != "" and cRaw < close * 0.5 ? cRaw : na
pPx = putSym != "" and pRaw < close * 0.5 ? pRaw : na
f_spyGate() =>
    var float sum = 0.0
    var int n = 0
    if dayofmonth(time, "America/New_York") != dayofmonth(time[1], "America/New_York")
        sum := 0.0
        n := 0
    if not na(time("1", "0930-1600", "America/New_York"))
        sum += close
        n += 1
    n > 0 ? (close >= sum / n ? 1 : -1) : 0
spyDir = request.security("AMEX:SPY", "1", f_spyGate())
// one fired signal; its label is redrawn on the last bar so it sits above the other labels and
// stays clickable, and its tooltip tracks the option from the signal to now (or that day's close)
type HodSig
    int bt
    bool isCall
    string txt
    string sym
    string strike
    string exp
    int t
    float entry
    float prevHigh
    float spot
    int gate
    float last
    float best
    int bestT
    float worst
    int worstT
    label lbl
type HodBook
    float hod = na
    float prevHod = na
    bool prevHigh = true
    int breaks = 0
    bool fired = false
    HodSig sig = na
var cBook = HodBook.new()
var pBook = HodBook.new()
var hodSigs = array.new<HodSig>()
if newDay or (rth and not rth[1])
    cBook := HodBook.new()
    pBook := HodBook.new()
// returns the break count when this minute completes a break, else 0
bookStep(HodBook b, float px) =>
    int out = 0
    if not na(px)
        first = na(b.hod)
        isHigh = first or px > b.hod
        if isHigh
            b.prevHod := b.hod
            b.hod := px
        if not first and isHigh and not b.prevHigh
            b.breaks += 1
            out := b.breaks
        b.prevHigh := isHigh
    out
f2(float x) => na(x) ? "–" : str.tostring(x, "0.00")
pct(float x, float e) => na(x) or na(e) or e == 0 ? "" : (x >= e ? "+" : "") + str.tostring((x / e - 1) * 100, "0.0") + "%"
hm(int t) => str.format_time(t, "HH:mm", NY)
hodTip(HodSig s) =>
    (s.isCall ? "▲ CALL" : "▼ PUT") + " signal · premium HOD break #" + str.tostring(iHodN) + "\n" +
     syminfo.ticker + " " + s.strike + " · expires " + s.exp + " · " + s.sym + "\n" +
     "Fired " + hm(s.t) + " ET at premium " + f2(s.entry) + " (prior high " + f2(s.prevHigh) + ")\n" +
     syminfo.ticker + " " + f2(s.spot) + " · SPY " + (s.gate >= 0 ? "above" : "below") + " its average since 09:30\n" +
     "Now " + f2(s.last) + " (" + pct(s.last, s.entry) + ")\n" +
     "Best " + f2(s.best) + " (" + pct(s.best, s.entry) + ") at " + hm(s.bestT) + " · worst " + f2(s.worst) + " (" + pct(s.worst, s.entry) + ") at " + hm(s.worstT) + "\n" +
     "Option last-trade prices (TradingView OPRA feed; delayed unless you have real-time OPRA data)"
hodFire(bool isCall, string strike, string sym, float px, float prevHod) =>
    txt = (isCall ? "▲ " : "▼ ") + strike + " HOD#" + str.tostring(iHodN)
    HodSig.new(time, isCall, txt, sym, strike, expLab, time_close, px, prevHod, close, spyDir, px, px, time_close, px, time_close,
         label.new(bar_index, isCall ? low : high, txt, yloc = isCall ? yloc.belowbar : yloc.abovebar, style = isCall ? label.style_label_up : label.style_label_down,
             color = color.new(isCall ? C_UP : C_DOWN, 10), textcolor = #080b12, size = size.small))
hodTrack(HodSig s, float px) =>
    if not na(s) and not na(px)
        s.last := px
        if px > s.best
            s.best := px
            s.bestT := time_close
        if px < s.worst
            s.worst := px
            s.worstT := time_close
        label.set_tooltip(s.lbl, hodTip(s))
inWin = not na(time(timeframe.period, iWin, NY))
// minute closes only: mid-minute ticks never fire or move a signal
if liveOn and rth and callSym != "" and barstate.isconfirmed
    if not na(cBook.sig)
        hodTrack(cBook.sig, cPx)
    if not na(pBook.sig)
        hodTrack(pBook.sig, pPx)
    cb = bookStep(cBook, cPx)
    pb = bookStep(pBook, pPx)
    if cb == iHodN and inWin and not cBook.fired and (not iGate or spyDir >= 0)
        cBook.fired := true
        cBook.sig := hodFire(true, callLab, callSym, cPx, cBook.prevHod)
        label.set_tooltip(cBook.sig.lbl, hodTip(cBook.sig))
        hodSigs.push(cBook.sig)
    if pb == iHodN and inWin and not pBook.fired and (not iGate or spyDir < 0)
        pBook.fired := true
        pBook.sig := hodFire(false, putLab, putSym, pPx, pBook.prevHod)
        label.set_tooltip(pBook.sig.lbl, hodTip(pBook.sig))
        hodSigs.push(pBook.sig)
if barstate.islast
    for sg in hodSigs
        lbl = sg.lbl
        sg.lbl := label.new(sg.bt, label.get_y(lbl), sg.txt, xloc = xloc.bar_time, yloc = sg.isCall ? yloc.belowbar : yloc.abovebar,
             style = sg.isCall ? label.style_label_up : label.style_label_down, color = color.new(sg.isCall ? C_UP : C_DOWN, 10),
             textcolor = #080b12, size = size.small, tooltip = hodTip(sg))
        label.delete(lbl)
 
// ---------------------------------------------------------------- option flow bubbles (TradingView option volume)
// Each minute of the latest session: premium traded (volume × last price × 100) on the 5 strikes around the
// money, calls and puts, nearest expiry (SPY / QQQ same day, others this week's Friday). Strike-minutes at or
// above the threshold are summed per side: calls below the bar, puts above. TradingView gives no trade side, so
// a bubble can't say bought vs sold, and one minute's total can be several smaller trades. The strike window is
// set at the open and re-centred once if price leaves it (each contract is one of the script's 40 data requests).
money(float v) =>
    v >= 1e6 ? "$" + str.tostring(v / 1e6, v >= 1e7 ? "#" : "0.0") + "M" : "$" + str.tostring(math.round(v / 1e3)) + "K"
bubOn = iBub and timeframe.period == "1"
lastDay = dayofmonth(time, NY) == dayofmonth(last_bar_time, NY) and time > last_bar_time - 86400000
var float bk0 = na
var int bAnch = 0
var int bExpT = 0
var float bSum = 0.0
var int bCnt = 0
if newDay
    bk0 := na
    bAnch := 0
    bSum := 0.0
    bCnt := 0
bst = strikeStep(close)
if bubOn and rth and lastDay
    if na(bk0) or (bAnch < 2 and math.abs(close - bk0) > 2.5 * bst)
        bk0 := math.round(close / bst) * bst
        bAnch += 1
        bExpT := syminfo.ticker == "SPY" or syminfo.ticker == "QQQ" ? time : time + (6 - dayofweek(time, NY)) * 86400000
var bubIds = array.new<label>()
var bubPrem = array.new<float>()
float bC = 0.0
float bP = 0.0
string bTipC = ""
string bTipP = ""
// threshold: the $ floor, or a multiple of this session's average strike-minute so far, whichever is higher
bThr = math.max(iBubMin, bCnt > 0 ? iBubX * bSum / bCnt : 0)
if bubOn and rth and lastDay and not na(bk0)
    for i = -2 to 2
        k = bk0 + i * bst
        [cc, cv] = request.security(optTicker(bExpT, "C", k), "1", [close, volume], gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
        [pc, pv2] = request.security(optTicker(bExpT, "P", k), "1", [close, volume], gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
        if barstate.isconfirmed and not na(cc) and not na(cv) and cv > 0
            bSum += cc * cv * 100
            bCnt += 1
        if barstate.isconfirmed and not na(pc) and not na(pv2) and pv2 > 0
            bSum += pc * pv2 * 100
            bCnt += 1
        if not na(cc) and not na(cv) and cc * cv * 100 >= bThr
            bC += cc * cv * 100
            bTipC += "\n" + str.tostring(k) + "C  " + money(cc * cv * 100) + "  (" + str.tostring(cv, "#") + " × " + str.tostring(cc, "0.00") + ")"
        if not na(pc) and not na(pv2) and pc * pv2 * 100 >= bThr
            bP += pc * pv2 * 100
            bTipP += "\n" + str.tostring(k) + "P  " + money(pc * pv2 * 100) + "  (" + str.tostring(pv2, "#") + " × " + str.tostring(pc, "0.00") + ")"
bubSize(float v) =>
    z = 0.5 + math.log10(v / bThr + 1) * 1.3
    z < 1.2 ? size.tiny : z < 1.8 ? size.small : size.normal
if barstate.isconfirmed and bC > 0
    bubIds.push(label.new(bar_index, low, "", yloc = yloc.belowbar, style = label.style_circle, color = color.new(C_UP, 35), textcolor = C_UP,
         size = bubSize(bC), tooltip = "CALLS " + money(bC) + " traded at " + hm(time_close) + " ET" + bTipC + "\nTradingView option volume; trade side unknown"))
    bubPrem.push(bC)
if barstate.isconfirmed and bP > 0
    bubIds.push(label.new(bar_index, high, "", yloc = yloc.abovebar, style = label.style_circle, color = color.new(C_DOWN, 35), textcolor = C_DOWN,
         size = bubSize(bP), tooltip = "PUTS " + money(bP) + " traded at " + hm(time_close) + " ET" + bTipP + "\nTradingView option volume; trade side unknown"))
    bubPrem.push(-bP)
// the 5 biggest bubbles carry their $ amount
if barstate.islast and bubPrem.size() > 0
    srt = bubPrem.copy()
    for i = 0 to srt.size() - 1
        srt.set(i, math.abs(srt.get(i)))
    srt.sort(order.descending)
    big = srt.get(math.min(4, srt.size() - 1))
    for i = 0 to bubIds.size() - 1
        p = bubPrem.get(i)
        bubIds.get(i).set_text(math.abs(p) >= big ? money(math.abs(p)) + (p > 0 ? " C" : " P") : "")
 
// ---------------------------------------------------------------- last bar: levels, timeframe note
var float axHod = na
var table note = table.new(position.top_left, 1, 1)
if barstate.islast
    for l in edgeLabels
        l.delete()
    edgeLabels.clear()
    for l in lvLines
        l.delete()
    lvLines.clear()
    if iLevels
        lvAdd(pdc, "PDC", C_SLATE, line.style_dashed)
        lvAdd(pdh, "PDH", #64748b, line.style_dashed)
        lvAdd(pdl, "PDL", #64748b, line.style_dashed)
        lvAdd(pmh, "PMH", #7c6aa8, line.style_dotted)
        lvAdd(pml, "PML", #7c6aa8, line.style_dotted)
        lvAdd(hod, "HOD", C_GOLD, line.style_solid)
        axHod := hod
    note.clear(0, 0, 0, 0)
    if iLive and timeframe.period != "1"
        note.cell(0, 0, "Option HOD signals run on the 1-minute chart", text_color = C_TEXT, text_size = size.small)
plot(barstate.islast and iLevels ? axHod : na, "HOD", C_GOLD, display = display.price_scale)

← 返回列表