本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Altcoin Season Composite Oscillator", overlay=false)
// ==========================================
// 0. SYMBOL + TIMEFRAME LOCK — ALTCOINS ONLY, WEEKLY ONLY
// ==========================================
allowedSymbol = syminfo.ticker == "OTHERS.D"
allowedTimeframe = timeframe.isweekly
allowedToRun = allowedSymbol and allowedTimeframe
showRestrictionWarning = input.bool(true, "Show Symbol/Timeframe Restriction Warning",
group="Symbol & Timeframe Lock",
tooltip="This script is purpose-built for ONE chart only: CRYPTOCAP:OTHERS.D (the combined market-cap dominance of all altcoins EXCLUDING the 10 largest coins), viewed on the WEEKLY timeframe.\n\nWHY OTHERS.D ONLY: the oscillator's entire premise is to detect genuine 'alt season' conditions — periods where capital structurally rotates OUT of Bitcoin and the largest caps and INTO the broader altcoin market. That rotation can only be measured correctly on the dominance of the broad altcoin basket itself (OTHERS.D), not on an individual altcoin's price or on BTC.D in isolation.\n\nWHY WEEKLY ONLY: dominance rotation between Bitcoin and altcoins is a macro, multi-month phenomenon. Lower timeframes (daily, intraday) are dominated by noise, exchange-specific volume spikes and intraday volatility that do not reflect genuine structural rotation. The Weekly close is the lowest timeframe at which this macro signal remains statistically meaningful and fully non-repainting.\n\nWhen this box is checked, a small warning box appears on your chart whenever the symbol or timeframe does not match these requirements, telling you exactly what to switch. Turn it off only if you understand the restriction and prefer a clean chart regardless.")
// ==========================================
// 1. INPUTS & CONFIGURATION (WEEKLY FOCUS)
// ==========================================
btcSourceInput = input.symbol("INDEX:BTCUSD", title="Bitcoin Price Symbol",
group="Core Data Sources",
tooltip="The Bitcoin spot price feed used to measure BTC's own macro trend strength (its position relative to its long-term SMA and its upper Bollinger extreme). INDEX:BTCUSD is an aggregated, exchange-neutral BTC price index, which avoids single-exchange manipulation/wick artifacts. You may replace it with any BTC spot or index symbol, but an aggregated index is recommended for weekly macro analysis.")
domSource = input.symbol("CRYPTOCAP:BTC.D", title="Dominance Symbol (BTC.D recommended, or OTHERS.D)",
group="Core Data Sources",
tooltip="The market-dominance series used as the directional confirmation filter. When this symbol's weekly close is BELOW its own EMA (see 'Dominance EMA Length'), dominance is considered to be trending down — i.e. capital is rotating away from that basket, supporting bullish conditions for altcoins. BTC.D (Bitcoin dominance) is recommended as the primary confirmation because a falling BTC.D is the clearest macro signature of capital rotating into altcoins. OTHERS.D can be used instead if you prefer to confirm directly on the altcoin basket, but note the chart symbol lock already requires OTHERS.D as your chart.")
bbLength = input.int(200, title="BTC Bollinger Band Length (SMA)",
group="Core Data Sources",
tooltip="Lookback length (in weekly bars) of the moving-average basis used to build BTC's upper Bollinger Band. This band represents BTC's long-term 'fair value' baseline; price trading far above it, by the multiplier set below, defines a statistically extreme/overheated BTC price condition. 200 weeks (~4 years) approximates a full Bitcoin halving cycle.")
bbMult = input.float(3.0, title="BTC Bollinger Band StdDev Multiplier",
group="Core Data Sources",
tooltip="Number of standard deviations added to the Bollinger basis to define the 'Extreme' upper threshold for BTC price. A higher multiplier requires a more extreme, statistically rarer price extension above the mean before the Extreme Bullish state can trigger. Lower values make the extreme threshold easier to reach.")
emaDomLen = input.int(20, title="Dominance EMA Length",
group="Core Data Sources",
tooltip="Length of the EMA applied to the Dominance Symbol's weekly closes. This EMA is the trend baseline the dominance series is compared against: dominance closing below its own EMA is read as a confirmed downtrend in that dominance metric, which is the directional 'permission' gate for bullish altcoin signals.")
smaArmLen = input.int(20, title="BTC Price Arming SMA Length",
group="Core Data Sources",
tooltip="Length of the short/medium-term SMA applied to BTC's weekly close. BTC trading ABOVE this SMA 'arms' the bullish state machine (the first of three required gates). Together with the Bollinger extreme and the dominance filter, this establishes whether BTC itself is in a constructive trend before any altcoin-season signal is allowed.")
useDomFallback = input.bool(true, title="Enable Pre-2018 Dominance Fallback", group="Historical Compatibility",
tooltip="Market-cap dominance data (BTC.D / OTHERS.D) is not available on TradingView before late 2017-2018. When ON, any historical weekly bar with no dominance data available is treated as if the dominance-confirmation gate were satisfied, so the other two gates (BTC armed and slope) can still produce a signal on early history. When OFF, bars without dominance data are treated as 'not confirmed' and will show the No-Signal state. This only affects historical bars before dominance data existed; it has no effect on current or recent bars.")
nonRepainting = input.bool(true, "Non-Repainting Mode - Wait for Weekly Candle Close", group="Repainting Control",
tooltip="ON (recommended, default): every higher-timeframe value used by this script — BTC weekly close, BTC arming SMA, BTC Bollinger extreme, Dominance weekly close, Dominance EMA — is pulled exclusively from the LAST CONFIRMED weekly candle. Nothing updates intrabar, so historical bars and the live/forming bar will never repaint or change value after the fact. This is the 'wait for candle close' behavior required for a fully non-repainting signal. OFF: values update live, intrabar, on the currently forming weekly candle — useful for monitoring an early developing signal in real time, but the current week's state CAN still change before the weekly close.")
oscRespLen = input.int(9, "Oscillator Responsiveness (higher = smoother within its band)", minval=1, group="Display",
tooltip="Controls the exponential smoothing constant applied to the oscillator line WITHIN its current state band (Extreme Bullish / Bullish / No-Signal). It does not affect which state is active, only how smoothly the line travels inside that state's range. Higher values = slower, smoother movement; lower values = snappier, more reactive movement. The line always snaps instantly to its new band the moment the underlying state changes.")
colNeutralUp = input.color(#ffffff, "Neutral 'Up' Candle Color (no signal)", group="Neutral Candle Colors",
tooltip="Candle color applied on the overlay candles when NO altcoin-season signal is active (No-Signal state) and the weekly candle closed up (close >= open). Purely informational/neutral coloring, not a trade signal.")
colNeutralDown = input.color(#000000, "Neutral 'Down' Candle Color (no signal)", group="Neutral Candle Colors",
tooltip="Candle color applied on the overlay candles when NO altcoin-season signal is active (No-Signal state) and the weekly candle closed down (close < open). Purely informational/neutral coloring, not a trade signal.")
showSignalCandles = input.bool(true, "Show Signal-Colored Candles on Main Chart", group="Display",
tooltip="When ON, the script overlays color-coded weekly candles directly on your main chart (green shades for Bullish/Extreme Bullish states, white/black for No-Signal), in addition to the oscillator pane below. Turn OFF if you only want the oscillator pane and prefer to keep your main chart free of overlay plots.")
showSlopeMA = input.bool(true, "Show Slope MA on Main Chart", group="Slope Moving Average",
tooltip="When ON, plots the Slope Moving Average line directly on your main price chart, colored by its own slope direction. This is the same moving average used internally as the slope gate below; displaying it lets you visually verify why a signal is or isn't currently allowed.")
slopeMaType = input.string("EMA", "Slope MA Type", options=["SMA", "EMA", "WMA", "RMA", "VWMA"], group="Slope Moving Average",
tooltip="Moving-average calculation method used for the Slope MA gate. EMA/RMA react faster to recent price than SMA; WMA weights recent bars more heavily; VWMA additionally weights by volume. This choice changes how quickly the slope gate reacts to new trend changes.")
slopeMaLen = input.int(200, "Slope MA Length", minval=1, group="Slope Moving Average",
tooltip="Lookback length (in weekly bars) for the Slope MA. This moving average's week-over-week percentage change is the third and final gate: a Bullish or Extreme Bullish signal is only allowed when this slope is rising at or above the threshold set below.")
slopeMaSrc = input.source(close, "Slope MA Source", group="Slope Moving Average",
tooltip="Price source fed into the Slope MA calculation (default: close). Changing this changes what the slope gate is measuring the trend of — for example switching to hl2 or hlc3 will smooth out the influence of single-bar closes.")
slopeMaThresh = input.float(0.0, "Slope Threshold (%) — slope must be ABOVE this to allow a signal", minval=0.0, step=0.001, group="Slope Moving Average",
tooltip="Minimum required week-over-week percentage change of the Slope MA for the slope gate to be considered 'positive'. 0.0 means any non-negative slope (flat or rising) passes the gate. Raising this value requires a steeper, more decisive uptrend in the Slope MA before any Bullish or Extreme Bullish signal is permitted, filtering out weak/choppy trend conditions.")
slopeMaColUp = input.color(#1ff500, "Slope MA Up Color", group="Slope Moving Average",
tooltip="Color used to draw the Slope MA line when its slope is at or above the threshold (gate open / signals permitted).")
slopeMaColDn = input.color(#ff0000, "Slope MA Down Color", group="Slope Moving Average",
tooltip="Color used to draw the Slope MA line when its slope is below the threshold (gate closed / no Bullish or Extreme Bullish signals permitted, regardless of the other two gates).")
// ==========================================
// 0.1 ON-CHART RESTRICTION WARNING (replaces hard runtime.error)
// ==========================================
var table warnTable = table.new(position.top_right, 1, 1, border_width=1)
if barstate.islast
if showRestrictionWarning and not allowedToRun
warnMsg = ""
if not allowedSymbol
warnMsg := warnMsg + "Wrong symbol — switch to CRYPTOCAP:OTHERS.D. "
if not allowedTimeframe
warnMsg := warnMsg + "Wrong timeframe — switch chart to Weekly (1W)."
table.cell(warnTable, 0, 0, warnMsg, text_color=color.white, bgcolor=color.new(color.red, 10), text_size=size.small)
else
table.cell(warnTable, 0, 0, "", bgcolor=color.new(color.white, 100))
// ==========================================
// 2. HELPER FUNCTIONS
// ==========================================
f_safeSma(src, len) =>
availLen = math.max(1, math.min(bar_index + 1, len))
ta.sma(src, availLen)
f_safeBtcBbUpper(src, len, mult) =>
availLen = math.max(1, math.min(bar_index + 1, len))
smaVal = ta.sma(src, availLen)
stdevVal = ta.stdev(src, availLen)
smaVal + (nz(stdevVal, 0) * mult)
f_ma(float _src, simple int _len, string _type) =>
switch _type
"SMA" => ta.sma(_src, _len)
"EMA" => ta.ema(_src, _len)
"WMA" => ta.wma(_src, _len)
"RMA" => ta.rma(_src, _len)
"VWMA" => ta.vwma(_src, _len)
=> ta.sma(_src, _len)
f_secLive(sym, tf, src) =>
request.security(sym, tf, src, barmerge.gaps_off, barmerge.lookahead_off)
f_secSafe(sym, tf, src) =>
request.security(sym, tf, src[1], barmerge.gaps_off, barmerge.lookahead_on)
// ==========================================
// 3. DATA FEEDS
// ==========================================
btcCloseRaw = nonRepainting ? f_secSafe(btcSourceInput, "W", close) : f_secLive(btcSourceInput, "W", close)
btcClose = nz(btcCloseRaw, close)
btcSmaArmRaw = nonRepainting ? f_secSafe(btcSourceInput, "W", ta.sma(close, smaArmLen)) : f_secLive(btcSourceInput, "W", ta.sma(close, smaArmLen))
btcSmaArm = nz(btcSmaArmRaw, f_safeSma(close, smaArmLen))
btcBbExpr = ta.sma(close, bbLength) + (ta.stdev(close, bbLength) * bbMult)
btcBbUpperRaw = nonRepainting ? f_secSafe(btcSourceInput, "W", btcBbExpr) : f_secLive(btcSourceInput, "W", btcBbExpr)
btcBbUpper = nz(btcBbUpperRaw, f_safeBtcBbUpper(close, bbLength, bbMult))
domCloseRaw = nonRepainting ? f_secSafe(domSource, "W", close) : f_secLive(domSource, "W", close)
domEmaRaw = nonRepainting ? f_secSafe(domSource, "W", ta.ema(close, emaDomLen)) : f_secLive(domSource, "W", ta.ema(close, emaDomLen))
// ==========================================
// 4. SLOPE MA — COMPUTED FIRST, A HARD SIGNAL GATE
// ==========================================
slopeMA = f_ma(slopeMaSrc, slopeMaLen, slopeMaType)
slopeMaPct = nz((slopeMA - slopeMA[1]) / slopeMA[1] * 100)
slopeMaColor = slopeMaPct >= slopeMaThresh ? slopeMaColUp : slopeMaColDn
slopePositive = slopeMaPct >= slopeMaThresh
// ==========================================
// 5. CORE CONDITIONS (LONG-ONLY, SLOPE-GATED)
// ==========================================
condArmed = (btcClose > btcSmaArm)
condDomConfirm = (na(domCloseRaw) or na(domEmaRaw)) ? useDomFallback : (domCloseRaw < domEmaRaw)
condExtremeTouch = (btcClose >= btcBbUpper)
condBullishBase = condArmed and condDomConfirm and slopePositive
condExtremeBullish = condBullishBase and condExtremeTouch
condBullish = condBullishBase and not condExtremeTouch
condNoSignal = not (condExtremeBullish or condBullish)
condArmedNoConfirm = condArmed and not condDomConfirm
condNotArmedDomOk = (not condArmed) and condDomConfirm
// ==========================================
// 6. OSCILLATOR — EXACT, ZERO-LAG TRACKING OF THE CANDLE STATE
// ==========================================
bullSpan = btcBbUpper - btcSmaArm
minSpanGuard = math.max(math.abs(btcSmaArm) * 0.05, syminfo.mintick * 10)
safeBullSpan = bullSpan > 0 ? bullSpan : minSpanGuard
bullPos = (btcClose - btcSmaArm) / safeBullSpan
bullPosClamped = math.max(0.0, math.min(bullPos, 1.0))
extPos = (btcClose - btcBbUpper) / safeBullSpan
extPosClamped = math.max(0.0, math.min(extPos, 1.0))
noSigPos = (btcSmaArm - btcClose) / safeBullSpan
noSigPosClamped = math.max(0.0, math.min(noSigPos, 1.0))
targetOsc = 0.0
if condExtremeBullish
targetOsc := 75.0 + extPosClamped * 25.0
else if condBullish
targetOsc := 50.0 + bullPosClamped * 25.0
else
targetOsc := 50.0 - noSigPosClamped * 50.0
curState = 0
if condExtremeBullish
curState := 2
else if condBullish
curState := 1
else
curState := 0
prevState = curState[1]
var float smoothOsc = na
alpha = 2.0 / (oscRespLen + 1.0)
if na(smoothOsc) or curState != prevState
smoothOsc := targetOsc
else
smoothOsc := smoothOsc + alpha * (targetOsc - smoothOsc)
oscLine = 0.0
if condExtremeBullish
oscLine := math.max(smoothOsc, 75.0)
else if condBullish
oscLine := math.min(math.max(smoothOsc, 50.0), 75.0)
else
oscLine := math.min(smoothOsc, 50.0)
// ==========================================
// 7. COLORS DEFINITION (ONLY 2 GREENS + NEUTRAL BLACK/WHITE)
// ==========================================
colExtremeBullish = #1fff00
colBullish = #2cb519
neutralCandleColor = close >= open ? colNeutralUp : colNeutralDown
activeColor = colNeutralUp
if condExtremeBullish
activeColor := colExtremeBullish
else if condBullish
activeColor := colBullish
else
activeColor := neutralCandleColor
// ==========================================
// 8. ZONES & PLOTTING
// ==========================================
p100 = plot(100, title="Max (100)", color=color.new(color.gray, 50), style=plot.style_line)
p75 = plot(75, title="Extreme Bullish Base (75)", color=color.new(colExtremeBullish, 30), style=plot.style_line, linewidth=1)
p50 = plot(50, title="Bullish Base (50)", color=color.new(colBullish, 30), style=plot.style_line, linewidth=1)
p0 = plot(0, title="Min (0)", color=color.new(color.gray, 50), style=plot.style_line)
fill(p100, p75, color=color.new(colExtremeBullish, 50), title="Extreme Bullish Zone (75-100)")
fill(p75, p50, color=color.new(colBullish, 50), title="Bullish Zone (50-75)")
fill(p50, p0, color=color.new(color.gray, 85), title="No-Signal Zone (0-50)")
plot(allowedToRun ? oscLine : na, title="Altcoin Season Composite Oscillator", color=color.white, linewidth=2, trackprice=true)
candleShow = showSignalCandles and allowedToRun
plotcandle(candleShow ? open : na, candleShow ? high : na, candleShow ? low : na, candleShow ? close : na,
title="Altcoin Season Candles", color=activeColor, wickcolor=activeColor, bordercolor=activeColor, force_overlay=true)
plot((showSlopeMA and allowedToRun) ? slopeMA : na, title="Slope MA Overlay", color=slopeMaColor, linewidth=3, force_overlay=true)
// ==========================================
// 9. ALERTS
// ==========================================
stateExtremeChanged = condExtremeBullish and not condExtremeBullish[1]
stateBullishChanged = condBullish and not condBullish[1]
stateNoSignalChanged = condNoSignal and not condNoSignal[1]
stateArmedWaitChanged = condArmedNoConfirm and not condArmedNoConfirm[1]
stateDomWaitChanged = condNotArmedDomOk and not condNotArmedDomOk[1]
anyStateChanged = stateExtremeChanged or stateBullishChanged or stateNoSignalChanged
alertcondition(stateExtremeChanged, title="Extreme Bullish State Entered",
message="Altcoin Season Composite Oscillator: EXTREME BULLISH state entered on {{ticker}} ({{interval}}). BTC is armed, extended above its Bollinger extreme, dominance confirms, and the slope gate is positive.")
alertcondition(stateBullishChanged, title="Bullish State Entered",
message="Altcoin Season Composite Oscillator: BULLISH state entered on {{ticker}} ({{interval}}). BTC is armed above its SMA, dominance confirms, and the slope gate is positive.")
alertcondition(stateNoSignalChanged, title="No-Signal State Entered",
message="Altcoin Season Composite Oscillator: conditions no longer support an altcoin-season signal on {{ticker}} ({{interval}}).")
alertcondition(stateArmedWaitChanged, title="BTC Armed - Awaiting Dominance Confirmation",
message="Altcoin Season Composite Oscillator: BTC is armed above its SMA on {{ticker}} ({{interval}}), but dominance has not yet confirmed a downtrend. Watch for confirmation.")
alertcondition(stateDomWaitChanged, title="Dominance Confirming - Awaiting BTC Arming",
message="Altcoin Season Composite Oscillator: dominance is already confirming a downtrend on {{ticker}} ({{interval}}), but BTC has not yet armed above its SMA. Watch for BTC to catch up.")
alertcondition(anyStateChanged, title="Any Signal State Change",
message="Altcoin Season Composite Oscillator: signal state changed on {{ticker}} ({{interval}}). Check the chart for the new state.")
if allowedToRun and barstate.isconfirmed
if stateExtremeChanged
alert("Altcoin Season Composite Oscillator: EXTREME BULLISH state entered on " + syminfo.ticker + " (" + timeframe.period + ").", alert.freq_once_per_bar_close)
if stateBullishChanged
alert("Altcoin Season Composite Oscillator: BULLISH state entered on " + syminfo.ticker + " (" + timeframe.period + ").", alert.freq_once_per_bar_close)
if stateNoSignalChanged
alert("Altcoin Season Composite Oscillator: NO-SIGNAL state entered on " + syminfo.ticker + " (" + timeframe.period + ").", alert.freq_once_per_bar_close)
if stateArmedWaitChanged
alert("Altcoin Season Composite Oscillator: BTC armed, awaiting dominance confirmation, on " + syminfo.ticker + " (" + timeframe.period + ").", alert.freq_once_per_bar_close)
if stateDomWaitChanged
alert("Altcoin Season Composite Oscillator: dominance confirming, awaiting BTC arming, on " + syminfo.ticker + " (" + timeframe.period + ").", alert.freq_once_per_bar_close)