Gold-Silver Ratio Monitor - Light

deltaterminal · study · 176 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
// =====================================================================
//  Gold-Silver Ratio Monitor - Light
//  Version: 1.0
//
//  The gold-silver ratio (ounces of silver per ounce of gold), with a
//  rolling mean, z-score bands, a one-year percentile and a compact
//  top-right dashboard. A context tool: it tells you how stretched the
//  ratio is versus its own recent history, and whether silver is
//  lagging or outrunning gold. It does not predict the next move.
//
//  No lookahead. Pine v6 strict.
// =====================================================================
indicator("Gold-Silver Ratio Monitor - Light", shorttitle = "GSR Monitor",
         overlay = false, precision = 2, max_labels_count = 50)
 
// =============================
//  INPUTS
// =============================
grpSrc = "Sources"
goldSym   = input.symbol("OANDA:XAUUSD", "Gold symbol", group = grpSrc,
         tooltip = "Numerator. Default: Gold spot.")
silverSym = input.symbol("OANDA:XAGUSD", "Silver symbol", group = grpSrc,
         tooltip = "Denominator. Default: Silver spot.")
useCurrentAsGold = input.bool(false, "Use current chart as gold", group = grpSrc,
         tooltip = "If true, the current chart symbol replaces the gold symbol above. Useful on futures or CFD tickers.")
tfIn = input.timeframe("", "Timeframe", group = grpSrc,
         tooltip = "Timeframe used for both symbols. Empty = chart timeframe. Daily is the classic reading.")
 
grpCalc = "Calculation"
zLen   = input.int(100, "Mean / z-score length (bars)", minval = 10, maxval = 1000, group = grpCalc,
         tooltip = "Window for the rolling mean and standard deviation of the ratio. 100 daily bars is a reasonable default; 250 is a one-year reading.")
pctLen = input.int(250, "Percentile length (bars)", minval = 20, maxval = 2000, group = grpCalc,
         tooltip = "Window for the percentile rank of the current ratio. 250 daily bars = roughly one year.")
chgLen = input.int(20, "Change lookback (bars)", minval = 1, maxval = 500, group = grpCalc,
         tooltip = "Bars used for the 'change' row of the dashboard.")
zWarn  = input.float(1.0, "Stretched threshold (z)", minval = 0.1, step = 0.1, group = grpCalc)
zThr   = input.float(2.0, "Extreme threshold (z)", minval = 0.2, step = 0.1, group = grpCalc,
         tooltip = "Absolute z-score above which the ratio is flagged as extreme versus its own recent history.")
 
grpUI = "Display"
showMean  = input.bool(true, "Show rolling mean", group = grpUI)
showBands = input.bool(true, "Show z-score bands", group = grpUI)
showBg    = input.bool(true, "Tint background at extremes", group = grpUI)
showDash  = input.bool(true, "Show dashboard", group = grpUI)
dashPos   = input.string("top_right", "Dashboard position", options = ["top_right", "top_left", "bottom_right", "bottom_left", "middle_right"], group = grpUI)
dashSize  = input.string("small", "Dashboard size", options = ["tiny", "small", "normal"], group = grpUI)
 
// =============================
//  DATA FETCH
// =============================
string tfUse = tfIn == "" ? timeframe.period : tfIn
 
