本页源码来自 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/
// Trend Safety Switch: long-only SuperTrend with a public risk regime, scale-out exits and a buy-and-hold comparison
// SuperTrend band and trend-flip code is based on "SuperTrend" by KivancOzbilgic (open-source on TradingView, 2020),
// who credits everget (Alex Orekhov) for the signal and highlight style. SuperTrend itself is a classic ATR indicator
// by Olivier Seban. Full credit to them for the original.
// New in this version: Pine v6 strategy, a public regime filter (VIX percentile, 200 MA, drawdown), an ADX chop filter,
// plain-language order labels (BUY -> 100%, SELL 70% (keep 30%), SELL ALL), a live status label,
// scale-out (keep a part of the position on a flip in a healthy regime instead of all-or-nothing), alerts, and a stats
// table that compares the strategy with buy-and-hold over the same period.
//@version=6
strategy("Trend Safety Switch", shorttitle = "Trend Safety Switch", overlay = true,
initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100,
commission_type = strategy.commission.percent, commission_value = 0.02, slippage = 2,
margin_long = 100, margin_short = 100, pyramiding = 10, process_orders_on_close = false, calc_on_every_tick = false, max_labels_count = 500)
// ───────── Original SuperTrend inputs (same defaults as KivancOzbilgic) ─────────
grpS = "SuperTrend"
Periods = input.int(10, "ATR period", minval = 1, group = grpS)
src = input.source(hl2, "Source", group = grpS)
Multiplier = input.float(3.0, "ATR multiplier", step = 0.1, minval = 0.1, group = grpS)
changeATR = input.bool(true, "Use RMA ATR (off = SMA of true range)", group = grpS)
// ───────── Regime inputs (public data only) ─────────
grpR = "Risk regime (public inputs)"
useVix = input.bool(true, "Use VIX percentile", group = grpR)
vixSym = input.symbol("CBOE:VIX", "VIX symbol", group = grpR)
vixLen = input.int(252, "VIX ranking window (bars)", minval = 20, group = grpR)
vixHigh = input.int(80, "Risk-off when VIX percentile >=", minval = 50, maxval = 100, group = grpR)
useMA = input.bool(true, "Use trend MA", group = grpR)
maLen = input.int(200, "Trend MA length", minval = 20, group = grpR)
useDD = input.bool(true, "Use drawdown", group = grpR)
ddLen = input.int(252, "Drawdown lookback (bars)", minval = 20, group = grpR)
ddMax = input.float(15.0, "Risk-off when drawdown deeper than (%)", minval = 1, group = grpR)
riskVotes = input.int(2, "Risk-off needs this many warnings", minval = 1, maxval = 3, group = grpR, tooltip = "Warnings: VIX percentile high, close below the trend MA, drawdown deeper than the limit. Only the enabled ones count.")
// ───────── Entries / exits ─────────
grpE = "Position"
keepPct = input.float(30.0, "Keep this % on a down-flip in a healthy regime", minval = 0, maxval = 100, step = 5, group = grpE, tooltip = "0 = classic all-or-nothing SuperTrend.")
useAdx = input.bool(true, "Skip new entries in chop (ADX filter)", group = grpE)
adxLen = input.int(14, "ADX length", minval = 2, group = grpE)
adxMin = input.float(15.0, "Min ADX for a new entry", minval = 0, group = grpE)
startT = input.time(timestamp("2000-01-01T00:00:00"), "Backtest start", group = grpE)
// ───────── Display ─────────
grpD = "Display"
showSig = input.bool(true, "Show buy / sell labels", group = grpD)
showBg = input.bool(true, "Shade risk-off regime", group = grpD)
showTbl = input.bool(true, "Show stats table", group = grpD)
// ───────── SuperTrend (original logic, v6 syntax) ─────────
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * 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
flipUp = trend == 1 and trend[1] == -1
flipDn = trend == -1 and trend[1] == 1
// ───────── Regime ─────────
vixClose = request.security(vixSym, timeframe.period, close) // same timeframe as the chart, no lookahead
vixPct = ta.percentrank(vixClose, vixLen)
trendMA = ta.sma(close, maLen)
ddPct = (close / ta.highest(high, ddLen) - 1) * 100
w1 = useVix and not na(vixPct) and vixPct >= vixHigh ? 1 : 0
w2 = useMA and close < trendMA ? 1 : 0
w3 = useDD and ddPct < -ddMax ? 1 : 0
enabled = (useVix ? 1 : 0) + (useMA ? 1 : 0) + (useDD ? 1 : 0)
riskOff = enabled > 0 and w1 + w2 + w3 >= math.min(riskVotes, enabled)
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
adxOK = not useAdx or adx >= adxMin
// ───────── Target exposure ─────────
// 100% when the SuperTrend is up and the regime is not risk-off (and ADX allows a new entry)
// keepPct when the SuperTrend is down but the regime is healthy, 0% when the regime is risk-off
var float target = 0.0
prevTarget = target
if trend == 1 and not riskOff
target := prevTarget >= 100 or adxOK ? 100.0 : prevTarget
else if trend == 1 and riskOff
target := 0.0
else
target := riskOff ? 0.0 : math.min(prevTarget, keepPct)
inRange = time >= startT
// ───────── Orders: move the position to the target % of equity ─────────
if inRange and barstate.isconfirmed
wantQty = strategy.equity * target / 100 / close
diff = wantQty - strategy.position_size
if target == 0 and strategy.position_size > 0
strategy.close_all(comment = "Sell all")
else if diff > 0 and diff * close > strategy.equity * 0.05
strategy.order("Buy", strategy.long, diff, comment = "Buy " + str.tostring(target, "#") + "%")
else if diff < 0 and -diff * close > strategy.equity * 0.05
strategy.order("Trim", strategy.short, -diff, comment = "Keep " + str.tostring(target, "#") + "%")
// ───────── Plots ─────────
// line colour: green = up trend, red = down trend, grey = up trend but the regime is risk-off (strategy is out)
upCol = riskOff ? color.gray : color.green
upPlot = plot(trend == 1 ? up : na, "Up trend", upCol, 2, plot.style_linebr)
dnPlot = plot(trend == 1 ? na : dn, "Down trend", color.red, 2, plot.style_linebr)
bgcolor(showBg and riskOff ? color.new(color.orange, 88) : na, title = "Risk-off regime (orange)")
buyLbl = target > prevTarget
sellLbl = target < prevTarget
fmtP(float x) => str.tostring(x, "#") + "%"
if showSig and inRange and buyLbl
label.new(bar_index, low, "BUY → " + fmtP(target), yloc = yloc.belowbar, color = color.new(color.green, 10), textcolor = color.white, style = label.style_label_up, size = size.small)
if showSig and inRange and sellLbl
txt = target == 0 ? "SELL ALL" : "SELL " + fmtP(prevTarget - target) + " (keep " + fmtP(target) + ")"
label.new(bar_index, high, txt, yloc = yloc.abovebar, color = target == 0 ? color.new(color.red, 10) : color.new(color.orange, 10), textcolor = color.white, style = label.style_label_down, size = size.small)
// status at the last bar
var label lNow = na
if barstate.islast
label.delete(lNow)
why = (w1 == 1 ? " VIX high" : "") + (w2 == 1 ? " below " + str.tostring(maLen) + " MA" : "") + (w3 == 1 ? " deep drawdown" : "")
reg = riskOff ? "RISK-OFF (" + str.trim(why) + ")" : "regime OK" + (why != "" ? " (warning:" + why + ")" : "")
lNow := label.new(bar_index + 2, close, "Now: " + fmtP(target) + " invested · trend " + (trend == 1 ? "up" : "down") + " · " + reg, color = riskOff ? color.new(color.orange, 10) : color.new(color.gray, 20), textcolor = color.white, style = label.style_label_left, size = size.normal)
// ───────── Alerts ─────────
alertcondition(buyLbl, "BUY", "Trend Safety Switch: BUY (exposure up) on {{ticker}}")
alertcondition(sellLbl and target > 0, "SELL part (keep some)", "Trend Safety Switch: sold part, keeping some, on {{ticker}}")
alertcondition(sellLbl and target == 0, "SELL ALL", "Trend Safety Switch: SELL ALL on {{ticker}}")
alertcondition(riskOff and not riskOff[1], "Regime turns risk-off", "Risk-off regime started on {{ticker}}")
// ───────── Stats vs buy-and-hold ─────────
var float bhStart = na
var float peakEq = na
var float maxDD = 0.0
var float bhPeak = na
var float bhDD = 0.0
var int barsIn = 0
var int barsAll = 0
if inRange
if na(bhStart)
bhStart := close
peakEq := na(peakEq) ? strategy.equity : math.max(peakEq, strategy.equity)
maxDD := math.min(maxDD, strategy.equity / peakEq - 1)
bhPeak := na(bhPeak) ? close : math.max(bhPeak, close)
bhDD := math.min(bhDD, close / bhPeak - 1)
barsAll += 1
barsIn += strategy.position_size > 0 ? 1 : 0
var table t = table.new(position.bottom_right, 3, 7, bgcolor = color.new(color.black, 25), border_width = 1)
pct(x) => str.tostring(x * 100, "#.#") + "%"
if showTbl and barstate.islast and not na(bhStart)
t.cell(0, 0, "Backtest since " + str.format_time(startT, "yyyy-MM-dd", syminfo.timezone) + " (fees + slippage included)", text_color = color.white, text_size = size.small)
t.merge_cells(0, 0, 2, 0)
t.cell(0, 1, "", text_color = color.white, text_size = size.small)
t.cell(1, 1, "This strategy", 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(strategy.equity / strategy.initial_capital - 1), text_color = color.white, text_size = size.small)
t.cell(2, 2, pct(close / bhStart - 1), text_color = color.white, text_size = size.small)
t.cell(0, 3, "Worst drop (max drawdown)", text_color = color.white, text_size = size.small)
t.cell(1, 3, pct(maxDD), text_color = color.white, text_size = size.small)
t.cell(2, 3, pct(bhDD), text_color = color.white, text_size = size.small)
t.cell(0, 4, "Time in the market", text_color = color.white, text_size = size.small)
t.cell(1, 4, pct(barsAll > 0 ? float(barsIn) / barsAll : 0.0), text_color = color.white, text_size = size.small)
t.cell(2, 4, "100%", text_color = color.white, text_size = size.small)
t.cell(0, 5, "Closed trades", text_color = color.white, text_size = size.small)
t.cell(1, 5, str.tostring(strategy.closedtrades), text_color = color.white, text_size = size.small)
t.cell(2, 5, "-", text_color = color.white, text_size = size.small)
t.cell(0, 6, "Orange background = risk-off (strategy holds 0%)", text_color = color.orange, text_size = size.small)
t.merge_cells(0, 6, 2, 6)