本页源码来自 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/
// © yemilgr
//@version=6
indicator("Market Internals Score [MIS]", shorttitle = "MIS", overlay = false)
// ============================================================================
// INPUTS
// ============================================================================
grpData = "Data"
market = input.string("NYSE", "Market", options = ["NYSE", "NASDAQ", "Both"], group = grpData, tooltip = "Both: each market is normalized separately, then averaged 50/50 per component.")
sessRth = input.session("0930-1600", "Regular session (New York time)", group = grpData)
warmMin = input.int(5, "Warm-up after open (minutes)", minval = 0, group = grpData, tooltip = "Bars inside this window are grayed out and alerts are blocked: breadth ratios are unreliable in the first minutes.")
grpNorm = "Normalization (value that maps to ±100)"
tickLen = input.int(5, "TICK EMA length", minval = 1, group = grpNorm)
tickCapNy = input.float(1000, "TICK cap: NYSE", minval = 1, group = grpNorm)
tickCapNq = input.float(1500, "TICK cap: NASDAQ", minval = 1, group = grpNorm)
addCap = input.float(0.5, "ADD ratio cap", minval = 0.01, maxval = 1, step = 0.05, group = grpNorm, tooltip = "(adv − dec) / (adv + dec). 0.5 = a 75/25 breadth day scores 100.")
voldCap = input.float(0.6, "VOLD ratio cap", minval = 0.01, maxval = 1, step = 0.05, group = grpNorm, tooltip = "(upVol − dnVol) / (upVol + dnVol). 0.6 = an 80/20 up-volume day scores 100.")
grpW = "Weights (auto-normalized)"
wTick = input.float(1.0, "Weight: TICK", minval = 0, group = grpW)
wAdd = input.float(1.0, "Weight: ADD", minval = 0, group = grpW)
wVold = input.float(1.0, "Weight: VOLD", minval = 0, group = grpW)
grpVis = "Display & signals"
threshold = input.float(60, "Threshold (±)", minval = 0, maxval = 100, group = grpVis)
neutralBand = input.float(20, "Neutral band (±)", minval = 0, maxval = 100, group = grpVis)
showSignal = input.bool(true, "Show signal line", group = grpVis)
signalLen = input.int(9, "Signal line EMA length", minval = 1, group = grpVis)
showTable = input.bool(true, "Show component table", group = grpVis)
showComps = input.bool(false, "Plot component lines", group = grpVis)
if not timeframe.isintraday
runtime.error("MIS works on intraday timeframes only.")
if wTick + wAdd + wVold <= 0
runtime.error("MIS: at least one component weight must be greater than 0.")
// ============================================================================
// DATA (USI feeds, chart timeframe)
// ============================================================================
// gaps_on: a bar with no feed update is na (dropped and renormalized), not a stale repeat
feed(string sym) => request.security(sym, timeframe.period, close, gaps = barmerge.gaps_on)
tickRawNy = feed("USI:TICK")
tickRawNq = feed("USI:TICKQ")
advNy = feed("USI:ADVN.NY")
decNy = feed("USI:DECL.NY")
advNq = feed("USI:ADVN.NQ")
decNq = feed("USI:DECL.NQ")
upVolNy = feed("USI:UVOL")
dnVolNy = feed("USI:DVOL")
upVolNq = feed("USI:UVOLQ")
dnVolNq = feed("USI:DVOLQ")
// ============================================================================
// SESSION STATE
// ============================================================================
inSession = not na(time(timeframe.period, sessRth, "America/New_York"))
// Trading-day change, computed every bar (RTH-only charts have no gap bar between sessions)
newTradingDay = ta.change(time_tradingday) != 0
var int sessOpen = na
if inSession and (not inSession[1] or newTradingDay)
sessOpen := time
isFirstBar = inSession and time == sessOpen
warm = inSession and time - sessOpen < warmMin * 60000
// EMA that skips na inputs and re-seeds at each session open
sessEma(float src, int len, bool reset) =>
var float e = na
if reset
e := na
if not na(src)
e := na(e) ? src : e + 2.0 / (len + 1) * (src - e)
e
tickEmaNy = sessEma(tickRawNy, tickLen, isFirstBar)
tickEmaNq = sessEma(tickRawNq, tickLen, isFirstBar)
// A bar with no TICK update is dropped like the other feeds, not filled with the held EMA
tickNy = na(tickRawNy) ? na : tickEmaNy
tickNq = na(tickRawNq) ? na : tickEmaNq
// ============================================================================
// COMPONENTS (each clamped to −1..+1)
// ============================================================================
clamp1(float x) => na(x) ? na : math.max(-1.0, math.min(1.0, x))
ratio(float a, float b) => a + b > 0 ? (a - b) / (a + b) : na
// Average of the available values (na-aware)
avg2(float a, float b) => na(a) ? b : na(b) ? a : (a + b) / 2
pick(float ny, float nq) => market == "NYSE" ? ny : market == "NASDAQ" ? nq : avg2(ny, nq)
addRatioNy = ratio(advNy, decNy)
addRatioNq = ratio(advNq, decNq)
voldRatioNy = ratio(upVolNy, dnVolNy)
voldRatioNq = ratio(upVolNq, dnVolNq)
cTick = inSession ? pick(clamp1(tickNy / tickCapNy), clamp1(tickNq / tickCapNq)) : na
cAdd = inSession ? pick(clamp1(addRatioNy / addCap), clamp1(addRatioNq / addCap)) : na
cVold = inSession ? pick(clamp1(voldRatioNy / voldCap), clamp1(voldRatioNq / voldCap)) : na
// ============================================================================
// SCORE (weights renormalized over available components)
// ============================================================================
ew(float c, float w) => na(c) ? 0.0 : w
ewTick = ew(cTick, wTick)
ewAdd = ew(cAdd, wAdd)
ewVold = ew(cVold, wVold)
ewSum = ewTick + ewAdd + ewVold
score = ewSum > 0 ? 100 * (ewTick * nz(cTick) + ewAdd * nz(cAdd) + ewVold * nz(cVold)) / ewSum : na
// Signal line: EMA of the score, reset at each session open
signalEma = sessEma(score, signalLen, isFirstBar)
signal = na(score) ? na : signalEma
// ============================================================================
// SIGNALS (blocked during warm-up)
// ============================================================================
// Crosses are measured against the last live (post-warm-up) score of the same session.
// Thresholds start from a neutral baseline, so a level already breached during warm-up
// alerts on the first live bar; zero crosses need a previous live bar.
live = not warm and not na(score) and not isFirstBar
var float lastLive = na
if isFirstBar
lastLive := na
prevLive = lastLive
bullCross = live and score > threshold and nz(prevLive) <= threshold
bearCross = live and score < -threshold and nz(prevLive) >= -threshold
zeroUp = live and not na(prevLive) and score > 0 and prevLive <= 0
zeroDown = live and not na(prevLive) and score < 0 and prevLive >= 0
if live
lastLive := score
// ============================================================================
// VISUALS
// ============================================================================
cBlue = #0066ff
cCyan = #00ffff
cMaroon = #990033
cRed = #ff1744
cGray = #1e1e1e
cWhite = #ffffff
cWarm = color.new(color.gray, 50)
prevScore = isFirstBar ? 0.0 : nz(score[1])
rising = score >= prevScore
histColor = warm ? cWarm : score >= 0 ? (rising ? cCyan : cBlue) : (rising ? cMaroon : cRed)
plot(score, "Score", histColor, style = plot.style_columns)
plot(showSignal ? signal : na, "Signal", color.new(color.orange, 0), linewidth = 2)
plot(showComps and not na(cTick) ? cTick * 100 : na, "TICK component", color.yellow, display = display.pane)
plot(showComps and not na(cAdd) ? cAdd * 100 : na, "ADD component", color.fuchsia, display = display.pane)
plot(showComps and not na(cVold) ? cVold * 100 : na, "VOLD component", color.lime, display = display.pane)
hline(0, "Zero", color = color.new(color.gray, 50))
hBullT = hline(threshold, "Bull threshold", color = cCyan, linestyle = hline.style_dashed)
hBearT = hline(-threshold, "Bear threshold", color = cRed, linestyle = hline.style_dashed)
hNeuUp = hline(neutralBand, "Neutral band top", color = color.new(color.gray, 85), linestyle = hline.style_dotted)
hNeuDn = hline(-neutralBand, "Neutral band bottom", color = color.new(color.gray, 85), linestyle = hline.style_dotted)
fill(hNeuUp, hNeuDn, color.new(color.gray, 92), "Neutral band")
// ============================================================================
// COMPONENT TABLE
// ============================================================================
var table t = table.new(position.top_right, 4, 4, bgcolor = cGray, border_width = 1, border_color = color.new(cBlue, 50))
fmt(float x, string f, string suffix) => na(x) ? "n/a" : str.tostring(x, f) + suffix
fmtRaw(float ny, float nq, string f, string suffix) =>
market == "NYSE" ? fmt(ny, f, suffix) : market == "NASDAQ" ? fmt(nq, f, suffix) : fmt(ny, f, suffix) + " / " + fmt(nq, f, suffix)
compColor(float c) => na(c) ? color.gray : c > 0 ? cCyan : c < 0 ? cRed : cWhite
row(int r, string name, string raw, float c, float w) =>
t.cell(0, r, name, text_color = cWhite, text_size = size.small, text_halign = text.align_left)
t.cell(1, r, raw, text_color = cWhite, text_size = size.small)
t.cell(2, r, na(c) ? "n/a" : str.tostring(c * 100, "#"), text_color = compColor(c), text_size = size.small)
t.cell(3, r, ewSum > 0 ? str.tostring(w / ewSum * 100, "#") + "%" : "–", text_color = cWhite, text_size = size.small)
if showTable and barstate.islast
state = not inSession ? "CLOSED" : warm ? "WARM-UP" : na(score) ? "NO DATA" : math.abs(score) <= neutralBand ? "NEUTRAL" : score > 0 ? "BULL" : "BEAR"
stateColor = not inSession or warm or na(score) or math.abs(score) <= neutralBand ? color.gray : score > 0 ? cCyan : cRed
t.cell(0, 0, "MIS " + market, text_color = cWhite, text_size = size.small, text_halign = text.align_left)
t.cell(1, 0, state, text_color = stateColor, text_size = size.small)
t.cell(2, 0, na(score) ? "–" : str.tostring(score, "#"), text_color = compColor(score), text_size = size.small)
t.cell(3, 0, "Wt", text_color = cWhite, text_size = size.small)
row(1, "TICK (EMA)", fmtRaw(tickNy, tickNq, "#", ""), cTick, ewTick)
row(2, "ADD ratio", fmtRaw(addRatioNy * 100, addRatioNq * 100, "#", "%"), cAdd, ewAdd)
row(3, "VOLD ratio", fmtRaw(voldRatioNy * 100, voldRatioNq * 100, "#", "%"), cVold, ewVold)
// ============================================================================
// ALERTS (use "Once Per Bar Close")
// ============================================================================
alertcondition(bullCross, "MIS bullish threshold", '{{ticker}}: Market internals score {{plot("Score")}} is ABOVE the bullish threshold (broad buying)')
alertcondition(bearCross, "MIS bearish threshold", '{{ticker}}: Market internals score {{plot("Score")}} is BELOW the bearish threshold (broad selling)')
alertcondition(zeroUp, "MIS zero cross up", '{{ticker}}: Market internals score crossed above zero ({{plot("Score")}})')
alertcondition(zeroDown, "MIS zero cross down", '{{ticker}}: Market internals score crossed below zero ({{plot("Score")}})')