goldRaw = request.security(goldSym,          tfUse, close, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
goldCur = request.security(syminfo.tickerid, tfUse, close, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
silver  = request.security(silverSym,        tfUse, close, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
 
float gold = useCurrentAsGold ? goldCur : goldRaw
 
// =============================
//  RATIO, MEAN, Z-SCORE, PERCENTILE
// =============================
bool haveData = not na(gold) and not na(silver) and silver > 0
float ratio = haveData ? gold / silver : na
 
float mean = ta.sma(ratio, zLen)
float sd   = ta.stdev(ratio, zLen)
float z    = not na(sd) and sd > 0 ? (ratio - mean) / sd : na
 
float upperBand = mean + zThr * sd
float lowerBand = mean - zThr * sd
 
float pct = ta.percentrank(ratio, pctLen)
 
float ratioPrev = ratio[chgLen]
float chgPct = not na(ratioPrev) and ratioPrev > 0 ? (ratio / ratioPrev - 1.0) * 100.0 : na
 
// =============================
//  STATE
// =============================
colUp    = #26A69A   // ratio stretched LOW: silver has outrun gold
colDown  = #EF5350   // ratio stretched HIGH: silver has lagged gold
colWarn  = #FFA726
colNeut  = #787B86
 
int state = 0
if not na(z)
    if z >= zThr
        state := 2
    else if z >= zWarn
        state := 1
    else if z <= -zThr
        state := -2
    else if z <= -zWarn
        state := -1
 
color zCol = state == 2 ? colDown : state == 1 ? colWarn : state == -2 ? colUp : state == -1 ? colWarn : colNeut
 
string readTxt = na(z) ? "Waiting for data" :
     state == 2  ? "Extreme high: silver has lagged gold" :
     state == 1  ? "Stretched high: silver lagging gold" :
     state == -2 ? "Extreme low: silver has outrun gold" :
     state == -1 ? "Stretched low: silver outrunning gold" :
                   "Normal range vs recent history"
 
string trendTxt = na(ratio) or na(mean) ? "—" : ratio > mean ? "Above mean: gold outperforming" : "Below mean: silver outperforming"
color  trendCol = na(ratio) or na(mean) ? colNeut : ratio > mean ? colDown : colUp
 
// =============================
//  PLOTS
// =============================
plot(ratio, "Gold-Silver ratio", color = zCol, linewidth = 2)
pMean = plot(showMean ? mean : na, "Rolling mean", color = color.new(color.white, 40), linewidth = 1)
pUp   = plot(showBands ? upperBand : na, "Upper band", color = color.new(colDown, 60), linewidth = 1)
pDn   = plot(showBands ? lowerBand : na, "Lower band", color = color.new(colUp, 60), linewidth = 1)
fill(pUp, pDn, color = color.new(colNeut, 92), title = "Band fill")
 
bgcolor(showBg and state == 2 ? color.new(colDown, 88) : showBg and state == -2 ? color.new(colUp, 88) : na, title = "Extreme tint")
 
// =============================
//  DASHBOARD
// =============================
f_pos(string p) =>
    p == "top_left" ? position.top_left : p == "bottom_right" ? position.bottom_right : p == "bottom_left" ? position.bottom_left : p == "middle_right" ? position.middle_right : position.top_right
 
f_size(string s) =>
    s == "tiny" ? size.tiny : s == "normal" ? size.normal : size.small
 
var table dash = table.new(position = f_pos(dashPos), columns = 2, rows = 8,
     bgcolor = color.new(color.black, 75), border_width = 1, border_color = color.new(color.gray, 70), frame_width = 1, frame_color = color.new(color.gray, 60))
 
if barstate.islast and showDash
    tsz = f_size(dashSize)
    table.clear(dash, 0, 0, 1, 7)
    table.cell(dash, 0, 0, "GSR Monitor", text_color = color.white, text_size = tsz, bgcolor = color.new(color.black, 40))
    table.cell(dash, 1, 0, str.format("n={0} · pct {1}", zLen, pctLen), text_color = color.white, text_size = tsz, bgcolor = color.new(color.black, 40))
 
    table.cell(dash, 0, 1, "Ratio", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 1, na(ratio) ? "—" : str.tostring(ratio, "0.00"), text_color = color.white, text_size = tsz)
 
    table.cell(dash, 0, 2, "Z-score", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 2, na(z) ? "—" : (z >= 0 ? "+" : "") + str.tostring(z, "0.00"), text_color = zCol, text_size = tsz)
 
    table.cell(dash, 0, 3, "Percentile", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 3, na(pct) ? "—" : str.tostring(pct, "0") + "th of last " + str.tostring(pctLen), text_color = color.white, text_size = tsz)
 
    table.cell(dash, 0, 4, "Change (" + str.tostring(chgLen) + " bars)", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 4, na(chgPct) ? "—" : (chgPct >= 0 ? "+" : "") + str.tostring(chgPct, "0.0") + "%", text_color = na(chgPct) ? colNeut : chgPct > 0 ? colDown : colUp, text_size = tsz)
 
    table.cell(dash, 0, 5, "Vs mean", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 5, trendTxt, text_color = trendCol, text_size = tsz)
 
    table.cell(dash, 0, 6, "Read", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 6, readTxt, text_color = zCol, text_size = tsz)
 
    table.cell(dash, 0, 7, "Note", text_color = color.silver, text_size = tsz)
    table.cell(dash, 1, 7, "Context, not a trigger", text_color = colNeut, text_size = tsz)
 
// =============================
//  ALERTS (transitions only)
// =============================
bool enterHigh = ta.crossover(z, zThr)
bool enterLow  = ta.crossunder(z, -zThr)
bool exitHigh  = ta.crossunder(z, zThr)
bool exitLow   = ta.crossover(z, -zThr)
bool crossMeanUp   = ta.crossover(ratio, mean)
bool crossMeanDown = ta.crossunder(ratio, mean)
 
alertcondition(enterHigh, "GSR extreme HIGH", "Gold-silver ratio z-score crossed above the extreme threshold (silver has lagged gold).")
alertcondition(enterLow,  "GSR extreme LOW",  "Gold-silver ratio z-score crossed below the negative extreme threshold (silver has outrun gold).")
alertcondition(exitHigh,  "GSR back inside from HIGH", "Gold-silver ratio z-score fell back below the extreme threshold.")
alertcondition(exitLow,   "GSR back inside from LOW",  "Gold-silver ratio z-score rose back above the negative extreme threshold.")
alertcondition(crossMeanUp,   "GSR crossed mean UP",   "Gold-silver ratio crossed above its rolling mean (gold outperforming).")
alertcondition(crossMeanDown, "GSR crossed mean DOWN", "Gold-silver ratio crossed below its rolling mean (silver outperforming).")
 
// No indicator is infallible. A stretched ratio describes the present; it does not schedule the next move.

← 返回列表