Risk-Off Ladder [Simple]

TheSimplePortfolio · study · 170 行 · 点赞 28 · 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/
// © oridahari
// Risk-Off Ladder (v2 of the Greed Fear Ladder draft): stay 100% invested while the market is healthy, step aside only when
// the risk check says so, and come back fast after a panic.
//   - Risk check (from the free Trend Safety Switch): three warnings - CBOE VIX in the top 20% of its past year, close below
//     the 200-day average, close more than 15% under the one-year high. 2 warnings = risk-off, 3 = full danger.
//   - SuperTrend (10, 3) is used only inside risk-off, as the rebound trigger. SuperTrend is Olivier Seban's classic ATR
//     indicator; the band and flip code is based on "SuperTrend" by KivancOzbilgic (open-source, 2020), who credits everget.
//   - The fear / greed reading in the Now box is the free Market Fear Meter gauge (Williams VIX Fix by Larry Williams; the
//     spike code is based on ChrisMoody's CM_Williams_Vix_Fix). It is shown for context only and does not change the ladder.
// Rules (fixed round numbers): 0-1 warnings = 100%. 2 warnings = 0%, or 70% while the SuperTrend is up (rebound).
// 3 warnings = 0%. Moves to 0% and buys from 0% happen at once; any other change waits at least 10 bars after the last one.
// No repainting: chart-timeframe data only, the VIX is read on the same timeframe without lookahead, and every decision is
// made at the bar close.
//@version=6
indicator("Risk-Off Ladder [Simple]", shorttitle = "Risk-Off Ladder", overlay = false, precision = 0, max_labels_count = 500)
 
// ───────── Inputs (display and data only; the ladder rules are fixed) ─────────
grpD    = "Display"
showLbl = input.bool(true, "Show BUY / SELL labels on the price chart", group = grpD)
showWhy = input.bool(true, "Show the reason under each label", group = grpD)
showNow = input.bool(true, "Show the Now readout", group = grpD)
showTbl = input.bool(true, "Show the results table", group = grpD)
startT  = input.time(timestamp("2000-01-01T00:00:00"), "Results table start", group = grpD)
grpV    = "Data"
useVix  = input.bool(true, "Use the CBOE VIX warning (US index / ETF charts)", group = grpV, tooltip = "Turn off for markets the US VIX does not describe. Risk-off then needs both other warnings.")
vixSym  = input.symbol("CBOE:VIX", "VIX symbol", group = grpV)
 
// ───────── Fixed rules ─────────
COOL = 10
 
// ───────── Risk check (Trend Safety Switch warnings) ─────────
ma200    = ta.sma(close, 200)
hi252    = ta.highest(high, 252)
ddPct    = (close / hi252 - 1) * 100
vixClose = request.security(vixSym, timeframe.period, close)   // same timeframe as the chart, no lookahead
vixPct   = ta.percentrank(vixClose, 252)
w1 = useVix and not na(vixPct) and vixPct >= 80 ? 1 : 0
w2 = close < ma200 ? 1 : 0
w3 = ddPct < -15 ? 1 : 0
warnings = w1 + w2 + w3
riskOff  = not na(ma200) and warnings >= 2
 
// ───────── SuperTrend (10, 3): the rebound trigger inside risk-off ─────────
atr  = ta.atr(10)
up   = hl2 - 3.0 * atr
up1  = nz(up[1], up)
up  := close[1] > up1 ? math.max(up, up1) : up
dn   = hl2 + 3.0 * atr
dn1  = nz(dn[1], dn)
dn  := close[1] < dn1 ? math.min(dn, dn1) : dn
var int trend = 1
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
 
// ───────── Market Fear Meter gauge (context only) ─────────
hiClose  = ta.highest(close, 22)
wvf      = (hiClose - low) / hiClose * 100
fearRank = ta.percentrank(wvf, 252)
stretch  = close / ta.sma(close, 50) - 1
gauge    = 0.5 * (100 - fearRank) + 0.5 * ta.percentrank(stretch, 252)
 
