本页源码来自 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/
// Inspired by "QQQ NDX NQ Price Converter [Pt]" and "SPY SPX ES Price Converter [Pt]" by PtGambler.
//
// QQQ/SPY live convergence
// - NQ / MNQ chart -> QQQ levels only
// - ES / MES chart -> SPY levels only
// - futures/ETF ratio calibrated on synchronized 1-minute data (independent of chart timeframe),
// smoothed, outlier/jump guarded, carry-adjusted while the ETF is not trading,
// and taken from the front contract the chart currently shows (roll-safe).
//@version=6
indicator("QQQ/SPY live convergence", shorttitle = "QQQ/SPY conv", overlay = true, max_lines_count = 500, max_labels_count = 500)
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
grpCal = "Calibration"
grpLvl = "Levels"
grpInf = "Info table"
instrIn = input.string("Auto", "Instrument", options = ["Auto", "QQQ levels", "SPY levels"], group = grpCal,
tooltip = "Auto: QQQ levels on NQ/MNQ, SPY levels on ES/MES, nothing on other symbols.\nForce a mode for CFDs (NAS100, US500, ...).")
sessIn = input.string("RTH + pre/after-market", "ETF data", options = ["RTH + pre/after-market", "RTH only"], group = grpCal,
tooltip = "RTH + pre/after-market keeps calibrating 04:00-20:00 ET (catches ex-dividend gaps in premarket).\nRTH only uses the cleanest data and holds the ratio outside 09:30-16:00 ET.")
smoothLen = input.int(10, "Smoothing (synced 1m samples)", minval = 1, maxval = 200, group = grpCal,
tooltip = "EMA length of the futures/ETF ratio, in synchronized 1-minute samples.\nPre/after-market samples get 3x lower weight. 1 = raw last minute.")
jumpPct = input.float(0.04, "Jump guard %", minval = 0.005, step = 0.005, group = grpCal,
tooltip = "A sample deviating more than this from the calibrated ratio is ignored as an outlier.\nIf 3 synced samples in a row deviate in the same direction (ex-dividend, roll), the ratio re-anchors immediately.")
carryIn = input.string("Auto (US 3M T-bill)", "Carry while ETF is closed", options = ["Auto (US 3M T-bill)", "Manual", "Off"], group = grpCal,
tooltip = "The futures/ETF ratio decays at roughly the risk-free rate. While there are no ETF prints (overnight, weekends) the held ratio is decayed by exp(-r * elapsed time).")
carryManIn = input.float(4.0, "Manual / fallback carry % p.a.", step = 0.25, group = grpCal)
stepQQQ = input.float(1.0, "QQQ step $", minval = 0.01, step = 0.5, group = grpLvl)
stepSPY = input.float(1.0, "SPY step $", minval = 0.01, step = 0.5, group = grpLvl)
majorEvery = input.float(5.0, "Major level every $", minval = 0.01, step = 1.0, group = grpLvl, tooltip = "Major levels (e.g. 750 / 755 / 760) are drawn solid and thicker with bold labels; the rest dashed.")
nLevels = input.int(10, "Levels +/-", minval = 1, maxval = 120, group = grpLvl)
lvlColor = input.color(#d8d8d8, "Color", group = grpLvl)
majorWidth = input.int(2, "Width major", minval = 1, maxval = 5, group = grpLvl, inline = "w")
minorWidth = input.int(1, "minor", minval = 1, maxval = 5, group = grpLvl, inline = "w")
labelMode = input.string("All", "Labels", options = ["All", "Major only", "None"], group = grpLvl)
labelOffset = input.int(20, "Label offset (bars)", minval = 0, maxval = 400, group = grpLvl)
textSizeIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = grpLvl)
showFutPx = input.bool(false, "Show futures price in label", group = grpLvl)
showInfo = input.bool(true, "Show info table", group = grpInf)
infoPosIn = input.string("Bottom right", "Position", options = ["Top left", "Top right", "Bottom left", "Bottom right"], group = grpInf)
// ─────────────────────────────────────────────────────────────────────────────
// Instrument detection: QQQ on NQ/MNQ, SPY on ES/MES (the other set stays hidden)
// ─────────────────────────────────────────────────────────────────────────────
string root = syminfo.root
bool rootNQ = root == "NQ" or root == "MNQ"
bool rootES = root == "ES" or root == "MES"
bool isQQQ = instrIn == "QQQ levels" or (instrIn == "Auto" and rootNQ)
bool isSPY = not isQQQ and (instrIn == "SPY levels" or (instrIn == "Auto" and rootES))
bool active = isQQQ or isSPY
string etfName = isQQQ ? "QQQ" : "SPY"
string etfSess = sessIn == "RTH only" ? session.regular : session.extended
string etfTid = isQQQ ? ticker.new("NASDAQ", "QQQ", etfSess) : ticker.new("AMEX", "SPY", etfSess)
// Calibrate against the contract the chart actually shows (NQ1! -> NQZ2026 etc.), so a roll never mixes contracts.
string cc = syminfo.current_contract
bool hasCC = not na(cc) and cc != ""
string futTid = not hasCC ? syminfo.tickerid : str.contains(cc, ":") ? cc : syminfo.prefix + ":" + cc
string futShort = not hasCC ? syminfo.ticker : str.contains(cc, ":") ? str.split(cc, ":").last() : cc
// ─────────────────────────────────────────────────────────────────────────────
// Calibration — runs inside the futures 1-minute context
// ─────────────────────────────────────────────────────────────────────────────
float alphaRth = 2.0 / (smoothLen + 1)
float alphaEth = alphaRth / 3.0
float jumpThr = jumpPct / 100.0
float MS_YEAR = 31557600000.0
// Returns [smoothed ratio, close time of last synced minute, ETF close of that minute, raw ratio of that minute, was it RTH, carry % p.a.]
f_calib(string etfId, float aRth, float aEth, float thr, string carryMode, float carryMan) =>
[eC, eT] = request.security(etfId, "1", [close, time], ignore_invalid_symbol = true, calc_bars_count = 5000)
float tbill = request.security("TVC:US03MY", "D", close, ignore_invalid_symbol = true)
float rate = carryMode == "Off" ? 0.0 : carryMode == "Manual" ? carryMan : nz(tbill, carryMan)
var float ema = na
var int lastT = na
var float lastEtf = na
var float lastRaw = na
var bool lastRth = false
var int jumpN = 0
var float jumpSum = 0.0
var float jumpSign = 0.0
// Only use minutes where both the futures and the ETF printed a bar at the same timestamp.
bool synced = not na(eC) and eC > 0 and eT == time
if synced
float r = close / eC
bool inRth = not na(time("1", "0930-1600", "America/New_York"))
float a = inRth ? aRth : aEth
if na(ema)
ema := r
else
// Carry the held ratio across the gap since the last synced minute (overnight / weekend), then compare.
ema *= math.exp(-rate / 100.0 * math.max(0, time_close - lastT) / MS_YEAR)
float dev = r / ema - 1.0
if math.abs(dev) > thr
// Outlier or a real jump (ex-dividend). Re-anchor only if it persists 3 synced minutes in one direction.
float s = math.sign(dev)
if s != jumpSign
jumpN := 0
jumpSum := 0.0
jumpSign := s
jumpN += 1
jumpSum += r
if jumpN >= 3
ema := jumpSum / jumpN
jumpN := 0
jumpSum := 0.0
jumpSign := 0.0
else
jumpN := 0
jumpSum := 0.0
jumpSign := 0.0
ema += a * (r - ema)
lastT := time_close
lastEtf := eC
lastRaw := r
lastRth := inRth
[ema, lastT, lastEtf, lastRaw, lastRth, rate]
[ratioEma, lastSyncT, etfLast, ratioRaw, lastWasRth, carryPct] = request.security(futTid, "1", f_calib(etfTid, alphaRth, alphaEth, jumpThr, carryIn, carryManIn), ignore_invalid_symbol = true, calc_bars_count = 5000)
// Carry: while the ETF does not print, decay the held ratio by the risk-free rate up to now.
float dtYears = na(lastSyncT) ? 0.0 : math.max(0, timenow - lastSyncT) / MS_YEAR
float ratio = ratioEma * math.exp(-nz(carryPct) / 100.0 * dtYears)
// ─────────────────────────────────────────────────────────────────────────────
// Levels
// ─────────────────────────────────────────────────────────────────────────────
textSize = switch textSizeIn
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
var array<line> lvlLines = array.new<line>()
var array<label> lvlLabels = array.new<label>()
var float gridCenter = na
f_clear() =>
while lvlLines.size() > 0
lvlLines.shift().delete()
while lvlLabels.size() > 0
lvlLabels.shift().delete()
f_isMajor(float p) =>
float k = p / majorEvery
math.abs(k - math.round(k)) < 1e-6
if barstate.islast
if not active or na(ratio) or ratio <= 0
f_clear()
gridCenter := na
else
float step = isQQQ ? stepQQQ : stepSPY
float center = math.round(close / ratio / step) * step
// Rebuild objects only when the grid re-centers; otherwise just move them.
if na(gridCenter) or center != gridCenter or lvlLines.size() != 2 * nLevels + 1
f_clear()
gridCenter := center
for i = 0 to 2 * nLevels
float p = center + (i - nLevels) * step
bool major = f_isMajor(p)
lvlLines.push(line.new(bar_index, p * ratio, bar_index + 1, p * ratio, xloc.bar_index, extend.both, lvlColor,
major ? line.style_solid : line.style_dashed, major ? majorWidth : minorWidth))
bool wantLbl = labelMode == "All" or (labelMode == "Major only" and major)
lvlLabels.push(wantLbl ? label.new(bar_index + labelOffset, p * ratio, "", xloc = xloc.bar_index, yloc = yloc.price,
color = color.new(chart.bg_color, 50), style = label.style_label_left, textcolor = lvlColor, size = textSize,
textalign = text.align_left, text_formatting = major ? text.format_bold : text.format_none) : na)
for i = 0 to 2 * nLevels
float p = gridCenter + (i - nLevels) * step
float y = p * ratio
line ln = lvlLines.get(i)
ln.set_xy1(bar_index, y)
ln.set_xy2(bar_index + 1, y)
label lb = lvlLabels.get(i)
if not na(lb)
lb.set_xy(bar_index + labelOffset, y)
lb.set_text(etfName + " " + str.tostring(p, "#.##") + (showFutPx ? " (" + str.tostring(y, format.mintick) + ")" : ""))
// ─────────────────────────────────────────────────────────────────────────────
// Info table
// ─────────────────────────────────────────────────────────────────────────────
f_age(int ms) =>
int m = math.floor(ms / 60000)
int d = math.floor(m / 1440)
int h = math.floor((m % 1440) / 60)
int mm = m % 60
d > 0 ? str.format("{0}d {1}h", d, h) : h > 0 ? str.format("{0}h {1}m", h, mm) : str.format("{0}m", mm)
infoPos = switch infoPosIn
"Top left" => position.top_left
"Top right" => position.top_right
"Bottom left" => position.bottom_left
=> position.bottom_right
var table info = table.new(infoPos, 2, 6, bgcolor = color.new(chart.bg_color, 15), border_width = 1)
f_row(int row, string k, string v, color vCol) =>
table.cell(info, 0, row, k, text_color = chart.fg_color, text_size = size.small, text_halign = text.align_left)
table.cell(info, 1, row, v, text_color = vCol, text_size = size.small, text_halign = text.align_right)
if barstate.islast and showInfo
table.clear(info, 0, 0, 1, 5)
if not active
f_row(0, "QQQ/SPY conv", "NQ/MNQ/ES/MES only", color.orange)
else if na(ratioEma)
f_row(0, etfName + " → " + futShort, "NO DATA", color.red)
else
int ageMs = timenow - lastSyncT
bool live = ageMs <= 3 * 60000
string status = live ? (lastWasRth ? "LIVE RTH" : "LIVE ETH") : "HOLD + carry " + f_age(ageMs)
float resid = (ratioRaw - ratioEma) * etfLast
f_row(0, etfName + " → " + futShort, status, live ? color.lime : color.orange)
f_row(1, "Ratio", str.tostring(ratio, "#.000000"), chart.fg_color)
f_row(2, etfName + " equiv.", str.tostring(close / ratio, "#.00"), chart.fg_color)
f_row(3, etfName + " last synced", str.tostring(etfLast, "#.00"), chart.fg_color)
f_row(4, "Last sample Δ (pt)", (resid >= 0 ? "+" : "") + str.tostring(resid, "#.00"), math.abs(resid) <= syminfo.mintick * 2 ? color.lime : chart.fg_color)
f_row(5, "Carry", carryIn == "Off" ? "off" : str.tostring(carryPct, "#.00") + " % p.a.", chart.fg_color)