GC 12 Levels + Basis Dashboard V2.4

patawee_1978 · study · 264 行 · 点赞 31 · TradingView 原页

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

Pine Script

//@version=6
indicator("GC 12 Levels + Basis Dashboard V2.4", shorttitle="GC Levels + Basis", overlay=true, max_labels_count=500, max_lines_count=500)
 
// Basis = GC Futures - XAUUSD (manual input)
manualBasis = input.float(26.50, "Fixed Basis for 12 Levels (GC - XAU)", step=0.1, group="Settings")
showLabels = input.bool(true, "Show price labels", group="Settings")
textPosition = input.string("Center", "Price text position", options=["Left", "Center", "Right"], group="Settings")
textSize = input.string(size.small, "Price text size", options=[size.tiny, size.small, size.normal, size.large], group="Settings")
 
// Position within the visible chart, with a small margin at the edges.
visibleSpan = chart.right_visible_bar_time - chart.left_visible_bar_time
positionFraction = textPosition == "Left" ? 0.08 : textPosition == "Right" ? 0.92 : 0.5
textTime = chart.left_visible_bar_time + int(visibleSpan * positionFraction)
textAlign = textPosition == "Left" ? text.align_left : textPosition == "Right" ? text.align_right : text.align_center
lineWidth = input.int(2, "All lines width", minval=1, maxval=5, group="Appearance")
allColor = input.color(color.orange, "All lines and text color", group="Appearance")
 
// Divide each main interval into equal parts (10 parts = 9 minor lines).
showMinor = input.bool(true, "Show minor dashed levels", group="Minor Levels")
minorParts = input.int(10, "Parts per main interval", minval=2, maxval=40, group="Minor Levels")
minorColor = input.color(color.silver, "Minor lines and text color", group="Minor Levels")
minorWidth = input.int(1, "Minor line width", minval=1, maxval=5, group="Minor Levels")
minorTransparency = input.int(25, "Minor line transparency", minval=0, maxval=100, group="Minor Levels")
showMinorText = input.bool(true, "Show minor price text", group="Minor Levels")
minorTextMode = input.string("XAU", "Minor text format", options=["XAU", "GC", "GC | XAU"], group="Minor Levels")
 
// Level 1 is the starting price. Higher levels are calculated automatically.
gcStart = input.float(4125, "GC starting price (Level 1)", step=0.1, group="Auto Levels")
gcStep = input.float(25, "GC spacing", minval=0.01, step=0.1, group="Auto Levels")
show1 = input.bool(true, "Level 1", inline="L1", group="GC Levels")
gc1 = gcStart + 0 * gcStep
show2 = input.bool(true, "Level 2", inline="L2", group="GC Levels")
gc2 = gcStart + 1 * gcStep
show3 = input.bool(true, "Level 3", inline="L3", group="GC Levels")
gc3 = gcStart + 2 * gcStep
show4 = input.bool(true, "Level 4", inline="L4", group="GC Levels")
gc4 = gcStart + 3 * gcStep
show5 = input.bool(true, "Level 5", inline="L5", group="GC Levels")
gc5 = gcStart + 4 * gcStep
show6 = input.bool(true, "Level 6", inline="L6", group="GC Levels")
gc6 = gcStart + 5 * gcStep
show7 = input.bool(true, "Level 7", inline="L7", group="GC Levels")
gc7 = gcStart + 6 * gcStep
show8 = input.bool(true, "Level 8", inline="L8", group="GC Levels")
gc8 = gcStart + 7 * gcStep
show9 = input.bool(true, "Level 9", inline="L9", group="GC Levels")
gc9 = gcStart + 8 * gcStep
show10 = input.bool(true, "Level 10", inline="L10", group="GC Levels")
gc10 = gcStart + 9 * gcStep
show11 = input.bool(true, "Level 11", inline="L11", group="GC Levels")
gc11 = gcStart + 10 * gcStep
show12 = input.bool(true, "Level 12", inline="L12", group="GC Levels")
gc12 = gcStart + 11 * gcStep
 
 
 
