GLD/GC + SLV/SL

F3L1XtheDEV · study · 284 行 · 点赞 2 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Drawing layout adapted from QQQ/SPY + NDX/SPX Convergence.
// That layout was inspired by price converters by PtGambler.
//@version=6
indicator("GLD/GC + SLV/SL", shorttitle = "GLD/GC + SLV/SL", overlay = true, behind_chart = false, max_lines_count = 250, max_labels_count = 125, dynamic_requests = true)
// Current projected round-price grid; NOT measured options positioning.
// Metals model: timestamp-paired futures / ETF price ratios. No equity-index carry model.
// Calibration always runs on ordinary five-minute bars, including on Range/HA charts.
string TZ = "America/New_York"
string LIVE = "Live paired ratio"
string FIXED = "Previous ETF session (frozen)"
int DAY_MS = 86400000
int FEED_KEEP = 96
int FEED_SCAN = 48
string grpDisplay = "Display"
string grpGold = "Gold — GLD → GC / MGC"
string grpSilver = "Silver — SLV → SIL / SI"
string grpLabels = "Labels"
string grpCal = "Calibration"
string grpInf = "Diagnostics"
nLevels = input.int(10, "Levels above / below", minval = 1, maxval = 60, group = grpDisplay, display = display.none)
majorWidth = input.int(2, "Width: major", minval = 1, maxval = 5, inline = "width", group = grpDisplay, display = display.none)
minorWidth = input.int(1, "Minor", minval = 1, maxval = 5, inline = "width", group = grpDisplay, display = display.none)
showGLD = input.bool(true, "GLD", inline = "gld", group = grpGold, display = display.none)
colorGLD = input.color(#D9B76B, "Color", inline = "gld", group = grpGold, display = display.none)
visibilityGLD = input.int(55, "Visibility (%)", minval = 0, maxval = 100, group = grpGold, tooltip = "100 = opaque. This overrides color-picker opacity for lines; text remains opaque.", display = display.none)
stepGLD = input.float(1.0, "Level spacing ($)", minval = 0.01, inline = "gs", group = grpGold, display = display.none)
majorGLD = input.float(5.0, "Major ($)", minval = 0.01, inline = "gs", group = grpGold, display = display.none)
showSLV = input.bool(true, "SLV", inline = "slv", group = grpSilver, display = display.none)
colorSLV = input.color(#D8D8D8, "Color", inline = "slv", group = grpSilver, display = display.none)
visibilitySLV = input.int(55, "Visibility (%)", minval = 0, maxval = 100, group = grpSilver, display = display.none)
stepSLV = input.float(0.5, "Level spacing ($)", minval = 0.01, inline = "ss", group = grpSilver, display = display.none)
majorSLV = input.float(1.0, "Major ($)", minval = 0.01, inline = "ss", group = grpSilver, display = display.none)
labelMode = input.string("All", "Pane labels", options = ["All", "Major only", "None"], inline = "labels", group = grpLabels, display = display.none)
textSizeIn = input.string("Small", "Size", options = ["Tiny", "Small", "Normal", "Large"], inline = "labels", group = grpLabels, display = display.none)
labelOffset = input.int(20, "Label offset (bars)", minval = 1, maxval = 250, group = grpLabels, display = display.none)
labelGapTicks = input.int(8, "Minimum label gap (chart ticks)", minval = 0, maxval = 100000, group = grpLabels, tooltip = "Only text moves to prevent overlap; a connector points to the exact level. 0 disables packing.", display = display.none)
showMapped = input.bool(false, "Show converted futures price", group = grpLabels, display = display.none)
basisMode = input.string(LIVE, "Basis", options = [LIVE, FIXED], group = grpCal, tooltip = "Live: median of the latest paired, completed 5m futures/ETF prices during 09:30–16:00 New York. Holds its last value outside ETF hours. Levels can move when the ratio updates.\nFrozen: median of the previous ETF regular session, activated at 18:00 New York. Holds intraday; no financing extrapolation. Before the first anchor exists, uses available paired samples and reports WARMUP.", display = display.none)
smoothN = input.int(6, "Live median samples", minval = 1, maxval = 48, group = grpCal, display = display.none)
minSamples = input.int(3, "Minimum paired samples", minval = 1, maxval = 12, group = grpCal, display = display.none)
manual = input.bool(false, "Manual chart / ETF ratio", inline = "manual", group = grpCal, display = display.none)
manualRatio = input.float(1.0, "Ratio", minval = 0.000001, inline = "manual", group = grpCal, tooltip = "Projected price = ETF level × ratio. Futures only. Does not bypass the instrument/chart guards.", display = display.none)
maxAgeDays = input.int(4, "Hide automatic levels after days without a pair", minval = 1, maxval = 10, group = grpCal, display = display.none)
showInfo = input.bool(false, "Show diagnostics", group = grpInf, display = display.none)
bool onFuture = syminfo.type == "futures"
bool goldFuture = onFuture and (syminfo.root == "GC" or syminfo.root == "MGC")
bool silverFuture = onFuture and (syminfo.root == "SIL" or syminfo.root == "SI")
bool usETF = (syminfo.type == "fund" or syminfo.type == "stock") and (syminfo.prefix == "AMEX" or syminfo.prefix == "NYSEARCA")
bool onGLD = usETF and syminfo.ticker == "GLD"
bool onSLV = usETF and syminfo.ticker == "SLV"
bool familyOK = goldFuture or silverFuture or onGLD or onSLV
bool gold = goldFuture or onGLD
bool onETF = onGLD or onSLV
string etfName = gold ? "GLD" : "SLV"
string etfId = ticker.new("AMEX", etfName, session.regular, adjustment.none)
bool timedChart = chart.is_standard or chart.is_heikinashi
bool timedOK = timedChart ? timeframe.isintraday and timeframe.in_seconds() >= 60 and timeframe.in_seconds() <= 3600 : false
bool contextOK = chart.is_range or timedOK
string ownId = ticker.modify(ticker.standard(syminfo.tickerid), session = syminfo.session)
bool continuous = onFuture and str.contains(syminfo.ticker, "!")
string currentContract = syminfo.current_contract
bool contractKnown = continuous and not na(currentContract) and str.length(currentContract) > 0
string legId = contractKnown ? (str.contains(currentContract, ":") ? currentContract : syminfo.prefix + ":" + currentContract) : ownId
bool contractOK = not continuous or contractKnown
f_finite(float v) =>
    not na(v) and not na(v - v) and v - v == 0
f_forward(float raw, float a, float b) =>
    raw * a + b
f_inverse(float y, float a, float b) =>
    (y - b) / a
f_mins(int t) =>
    hour(t, TZ) * 60 + minute(t, TZ)
f_day(int t) =>
    year(t, TZ) * 10000 + month(t, TZ) * 100 + dayofmonth(t, TZ)
f_session(int t) =>
    timestamp(TZ, year(t, TZ), month(t, TZ), dayofmonth(t, TZ) + (f_mins(t) >= 1080 ? 1 : 0), 0, 0)
type Feed
    array<int> times
    array<float> prices
method put(Feed f, int t, float p) =>
    if not na(t) and f_finite(p) and p > 0 and (f.times.size() == 0 or t > f.times.last())
        f.times.push(t)
        f.prices.push(p)
        if f.times.size() > FEED_KEEP
            f.times.shift()
            f.prices.shift()
method at(Feed f, int t) =>
    int i = f.times.lastindexof(t)
    i >= 0 ? f.prices.get(i) : na
f_calibrate() =>
    // Previous bars + lookahead_on: only closed samples, consistently available
    // at the next 5m opening. No unoffset future prices are requested.
    [ft1, fp1, ft2, fp2] = request.security(legId, "5", [time[1], close[1], time[2], close[2]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
    [st1, sp1, st2, sp2] = request.security(etfId, "5", [time[1], close[1], time[2], close[2]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
    var Feed fut = Feed.new(array.new<int>(), array.new<float>())
    var Feed etf = Feed.new(array.new<int>(), array.new<float>())
    var array<float> cash = array.new<float>()
    var array<float> recent = array.new<float>()
    var int cashDay = na
    var int liveDay = na
    var int pairedToday = 0
    var int lastT = na
    var int cashT = na
    var int anchorT = na
    var float live = na
    var float anchor = na
    int sessionKey = f_session(time)
    bool newSession = not na(sessionKey[1]) and sessionKey != sessionKey[1]
    if newSession and cash.size() >= minSamples
        anchor := cash.median()
        anchorT := cashT
        cash.clear()
        cashDay := na
    fut.put(ft2, fp2)
    fut.put(ft1, fp1)
    etf.put(st2, sp2)
    etf.put(st1, sp1)
    int n = fut.times.size()
    if n > 0 and etf.times.size() > 0
        for i = math.max(0, n - FEED_SCAN) to n - 1
            int t = fut.times.get(i)
            int m = f_mins(t)
            // Pair by exchange timestamp, never by the arrival/update time.
            if (na(lastT) or t > lastT) and m >= 570 and m + 5 <= 960
                float s = etf.at(t)
                if not na(s)
                    int d = f_day(t)
                    float r = fut.prices.get(i) / s
                    if na(liveDay) or d != liveDay
                        recent.clear()
                        liveDay := d
                        pairedToday := 0
                    pairedToday += 1
                    recent.push(r)
                    if recent.size() > smoothN
                        recent.shift()
                    if pairedToday >= minSamples
                        live := recent.median()
                    // The session accumulator is date-isolated. Early closes and
                    // holidays require no synthetic calendar samples.
                    if na(cashDay) or cashDay != d
                        cash.clear()
                        cashDay := d
                    cash.push(r)
                    cashT := t
                    lastT := t
    float selected = basisMode == LIVE ? live : nz(anchor, live)
    [selected, live, anchor, lastT, anchorT, pairedToday]
[autoRatio, liveRatio, anchorRatio, lastPairT, anchorT, sampleCount] = request.security(ownId, "5", f_calibrate(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10000)
float marketClose = request.security(ownId, "5", close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float ratio = onETF ? 1.0 : manual ? manualRatio : autoRatio
int ratioT = basisMode == FIXED and not na(anchorRatio) ? anchorT : lastPairT
// Historical/Replay age is chart time; realtime age also notices a stopped feed.
int referenceT = barstate.isrealtime ? timenow : time
bool stale = not onETF and not manual and not na(ratioT) and referenceT - ratioT > maxAgeDays * DAY_MS
bool valid = familyOK and contextOK and (onETF or manual or contractOK) and f_finite(ratio) and ratio > 0 and not stale and not na(marketClose)
bool enabled = gold ? showGLD : showSLV
float spacing = gold ? stepGLD : stepSLV
float majorEvery = gold ? majorGLD : majorSLV
color hue = gold ? colorGLD : colorSLV
int visibility = gold ? visibilityGLD : visibilitySLV
textSize = switch textSizeIn
    "Tiny" => size.tiny
    "Normal" => size.normal
    "Large" => size.large
    => size.small
// One reusable object pool per source; clearing never touches the other source.
type Grid
    array<line> levels
    array<label> labels
    array<line> links
f_clear(Grid g) =>
    while g.levels.size() > 0
        line.delete(g.levels.pop())
    while g.labels.size() > 0
        label.delete(g.labels.pop())
    while g.links.size() > 0
        line.delete(g.links.pop())
f_isMajor(float raw, float interval) =>
    float k = raw / interval
    math.abs(k - math.round(k)) < 1e-6
f_render(Grid g, bool enabled, bool valid, string name, float a, float b, float stepSize, float majorEvery, color hue, int visibility, int column) =>
    if not enabled or not valid or not f_finite(a) or a <= 0 or not f_finite(b)
        f_clear(g)
    else
        int count = 2 * nLevels + 1
        if g.levels.size() != count
            f_clear(g)
            for i = 0 to count - 1
                g.levels.push(line.new(bar_index, close, bar_index + 1, close, extend = extend.both))
                // Transparent left-anchored label: text starts at labelX and is
                // centered vertically on the level, never over the latest candles.
                g.labels.push(label.new(bar_index, close, "", style = label.style_label_left))
                g.links.push(line.new(bar_index, close, bar_index, close, color = na))
        float center = math.round(f_inverse(marketClose, a, b) / stepSize) * stepSize
        int labelX = bar_index + math.min(500, math.max(1, labelOffset))
        array<int> wanted = array.new<int>()
        array<float> positions = array.new<float>()
        for i = 0 to count - 1
            float raw = center + (i - nLevels) * stepSize
            float y = f_forward(raw, a, b)
            bool major = f_isMajor(raw, majorEvery)
            line ln = g.levels.get(i)
            ln.set_xy1(bar_index, y)
            ln.set_xy2(bar_index + 1, y)
            ln.set_color(color.new(hue, 100 - visibility))
            ln.set_style(major ? line.style_solid : line.style_dashed)
            ln.set_width(major ? majorWidth : minorWidth)
            label lb = g.labels.get(i)
            lb.set_text("")
            lb.set_color(color.new(chart.bg_color, 100))
            lb.set_xy(labelX, y)
            g.links.get(i).set_color(na)
            if labelMode == "All" or labelMode == "Major only" and major
                wanted.push(i)
                positions.push(y)
        // Centered deterministic packing. No pixel/zoom API or live ATR term.
        int sizeWanted = wanted.size()
        float gap = labelGapTicks * syminfo.mintick
        if sizeWanted > 0
            int pivot = int(math.floor((sizeWanted - 1) / 2))
            if pivot < sizeWanted - 1
                for j = pivot + 1 to sizeWanted - 1
                    positions.set(j, math.max(positions.get(j), positions.get(j - 1) + gap))
            if pivot > 0
                for j = pivot - 1 to 0
                    positions.set(j, math.min(positions.get(j), positions.get(j + 1) - gap))
            for j = 0 to sizeWanted - 1
                int i = wanted.get(j)
                float raw = center + (i - nLevels) * stepSize
                float y = f_forward(raw, a, b)
                float labelY = positions.get(j)
                bool major = f_isMajor(raw, majorEvery)
                label lb = g.labels.get(i)
                lb.set_xy(labelX, labelY)
                lb.set_text(name + " " + str.tostring(raw, "#.########") + (showMapped ? "  (" + str.tostring(y, format.mintick) + ")" : ""))
                lb.set_color(color.new(chart.bg_color, 100))
                lb.set_textcolor(color.new(hue, 0))
                lb.set_size(textSize)
                lb.set_text_formatting(major ? text.format_bold : text.format_none)
                lb.set_textalign(text.align_left)
                lb.set_tooltip("Source: " + name + " " + str.tostring(raw, "#.########") + "\nExact chart level: " + str.tostring(y, "#.########") + (labelY != y ? "\nText displaced for spacing; connector ends at the exact level." : ""))
                line link = g.links.get(i)
                link.set_xy1(math.max(bar_index + 1, labelX - 3), y)
                link.set_xy2(labelX, labelY)
                link.set_color(labelY != y ? color.new(hue, 65) : na)
                link.set_style(line.style_solid)
                link.set_width(1)
var Grid metalsGrid = Grid.new(array.new<line>(), array.new<label>(), array.new<line>())
f_fmtTime(int t) =>
    na(t) ? "—" : str.format_time(t, "yyyy-MM-dd HH:mm", TZ)
f_px(float x) =>
    na(x) ? "—" : str.tostring(x, "#.########")
string status = not familyOK ? "Use GC / MGC / SIL / SI / GLD / SLV" : not contextOK ? "Use Range or standard / HA 1–60m" : onETF ? "NATIVE ETF" : manual ? "MANUAL FIXED RATIO" : not contractOK ? "NO CURRENT CONTRACT — automatic mapping disabled" : stale ? "STALE — automatic levels hidden" : not valid ? "NO DATA — waiting for synchronized ETF / futures samples" : basisMode == FIXED and na(anchorRatio) ? "WARMUP — no previous ETF-session anchor yet" : basisMode == FIXED ? "FROZEN — previous ETF-session ratio" : "LIVE PAIRED RATIO — held outside ETF hours"
var table info = na
var table health = na
if barstate.islast
    f_render(metalsGrid, enabled, valid, etfName, ratio, 0.0, spacing, majorEvery, hue, visibility, 0)
    if showInfo
        if na(info)
            info := table.new(position.bottom_right, 2, 7, border_width = 1)
        array<string> names = array.from("Mapping", "Status", "Chart / ETF ratio", "Latest pair · NY", "Anchor sample · NY", "Price leg", "Model")
        array<string> values = array.from(etfName + " → " + syminfo.ticker, status, f_px(ratio), f_fmtTime(lastPairT), f_fmtTime(anchorT), legId, "5m paired closes · ETF RTH · no carry model")
        for i = 0 to 6
            table.cell(info, 0, i, names.get(i), text_color = chart.fg_color, bgcolor = chart.bg_color, text_size = size.small)
            table.cell(info, 1, i, values.get(i), text_color = valid ? chart.fg_color : color.orange, bgcolor = chart.bg_color, text_size = size.small)
    else if not na(info)
        table.delete(info)
        info := na
    bool warmup = not onETF and not manual and basisMode == FIXED and na(anchorRatio)
    bool warning = enabled and (not valid or warmup)
    if not showInfo and warning
        if na(health)
            health := table.new(position.bottom_left, 1, 1)
        table.cell(health, 0, 0, "GLD/GC + SLV/SL: " + status, text_color = color.orange, bgcolor = chart.bg_color, text_size = size.small)
    else if not na(health)
        table.delete(health)
        health := na
// Audit values only; nothing is added to the price scale.
plot(valid ? ratio : na, "Chart / ETF ratio", display = display.data_window, precision = 10)
plot(liveRatio, "Paired live ratio", display = display.data_window, precision = 10)
plot(anchorRatio, "Previous ETF-session ratio", display = display.data_window, precision = 10)
plot(valid ? 1 : 0, "Mapping valid (1/0)", display = display.data_window)

← 返回列表