// ───────── Ladder (decided at the bar close) ─────────
ready = not na(gauge) and not na(ma200) and (not useVix or not na(vixPct))
var float target = 0.0
var int   lastChg = -100000
prev = target
float want = 100.0
if warnings >= 3
    want := 0.0
else if riskOff
    want := trend == 1 ? 70.0 : 0.0
float newT = prev
if ready and want != prev and (want == 0 or prev == 0 or bar_index - lastChg >= COOL)
    newT := want
changed = newT != prev
string reason = ""
if changed
    reason := newT == 100 ? (prev == 0 ? "risk-off over" : "all clear") : newT == 70 ? (prev == 0 ? "rebound: trend up" : "risk-off, trend still up") : warnings >= 3 ? "3 of 3 warnings" : prev == 70 ? "trend down in risk-off" : "risk-off"
    lastChg := bar_index
target := newT
stepUp   = changed and newT > prev
stepDown = changed and newT < prev
 
// ───────── Exposure pane ─────────
expCol(float x) =>
    x >= 100 ? color.new(#00c853, 0) : x >= 70 ? color.new(#64dd17, 0) : color.new(#ff1744, 0)
pExp  = plot(target, "Exposure %", expCol(target), 3, plot.style_stepline)
pZero = plot(0, "Zero", color.new(color.gray, 100), display = display.none)
fill(pExp, pZero, color.new(expCol(target), 75), "Exposure fill")
hline(100, "100%", color.new(color.gray, 60), hline.style_dotted)
hline(70, "70%", color.new(color.gray, 60), hline.style_dotted)
hline(0, "0%", color.new(color.gray, 60), hline.style_dotted)
 
// ───────── Labels on price (every change states the action and the resulting position) ─────────
fmt(float x) => str.tostring(x, "#") + "%"
if showLbl and changed and barstate.isconfirmed
    string act = stepUp ? "BUY → " + fmt(newT) : newT == 0 ? "SELL ALL → 0%" : "SELL " + fmt(prev - newT) + " → " + fmt(newT)
    string txt = showWhy ? act + "\n" + reason : act
    if stepUp
        label.new(bar_index, low, txt, yloc = yloc.belowbar, color = color.new(#00c853, 0), textcolor = color.white, style = label.style_label_up, size = size.large, force_overlay = true)
    else
        label.new(bar_index, high, txt, yloc = yloc.abovebar, color = newT == 0 ? color.new(#d50000, 0) : color.new(#ff6d00, 0), textcolor = color.white, style = label.style_label_down, size = size.large, force_overlay = true)
bgcolor(riskOff ? color.new(#ff1744, 90) : na, title = "Risk-off shading", force_overlay = true)
 
// ───────── Now readout ─────────
mood(float g) =>
    g >= 90 ? "extreme greed" : g >= 80 ? "greed" : g <= 10 ? "extreme fear" : g <= 20 ? "fear" : "neutral"
var label lNow = na
if showNow and barstate.islast
    label.delete(lNow)
    string nxt = target >= 100 ? (warnings == 1 ? "one more warning = risk-off" : "risk-off needs 2 warnings") : target >= 70 ? "100% when risk-off ends; 0% if the trend turns down" : (warnings >= 3 ? "70% needs a warning to clear and the trend up" : "70% when the trend turns up; 100% when risk-off ends")
    string t1 = "Now: " + fmt(target) + " invested"
    string t2 = "Warnings " + str.tostring(warnings) + "/3 · trend " + (trend == 1 ? "up" : "down") + " · mood " + str.tostring(gauge, "#") + " (" + mood(gauge) + ", info only)"
    lNow := label.new(bar_index + 3, close, t1 + "\n" + t2 + "\nNext: " + nxt, color = expCol(target), textcolor = color.white, style = label.style_label_left, size = size.normal, force_overlay = true)
 
// ───────── Alerts ─────────
alertcondition(stepUp, "BUY (exposure up)", "Risk-Off Ladder: BUY, exposure up on {{ticker}}")
alertcondition(stepDown and target > 0, "SELL part (exposure down)", "Risk-Off Ladder: SELL part, exposure down on {{ticker}}")
alertcondition(stepDown and target == 0, "SELL ALL (risk-off)", "Risk-Off Ladder: SELL ALL, risk-off on {{ticker}}")
alertcondition(changed, "Any exposure change", "Risk-Off Ladder: exposure changed on {{ticker}}")
if changed and barstate.isconfirmed
    alert("Risk-Off Ladder " + syminfo.ticker + ": " + (stepUp ? "BUY → " : "SELL → ") + fmt(newT) + " (" + reason + ")", alert.freq_once_per_bar_close)
 
// ───────── Results table: ladder vs buy-and-hold, close to close, no costs ─────────
var float eq = 1.0
var float eqPk = 1.0
var float eqDD = 0.0
var float bh0 = na
var float bhPk = na
var float bhDD = 0.0
var float sumExp = 0.0
var int   nBars = 0
var int   nChg = 0
var int   t0 = na
if time >= startT and ready
    if na(bh0)
        bh0 := close
        t0 := time
    else
        eq := eq * (1 + target[1] / 100 * (close / close[1] - 1))
    eqPk := math.max(eqPk, eq)
    eqDD := math.min(eqDD, eq / eqPk - 1)
    bhPk := na(bhPk) ? close : math.max(bhPk, close)
    bhDD := math.min(bhDD, close / bhPk - 1)
    sumExp += target
    nBars += 1
    nChg += changed ? 1 : 0
pct(float x) => str.tostring(x * 100, "#.#") + "%"
var table t = table.new(position.top_left, 3, 7, bgcolor = color.new(color.black, 25), border_width = 1)
if showTbl and barstate.islast and not na(bh0)
    yrs = math.max((time - t0) / (365.25 * 86400000.0), 0.01)
    t.cell(0, 0, "Since " + str.format_time(t0, "yyyy-MM-dd", syminfo.timezone) + " (close to close, no costs)", text_color = color.white, text_size = size.small)
    t.merge_cells(0, 0, 2, 0)
    t.cell(1, 1, "Ladder", text_color = color.silver, text_size = size.small)
    t.cell(2, 1, "Buy & hold", text_color = color.silver, text_size = size.small)
    t.cell(0, 2, "Return", text_color = color.white, text_size = size.small)
    t.cell(1, 2, pct(eq - 1), text_color = color.white, text_size = size.small)
    t.cell(2, 2, pct(close / bh0 - 1), text_color = color.white, text_size = size.small)
    t.cell(0, 3, "Per year", text_color = color.white, text_size = size.small)
    t.cell(1, 3, pct(math.pow(eq, 1 / yrs) - 1), text_color = color.white, text_size = size.small)
    t.cell(2, 3, pct(math.pow(close / bh0, 1 / yrs) - 1), text_color = color.white, text_size = size.small)
    t.cell(0, 4, "Worst drop", text_color = color.white, text_size = size.small)
    t.cell(1, 4, pct(eqDD), text_color = color.white, text_size = size.small)
    t.cell(2, 4, pct(bhDD), text_color = color.white, text_size = size.small)
    t.cell(0, 5, "Average exposure", text_color = color.white, text_size = size.small)
    t.cell(1, 5, str.tostring(sumExp / nBars, "#") + "%", text_color = color.white, text_size = size.small)
    t.cell(2, 5, "100%", text_color = color.white, text_size = size.small)
    t.cell(0, 6, "Changes per year", text_color = color.white, text_size = size.small)
    t.cell(1, 6, str.tostring(nChg / yrs, "#.#"), text_color = color.white, text_size = size.small)
    t.cell(2, 6, "0", text_color = color.white, text_size = size.small)

← 返回列表