// ===== Dashboard inputs =====
futSym = input.symbol("COMEX:GC1!", "Futures symbol", group="Symbols")
spotSource = input.string("Chart", "Spot price source", options=["Chart", "Selected symbol"], group="Symbols", tooltip="Chart uses the current chart broker. Use on a standard XAUUSD chart.")
spotSym = input.symbol("OANDA:XAUUSD", "Spot symbol (Selected symbol mode)", group="Symbols")
expMode = input.string("Auto: all months", "Expiry mode", options=["Auto: all months", "Auto: even months", "Manual"], group="Expiry", tooltip="Auto is only a calendar estimate excluding weekends. It does not identify the contract in GC1! or exclude exchange holidays. For contract analysis, select the actual contract and Manual expiry.")
manualExp = input.time(timestamp("29 Dec 2026 00:00 +0000"), "Manual expiry", group="Expiry")
rfRate = input.float(4.0, "Reference interest rate (% p.a.)", step=0.1, group="Analysis")
lookback = input.int(100, "Z-score / Percentile lookback", minval=20, group="Analysis")
zThresh = input.float(2.0, "Abnormal Z-score threshold", minval=0.5, step=0.5, group="Analysis")
showDashboard = input.bool(true, "Show Dashboard", group="Dashboard")
posIn = input.string("Top Right", "Dashboard position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group="Dashboard")
sizeIn = input.string("Normal", "Dashboard text size", options=["Small", "Normal", "Large"], group="Dashboard")
 
// gaps_off carries the latest available symbol value across gaps.
// This does not guarantee real-time or synchronized price feeds.
fut = request.security(futSym, timeframe.period, close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
selectedSpot = request.security(spotSym, timeframe.period, close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
spot = spotSource == "Chart" ? close : selectedSpot
 
// Third weekday counted backward from month end (calendar estimate only).
f_expiry(y, m) =>
    nm = m == 12 ? 1 : m + 1
    ny = m == 12 ? y + 1 : y
    d = timestamp("UTC", ny, nm, 1, 0, 0) - 86400000
    cnt = 0
    for i = 0 to 10
        dow = dayofweek(d, "UTC")
        if dow >= dayofweek.monday and dow <= dayofweek.friday
            cnt += 1
        if cnt == 3
            break
        d -= 86400000
    d
 
f_nextExpiry(tRef, evenOnly) =>
    y0 = year(tRef, "UTC")
    m0 = month(tRef, "UTC")
    int res = na
    for i = 0 to 12
        mm = m0 + i
        yy = y0 + int(math.floor((mm - 1) / 12))
        mon = (mm - 1) % 12 + 1
        if not evenOnly or mon % 2 == 0
            e = f_expiry(yy, mon)
            if e > tRef
                res := e
                break
    res
 
expiry = expMode == "Manual" ? manualExp : f_nextExpiry(time, expMode == "Auto: even months")
daysToExp = (expiry - time) / 86400000.0
basisAbs = fut - spot
basisPct = not na(spot) and spot != 0 ? basisAbs / spot * 100 : na
basisAnn = daysToExp >= 1 ? basisPct * 365 / daysToExp : na
carry = basisAnn - rfRate
fairAbs = daysToExp >= 1 ? spot * rfRate / 100 * daysToExp / 365 : na
richAbs = basisAbs - fairAbs
avg = ta.sma(basisPct, lookback)
sd = ta.stdev(basisPct, lookback)
z = sd > 0 ? (basisPct - avg) / sd : na
pctR = ta.percentrank(basisPct, lookback)
// Fixed level basis is independent of the live dashboard.
basis = manualBasis
 
status = "n/a"
statusCol = color.gray
if not na(basisAnn)
    if basisAnn < 0
        status := "BACKWARDATION"
        statusCol := color.red
    else if not na(z) and z > zThresh
        status := "ELEVATED"
        statusCol := color.orange
    else if not na(z) and z < -zThresh
        status := "COMPRESSED"
        statusCol := color.yellow
    else
        status := "NORMAL CONTANGO"
        statusCol := color.green
 
tblPos = switch posIn
    "Top Left" => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left" => position.bottom_left
    => position.top_right
txtSize = switch sizeIn
    "Small" => size.small
    "Large" => size.large
    => size.normal
var t = table.new(tblPos, 2, 16, bgcolor=color.new(#131722, 10), border_color=color.new(color.gray, 60), border_width=1, frame_color=color.gray, frame_width=1)
if barstate.isfirst
    table.merge_cells(t, 0, 0, 1, 0)
f_row(r, rowLabel, value, valCol) =>
    table.cell(t, 0, r, rowLabel, text_color=color.silver, text_halign=text.align_left, text_size=txtSize)
    table.cell(t, 1, r, value, text_color=valCol, text_halign=text.align_right, text_size=txtSize)
f_num(v, fmt) =>
    na(v) ? "n/a" : str.tostring(v, fmt)
 
if barstate.islast
    if showDashboard
        table.cell(t, 0, 0, "CME GOLD BASIS + 12 LEVELS", text_color=color.white, bgcolor=color.new(color.blue, 30), text_size=txtSize)
        sgn = basisAbs >= 0 ? color.teal : color.red
        f_row(1, "Futures", f_num(fut, "0.##"), color.white)
        f_row(2, "Spot", f_num(spot, "0.##"), color.white)
        f_row(3, "Basis ($)", f_num(basisAbs, "+0.##;-0.##"), sgn)
        f_row(4, "Basis (%)", f_num(basisPct, "+0.###;-0.###") + "%", sgn)
        f_row(5, "Annualized", f_num(basisAnn, "+0.##;-0.##") + "%", basisAnn >= 0 ? color.teal : color.red)
        f_row(6, "Carry vs Rate", f_num(carry, "+0.##;-0.##") + "%", carry >= 0 ? color.teal : color.red)
        f_row(7, "Fair basis ($)", f_num(fairAbs, "0.##"), color.silver)
        f_row(8, "Rich / Cheap ($)", f_num(richAbs, "+0.##;-0.##"), na(richAbs) ? color.gray : richAbs >= 0 ? color.orange : color.aqua)
        expTag = expMode == "Manual" ? " (M)" : " (est)"
        expText = na(expiry) ? "n/a" : str.format_time(expiry, "yyyy-MM-dd", "UTC") + expTag
        f_row(9, "Expiry", expText, color.white)
        f_row(10, "Days to expiry", f_num(daysToExp, "0.0"), color.white)
        zCol = na(z) ? color.gray : math.abs(z) > zThresh ? color.orange : color.white
        f_row(11, "Z-score", f_num(z, "+0.##;-0.##"), zCol)
        filled = na(pctR) ? 0 : math.min(10, int(math.round(pctR / 10)))
        pctBar = str.repeat("■", filled) + str.repeat("□", 10 - filled)
        f_row(12, "Percentile", na(pctR) ? "n/a" : pctBar + " " + f_num(pctR, "0") + "%", color.white)
        table.cell(t, 0, 13, "STATUS", text_color=color.black, bgcolor=statusCol, text_size=txtSize)
        table.cell(t, 1, 13, status, text_color=color.black, bgcolor=statusCol, text_halign=text.align_right, text_size=txtSize)
        f_row(14, "Levels Basis (Fixed)", f_num(basis, "0.00"), color.white)
        note = na(fut) or na(spot) ? "Missing price data" : spotSource == "Chart" ? "Spot: chart broker" : "Spot: selected symbol"
        f_row(15, "Source", note, na(fut) or na(spot) ? color.orange : color.silver)
    else
        table.clear(t, 0, 0, 1, 15)
 
statusId = status == "BACKWARDATION" ? 3 : status == "ELEVATED" ? 2 : status == "COMPRESSED" ? 1 : 0
statusChanged = ta.change(statusId) != 0 and not na(basisAnn)
alertcondition(statusChanged, "Basis status changed", "Gold basis status changed ({{ticker}}): check Dashboard")
alertcondition(not na(basisAnn) and basisAnn < 0 and basisAnn[1] >= 0, "Backwardation", "Gold basis is negative (Backwardation)")
alertcondition(not na(z) and z > zThresh and z[1] <= zThresh, "Basis elevated", "Gold basis Z-score crossed above threshold")
alertcondition(not na(z) and z < -zThresh and z[1] >= -zThresh, "Basis compressed", "Gold basis Z-score crossed below threshold")
 
// Draw fixed levels: only GC start, spacing and manual basis change their prices.
 
gcLevels = array.from(gc1, gc2, gc3, gc4, gc5, gc6, gc7, gc8, gc9, gc10, gc11, gc12)
enabled = array.from(show1, show2, show3, show4, show5, show6, show7, show8, show9, show10, show11, show12)
var labels = array.new<label>(12, na)
var levelLines = array.new<line>(12, na)
 
if barstate.islast
    for i = 0 to 11
        label current = array.get(labels, i)
        line currentLine = array.get(levelLines, i)
        float linePrice = array.get(gcLevels, i) - basis
        color lineColor = allColor
        if array.get(enabled, i) and not na(basis)
            if na(currentLine)
                currentLine := line.new(bar_index, linePrice, bar_index + 1, linePrice, extend=extend.both, color=lineColor, width=lineWidth)
                array.set(levelLines, i, currentLine)
            else
                line.set_xy1(currentLine, bar_index, linePrice)
                line.set_xy2(currentLine, bar_index + 1, linePrice)
                line.set_color(currentLine, lineColor)
                line.set_width(currentLine, lineWidth)
        else
            if not na(currentLine)
                line.delete(currentLine)
                array.set(levelLines, i, na)
 
        if showLabels and array.get(enabled, i) and not na(basis)
            float gcPrice = array.get(gcLevels, i)
            float xauPrice = gcPrice - basis
            color levelColor = allColor
            color textColor = levelColor
            string caption = "GC " + str.tostring(gcPrice, "0.##") + " | XAU " + str.tostring(xauPrice, "0.00")
            if na(current)
                current := label.new(textTime, xauPrice, caption, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_none, color=color.new(levelColor, 100), textcolor=textColor, size=textSize, textalign=textAlign)
                array.set(labels, i, current)
            else
                label.set_xy(current, textTime, xauPrice)
                label.set_text(current, caption)
                label.set_color(current, color.new(levelColor, 100))
                label.set_size(current, textSize)
                label.set_textalign(current, textAlign)
                label.set_textcolor(current, textColor)
        else
            if not na(current)
                label.delete(current)
                array.set(labels, i, na)
 
 
// Equal subdivisions of all 11 main intervals, using the fixed level basis.
// Bound: 11 * (40 - 1) = 429 minor objects + 12 main objects per type.
var minorLines = array.new<line>()
var minorLabels = array.new<label>()
if barstate.islast
    while array.size(minorLines) > 0
        line.delete(array.pop(minorLines))
    while array.size(minorLabels) > 0
        label.delete(array.pop(minorLabels))
    if showMinor and not na(basis)
        float minorStep = gcStep / minorParts
        for interval = 0 to 10
            float lowerGC = gcStart + interval * gcStep
            for part = 1 to minorParts - 1
                float minorGC = lowerGC + part * minorStep
                float minorXAU = minorGC - basis
                line minorLine = line.new(bar_index, minorXAU, bar_index + 1, minorXAU, extend=extend.both, style=line.style_dashed, color=color.new(minorColor, minorTransparency), width=minorWidth)
                array.push(minorLines, minorLine)
                if showMinorText
                    string minorCaption = switch minorTextMode
                        "GC" => "GC " + str.tostring(minorGC, "0.00")
                        "GC | XAU" => "GC " + str.tostring(minorGC, "0.00") + " | XAU " + str.tostring(minorXAU, "0.00")
                        => "(" + str.tostring(minorXAU, "0.00") + ")"
                    label minorLabel = label.new(textTime, minorXAU, minorCaption, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_none, textcolor=minorColor, size=textSize, textalign=textAlign)
                    array.push(minorLabels, minorLabel)

← 返回列表