本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Market Leader Score", shorttitle="LEADER", overlay=false, precision=1)
// ── Guard: Daily or lower only ─────────────────────────
if timeframe.isweekly or timeframe.ismonthly
runtime.error("LEADER: use Daily or an intraday timeframe. Higher timeframes cannot be made non-repainting.")
// ── Inputs: logic ──────────────────────────────────────
benchSym = input.symbol("SPY", "Benchmark")
lenRSHigh = input.int(252, "RS-line high lookback (days)", minval=50)
lenDown = input.int(63, "Resilience lookback (days)", minval=20)
lenVol = input.int(50, "Accumulation lookback (days)", minval=10)
minScore = input.int(75, "Leader threshold", minval=0, maxval=100)
exitScore = input.int(60, "Leadership-lost threshold", minval=0, maxval=100)
grpExt = "Extension filter"
lenATR = input.int(14, "ATR length (days)", minval=5, group=grpExt)
buyMaxATR = input.float(2.0, "Buyable: max ATRs above 50MA", minval=0.5, step=0.25, group=grpExt)
extMaxATR = input.float(4.0, "Extended: max ATRs above 50MA", minval=1.0, step=0.25, group=grpExt)
grpSig = "Signal filtering"
cooldown = input.int(10, "Min trading days between same label", minval=0, group=grpSig)
// ── Inputs: display ────────────────────────────────────
grpVis = "Display"
showLabels = input.bool(true, "Signal labels (BUY / EXT / RS / ⭐)", group=grpVis)
showZones = input.bool(true, "Shade leader / exit zones", group=grpVis)
showTable = input.bool(true, "Show table", group=grpVis)
compact = input.bool(false, "Compact table", group=grpVis)
tblPosIn = input.string("Top left", "Table position", options=["Top left", "Middle left", "Bottom left", "Top right", "Middle right", "Bottom right"], group=grpVis)
tblSizeIn = input.string("Normal", "Table text size", options=["Small", "Normal", "Large"], group=grpVis)
tblPos = switch tblPosIn
"Middle left" => position.middle_left
"Bottom left" => position.bottom_left
"Top right" => position.top_right
"Middle right" => position.middle_right
"Bottom right" => position.bottom_right
=> position.top_left
tsz = switch tblSizeIn
"Small" => size.small
"Large" => size.large
=> size.normal
// ── Helpers ────────────────────────────────────────────
f_clamp(x) => math.max(0.0, math.min(100.0, x))
f_ret(src, n) =>
k = math.min(bar_index, n)
k > 0 ? src / src[k] : 1.0
f_weightedPerf(src) =>
0.4 * f_ret(src, 63) + 0.2 * f_ret(src, 126) + 0.2 * f_ret(src, 189) + 0.2 * f_ret(src, 252)
// ── Full calculation in DAILY context ──────────────────
// off = 1 → prior completed day (intraday charts); off = 0 → same day (daily chart)
f_calc(off) =>
bClose = request.security(benchSym, timeframe.period, close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
// 1. RS Rating
rsWeighted = f_weightedPerf(close) / f_weightedPerf(bClose)
rsComp = f_clamp(50 + (rsWeighted - 1) * 125)
// 2. RS line vs its 52w high
rsLine = close / bClose
rsHi = ta.highest(rsLine, lenRSHigh)
rsDist = rsLine / rsHi
rsHighComp = f_clamp((rsDist - 0.85) / 0.15 * 100)
hi52 = ta.highest(high, 252)
rsLeads = rsLine >= rsHi and close < hi52 * 0.95
// 3. Resilience: downside capture
sRet = close / close[1] - 1
bRet = bClose / bClose[1] - 1
bDown = bRet < 0
sDownSum = math.sum(bDown ? sRet : 0.0, lenDown)
bDownSum = math.sum(bDown ? bRet : 0.0, lenDown)
downCap = bDownSum != 0 ? sDownSum / bDownSum : na
resComp = na(downCap) ? 50.0 : f_clamp((1.5 - downCap) / 1.5 * 100)
// 4. Trend template
sma50 = ta.sma(close, 50)
sma150 = ta.sma(close, 150)
sma200 = ta.sma(close, 200)
lo52 = ta.lowest(low, 252)
t1 = close > sma50 and sma50 > sma150 and sma150 > sma200
t2 = sma200 > sma200[21]
t3 = close >= hi52 * 0.75
t4 = close >= lo52 * 1.30
trendComp = (t1 ? 40.0 : 0.0) + (t2 ? 20.0 : 0.0) + (t3 ? 20.0 : 0.0) + (t4 ? 20.0 : 0.0)
// 5. Accumulation
upVol = math.sum(close > close[1] ? volume : 0.0, lenVol)
dnVol = math.sum(close < close[1] ? volume : 0.0, lenVol)
udRatio = dnVol > 0 ? upVol / dnVol : 2.0
accComp = f_clamp((udRatio - 0.8) / (1.5 - 0.8) * 100)
// Composite + regime
score = 0.30 * rsComp + 0.20 * rsHighComp + 0.20 * resComp + 0.20 * trendComp + 0.10 * accComp
mktWeak = bClose < ta.sma(bClose, 50)
leaderCorr = mktWeak and close > sma50 and rsDist >= 0.97
// Extension: ATRs above the 50MA
atrD = ta.atr(lenATR)
extATR = atrD > 0 ? (close - sma50) / atrD : na
[score[off], rsComp[off], rsHighComp[off], resComp[off], trendComp[off], accComp[off], rsWeighted[off], rsDist[off], downCap[off], udRatio[off], mktWeak[off], leaderCorr[off], rsLeads[off], extATR[off]]
// ── Data request ───────────────────────────────────────
// Intraday: prior completed day + lookahead_on (standard non-repainting HTF pattern)
// Daily: same-bar values, lookahead_off
isIntra = timeframe.isintraday
[rScore, rRsComp, rRsHighComp, rResComp, rTrendComp, rAccComp, rRsWeighted, rRsDist, rDownCap, rUdRatio, rMktWeak, rLeaderCorr, rRsLeads, rExtATR] = request.security(syminfo.tickerid, "D", f_calc(isIntra ? 1 : 0), gaps=barmerge.gaps_off, lookahead=isIntra ? barmerge.lookahead_on : barmerge.lookahead_off)
// Daily chart: closed bars use their own values; only a still-forming bar falls back to the prior day
idx = isIntra ? 0 : (barstate.isconfirmed ? 0 : 1)
score = rScore[idx]
rsComp = rRsComp[idx]
rsHighComp = rRsHighComp[idx]
resComp = rResComp[idx]
trendComp = rTrendComp[idx]
accComp = rAccComp[idx]
rsWeighted = rRsWeighted[idx]
rsDist = rRsDist[idx]
downCap = rDownCap[idx]
udRatio = rUdRatio[idx]
mktWeak = rMktWeak[idx]
leaderCorr = rLeaderCorr[idx]
rsLeads = rRsLeads[idx]
extATR = rExtATR[idx]
isFinal = not isIntra and barstate.isconfirmed
// ── Status ─────────────────────────────────────────────
isLeader = score >= minScore
belowMA = not na(extATR) and extATR < 0
buyable = isLeader and not na(extATR) and extATR >= 0 and extATR <= buyMaxATR
extended = isLeader and extATR > buyMaxATR and extATR <= extMaxATR
veryExt = isLeader and extATR > extMaxATR
lost = score < exitScore
statusTxt = lost ? "NOT LEADER" : not isLeader ? "WATCH" : belowMA ? "BELOW 50MA" : buyable ? "BUYABLE ✅" : extended ? "EXTENDED — wait" : veryExt ? "VERY EXTENDED ⚠" : "n/a"
statusCol = lost ? color.new(color.red, 40) : not isLeader ? color.gray : belowMA ? color.orange : buyable ? color.lime : extended ? color.yellow : veryExt ? color.red : color.gray
extCol = na(extATR) ? color.gray : extATR < 0 ? color.orange : extATR <= buyMaxATR ? color.lime : extATR <= extMaxATR ? color.yellow : color.red
scoreCol = color.from_gradient(score, 40, 90, color.red, color.lime)
// ── De-chattered signals: arm/re-arm + cooldown ────────
var int dayNum = 0
if timeframe.change("D")
dayNum += 1
var bool buyArmed = true
var bool extArmed = true
var int lastBuyDay = -100000
var int lastExtDay = -100000
var int lastRSDay = -100000
var int lastCorDay = -100000
// BUY: once per setup cycle
buySig = buyable and not buyable[1] and buyArmed and (dayNum - lastBuyDay >= cooldown)
if buySig
buyArmed := false
lastBuyDay := dayNum
if veryExt or belowMA or lost
buyArmed := true
// EXT: once per run-up
extSig = veryExt and not veryExt[1] and extArmed and (dayNum - lastExtDay >= cooldown)
if extSig
extArmed := false
lastExtDay := dayNum
if (not na(extATR) and extATR <= buyMaxATR) or lost
extArmed := true
// RS / ⭐: cooldown only
rsSig = rsLeads and not rsLeads[1] and (dayNum - lastRSDay >= cooldown)
if rsSig
lastRSDay := dayNum
corrSig = leaderCorr and not leaderCorr[1] and (dayNum - lastCorDay >= cooldown)
if corrSig
lastCorDay := dayNum
// ── Fixed 0–100 scale + zones ──────────────────────────
hTop = hline(100, "Top", color.new(color.gray, 100))
hLead = hline(minScore, "Leader threshold", color.new(color.lime, 40), hline.style_dashed, 1)
hExit = hline(exitScore, "Exit threshold", color.new(color.red, 40), hline.style_dashed, 1)
hBot = hline(0, "Bottom", color.new(color.gray, 100))
fill(hTop, hLead, showZones ? color.new(color.lime, 90) : na, "Leader zone")
fill(hExit, hBot, showZones ? color.new(color.red, 92) : na, "Exit zone")
// ── Score ──────────────────────────────────────────────
plot(score, "Leader Score", scoreCol, 3, plot.style_stepline)
bgcolor(leaderCorr ? color.new(color.yellow, 85) : na, title="Leader in correction")
// ── Labels ─────────────────────────────────────────────
plotshape(showLabels and buySig ? score : na, "BUY label", shape.labelup, location.absolute, color.lime, text="BUY", textcolor=color.black, size=size.small)
plotshape(showLabels and extSig ? score : na, "EXT label", shape.labeldown, location.absolute, color.red, text="EXT", textcolor=color.white, size=size.small)
plotshape(showLabels and rsSig, "RS label", shape.labeldown, location.top, color.aqua, text="RS", textcolor=color.black, size=size.small)
plotshape(showLabels and corrSig, "Correction-leader label", shape.labeldown, location.top, color.yellow, text="⭐", textcolor=color.black, size=size.small)
// Hidden plots → columns in Pine Screener
plot(rsWeighted, "RS ratio", display=display.data_window)
plot(downCap, "Down capture", display=display.data_window)
plot(extATR, "Extension (ATR from 50MA)", display=display.data_window)
plot(leaderCorr ? 1 : 0, "Leader in correction", display=display.data_window)
plot(rsLeads ? 1 : 0, "RS leads price", display=display.data_window)
plot(buyable ? 1 : 0, "Leader buyable", display=display.data_window)
// ── Alerts: filtered signals only ──────────────────────
alertcondition(ta.crossover(score, minScore), "Leader score crossed up", "{{ticker}} leader score crossed threshold (confirmed close)")
alertcondition(ta.crossunder(score, exitScore), "Leadership lost", "{{ticker}} leader score fell below exit threshold (confirmed close)")
alertcondition(corrSig, "Leader in correction", "{{ticker}} held up while market weak (confirmed close)")
alertcondition(rsSig, "RS leads price", "{{ticker}} RS line new high ahead of price (confirmed close)")
alertcondition(buySig, "Leader buyable", "{{ticker}} leader within buyable range of 50MA (confirmed close)")
alertcondition(extSig, "Leader very extended", "{{ticker}} leader stretched far above 50MA (confirmed close)")
// ── Table ──────────────────────────────────────────────
var table tb = table.new(tblPos, 2, 11, bgcolor=color.new(#131722, 5), frame_color=color.new(color.gray, 60), frame_width=1, border_color=color.new(color.gray, 85), border_width=1)
f_row(r, label, val, col) =>
table.cell(tb, 0, r, label, text_color=color.new(color.white, 20), text_size=tsz, text_halign=text.align_left)
table.cell(tb, 1, r, val, text_color=col, text_size=tsz, text_halign=text.align_right)
if showTable and barstate.islast
table.clear(tb, 0, 0, 1, 10)
// Header
table.cell(tb, 0, 0, syminfo.ticker + " · " + (isFinal ? "last close" : "prior close"), text_color=color.white, text_size=tsz, bgcolor=color.new(color.gray, 70))
table.cell(tb, 1, 0, "", bgcolor=color.new(color.gray, 70))
table.merge_cells(tb, 0, 0, 1, 0)
// Score: big + colored background
table.cell(tb, 0, 1, "LEADER SCORE", text_color=color.white, text_size=tsz, text_halign=text.align_left)
table.cell(tb, 1, 1, str.tostring(score, "#"), text_color=color.black, bgcolor=scoreCol, text_size=tsz, text_halign=text.align_center)
if compact
f_row(2, "Ext (ATR > 50MA)", na(extATR) ? "n/a" : str.tostring(extATR, "#.#"), extCol)
f_row(3, "Market " + benchSym, mktWeak ? "WEAK" : "OK", mktWeak ? color.orange : color.lime)
table.cell(tb, 0, 4, "STATUS", text_color=color.white, text_size=tsz, text_halign=text.align_left)
table.cell(tb, 1, 4, statusTxt, text_color=color.black, bgcolor=statusCol, text_size=tsz, text_halign=text.align_center)
else
f_row(2, "RS rating", str.tostring(rsComp, "#") + " (" + str.tostring(rsWeighted, "#.##") + "x)", color.from_gradient(rsComp, 30, 90, color.red, color.lime))
f_row(3, "RS vs 52w high", str.tostring((rsDist - 1) * 100, "#.#") + "%", color.from_gradient(rsHighComp, 30, 90, color.red, color.lime))
f_row(4, "Down capture", na(downCap) ? "n/a" : str.tostring(downCap, "#.##"), color.from_gradient(resComp, 30, 90, color.red, color.lime))
f_row(5, "Trend template", str.tostring(trendComp, "#") + "/100", color.from_gradient(trendComp, 30, 90, color.red, color.lime))
f_row(6, "U/D volume", str.tostring(udRatio, "#.##"), color.from_gradient(accComp, 30, 90, color.red, color.lime))
f_row(7, "Ext (ATR > 50MA)", na(extATR) ? "n/a" : str.tostring(extATR, "#.#"), extCol)
f_row(8, "Market " + benchSym, mktWeak ? "WEAK" : "OK", mktWeak ? color.orange : color.lime)
f_row(9, "Leader in corr.", leaderCorr ? "YES ⭐" : "no", leaderCorr ? color.yellow : color.gray)
table.cell(tb, 0, 10, "STATUS", text_color=color.white, text_size=tsz, text_halign=text.align_left)
table.cell(tb, 1, 10, statusTxt, text_color=color.black, bgcolor=statusCol, text_size=tsz, text_halign=text.align_center)