本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("TPC Market + Sector Alignment", shorttitle="TPC Sector Alignment", overlay=true, dynamic_requests=true)
// TPC TRADES | Plan your trade. Trade your plan.
// LIVE version: current price / VWAP / EMAs, without a previous-bar offset.
// Indicators recalculate when the host chart receives a price update.
// All supported time-based chart intervals are retained; blank TF follows chart.
// Developing readings can change before the candle closes (repainting).
// No future-looking values are requested: every request uses lookahead_off.
// Historical HTF values cannot reproduce every intrabar live fluctuation.
// Actual feed delays / entitlements are controlled by TradingView, not this code.
// All rows use the same data session. Chart follows the chart session setting.
// In Extended mode, open/VWAP are anchored to the requested trading day session.
// Daily and higher feeds may exclude extended-hours trades.
// Sector ETF is matched to the stock automatically; a manual override remains.
// SPY / QQQ appear only for verified equity members of the dated holdings lists.
// Sector classifications: ITOT 2026-10-14, Select Sector SPDR 2026-10-15.
// SPY / QQQ membership: 2026-10-15. Lists are embedded, not a live holdings feed.
// Recreate old alerts after updating. For live alerts choose Once Per Bar.
// This is context only. Your entry, invalidation and risk rules still apply.
const string TZ = "America/New_York"
const string RTH = "0930-1600:23456"
const string G1 = "Comparison"
const string G2 = "Sector / industry ETF"
const string G3 = "Dashboard"
string tfInput = input.timeframe("", "Comparison timeframe (blank = chart)", group=G1, tooltip="Blank follows every chart timeframe. If a selected comparison is below the chart, the script uses the chart timeframe instead. Example: a saved 10m setting on a daily chart uses daily readings.")
string ruleInput = input.string("Auto", "Direction rule", options=["Auto", "RTH open + VWAP", "RTH open only", "VWAP only", "Candle open", "EMA trend"], group=G1, tooltip="Auto uses RTH open + VWAP below 390 minutes and the higher-timeframe rule otherwise. Session VWAP rules also use that fallback on longer timeframes.")
string higherTFRule = input.string("EMA trend", "Higher-timeframe rule", options=["EMA trend", "Candle open"], group=G1, tooltip="EMA trend: bullish when price > fast EMA > slow EMA; bearish when price < fast EMA < slow EMA. Candle open: current price versus the current candle's open. All readings use the current developing bar.")
float bufferPct = input.float(0.0, "Neutral buffer (%)", minval=0.0, maxval=5.0, step=0.01, group=G1, tooltip="0.02 means 0.02%, not 2%. Price must clear each reference by this amount. EMA trend applies the buffer to price versus the fast EMA.")
int fastLen = input.int(9, "Fast EMA length", minval=1, maxval=200, group=G1)
int slowLen = input.int(21, "Slow EMA length", minval=2, maxval=500, group=G1)
string sessionInput = input.string("Chart", "Data session", options=["Chart", "Regular", "Extended"], group=G1, tooltip="Chart follows the chart session setting. All displayed symbols use the same session selection. In Extended mode the intraday open/VWAP use that session, including available pre/post-market trades. Daily and higher data may remain regular-session only.")
bool alertsRTHOnly = input.bool(true, "Intraday alerts only during RTH", group=G1, tooltip="Controls alerts only; the dashboard stays visible. Daily and higher comparison timeframes are exempt. RTH: 09:30-16:00 New York, weekdays.")
string sectorPreset = input.string("Auto", "Sector ETF match", options=["Auto", "XLK - Technology", "XLY - Consumer discretionary", "XLC - Communication services", "XLF - Financials", "XLV - Health care", "XLE - Energy", "XLI - Industrials", "XLB - Materials", "XLU - Utilities", "XLP - Consumer staples", "XLRE - Real estate", "SMH - Semiconductors (industry)", "Custom"], group=G2, tooltip="Auto looks up the chart stock in a verified sector classification list, with conservative metadata fallbacks. Unmatched stocks require a manual selection. SMH is an industry ETF. Published holdings lists are dated and do not update themselves.")
bool showApplicableIndices = input.bool(true, "Show SPY / QQQ only for verified members", group=G2, tooltip="Only names in the embedded 2026-10-15 equity holdings lists get these index rows. Nasdaq listing alone does not qualify. Disable for a stock + sector ETF panel only. Hidden indexes never enter the alignment score.")
string customSector = input.symbol("AMEX:XLK", "Custom ETF (used only for Custom)", group=G2)
string panelLocation = input.string("Top right", "Panel position", options=["Top right", "Top left", "Bottom right", "Bottom left"], group=G3)
bool compactPanel = input.bool(true, "Compact dashboard", group=G3, tooltip="Smaller 4-column panel with tiny text. Price, direction, sector and applicable index rows stay visible. Hover direction cells for open/VWAP/EMA details. Turn off for the full layout.")
string fontInput = input.string("Tiny", "Text size", options=["Tiny", "Small", "Normal", "Large"], group=G3)
bool whiteTheme = input.bool(false, "White background", group=G3)
bool showPanel = input.bool(true, "Show dashboard", group=G3)
if barstate.isfirst and timeframe.isticks
runtime.error("Use a time-based chart: seconds, minutes, hours, days, weeks or months.")
string requestedTF = tfInput == "" ? timeframe.period : tfInput
float chartSeconds = timeframe.in_seconds()
float requestedSeconds = timeframe.in_seconds(requestedTF)
bool useChartFallback = requestedSeconds < chartSeconds
string comparisonTF = useChartFallback ? timeframe.period : requestedTF
float comparisonSeconds = timeframe.in_seconds(comparisonTF)
bool sessionCompatible = comparisonSeconds < 23400
bool requestedVWAP = ruleInput == "RTH open + VWAP" or ruleInput == "VWAP only"
string rule = ruleInput == "Auto" ? (sessionCompatible ? "RTH open + VWAP" : higherTFRule) : not sessionCompatible and requestedVWAP ? higherTFRule : not sessionCompatible and ruleInput == "RTH open only" ? "Candle open" : ruleInput
bool useSessionOpen = sessionCompatible and rule != "Candle open"
bool showVWAP = sessionCompatible and rule != "EMA trend" and rule != "Candle open"
string dataSession = sessionInput == "Chart" ? (syminfo.session == session.extended ? session.extended : session.regular) : sessionInput == "Extended" ? session.extended : session.regular
bool extendedHours = dataSession == session.extended
string sessionLabel = extendedHours ? "EXTENDED" : "REGULAR"
string ruleDisplay = extendedHours ? str.replace_all(rule, "RTH", "Session") : rule
if barstate.isfirst and rule == "EMA trend" and fastLen >= slowLen
runtime.error("Fast EMA length must be smaller than slow EMA length.")
f_tfLabel(string value) =>
na(str.tonumber(value)) ? value : value + "m"
string comparisonLabel = f_tfLabel(comparisonTF)
string openHeading = useSessionOpen ? (extendedHours ? "FROM SESSION OPEN" : "FROM RTH OPEN") : "FROM BAR OPEN"
string referenceHeading = showVWAP ? "VS VWAP" : "VS EMA " + str.tostring(fastLen)
// Published issuer data for lookup. These are classifications, not trade signals.
// SSGA: https://www.ssga.com/library-content/products/fund-data/etfs/us/holdings-daily-us-en-spy.xlsx
// ITOT: https://www.ishares.com/us/products/239724/ishares-core-s-p-total-u-s-stock-market-etf/latest-holdings.csv
// QQQ: https://dng-api.invesco.com/cache/v1/accounts/en_US/shareclasses/QQQ/holdings/fund?idType=ticker&interval=monthly&productType=ETF
const string MEMBERSHIP_DATE = "2026-10-15"
const string SECTOR_XLK = "AAOI,AAPL,ACIW,ACLS,ACMR,ACN,ADBE,ADEA,ADI,ADIG,ADSK,ADTN,AEHR,AEIS,AEVA,AGYS,AI,AIOT,AIP,AKAM,ALAB,ALGM,ALKT,ALRM,AMAT,AMBA,AMBQ,AMD,AMKR,AMPL,ANET,AOSL,APH,APLD,APPF,APPN,APPS,ARLO,ARW,ASAN,ATEN,AUR,AVGO,AVNW,AVPT,AVT,AXTI,BBAI,BDC,BELFB,BHE,BILL,BL,BLKB,BLND,BLZE,BMI,BMNR,BOX,BRZE,BSY,BTBT,CALX,CBRS,CCC,CCSI,CDNS,CDW,CEVA,CGNX,CIEN,CIFR,CLSK,CMRC,CNXN,COHR,COHU,CORZ,CRCL,CRDO,CRM,CRNC,CRSR,CRUS,CRWD,CRWV,CSCO,CSQR,CTS,CTSH,CVLT,CXM,CXT,DAKT,DBD,DBX,DDOG,DELL,DGII,DIOD,DJCO,DLB,DOCN,DOCU,DT,DVLT,DXC,EFOR,EGHT,ENPH,ENTG,EPAM,ESTC,EVLV,EXTR,FEIM,FFIV,FICO,FIG,FIVN,FLEX,FN,FORM,FRSH,FSLR,FSLY,FTNT,GDDY,GDYN,GEN,GLW,GPGI,GTLB,GWRE,HCKT,HLIT,HPE,HPQ,HUBS,HUT,IBM,ICHR,IDCC,IIIV,IMMR,INDI,INFQ,INGM,INTA,INTC,INTU,IOND,IONQ,IOT,IPGP,IT,ITRI,JBL,KD,KE,KEEL,KEYS,KLAC,KLIC,KN,KODK,KOPN,KVYO,LASR,LFUS,LIF,LITE,LPTH,LRCX,LSCC,LWLG,MANH,MARA,MCHP,MDB,MEI,MIR,MITK,MKSI,MPTI,MPWR,MRV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X,NVDA,NXPI,ODFL,ORLY,PANW,PAYX,PCAR,PDD,PEP,PLTR,PYPL,QCOM,REGN,RKLB,ROP,ROST,SBUX,SHOP,SNDK,SNPS,SPCX,STX,TER,TMUS,TRI,TSLA,TTWO,TXN,VRTX,WDAY,WDC,WMT,XEL"
f_key(string symbol) =>
array<string> pieces = str.split(symbol, ":")
string base = array.get(pieces, array.size(pieces) - 1)
str.replace_all(str.replace_all(str.replace_all(str.replace_all(str.upper(base), ".", ""), "-", ""), "_", ""), " ", "")
f_contains(string members, string key) =>
str.contains("," + members + ",", "," + key + ",")
f_lookupETF(string key) =>
switch
f_contains(SECTOR_XLK, key) => "AMEX:XLK"
f_contains(SECTOR_XLY, key) => "AMEX:XLY"
f_contains(SECTOR_XLC, key) => "AMEX:XLC"
f_contains(SECTOR_XLF, key) => "AMEX:XLF"
f_contains(SECTOR_XLV, key) => "AMEX:XLV"
f_contains(SECTOR_XLE, key) => "AMEX:XLE"
f_contains(SECTOR_XLI, key) => "AMEX:XLI"
f_contains(SECTOR_XLB, key) => "AMEX:XLB"
f_contains(SECTOR_XLU, key) => "AMEX:XLU"
f_contains(SECTOR_XLP, key) => "AMEX:XLP"
f_contains(SECTOR_XLRE, key) => "AMEX:XLRE"
=> ""
// A conservative fallback for clear classifications outside the stock list.
// A proxy does not mean the stock is an actual holding of that sector ETF.
f_metadataProxy() =>
string sec = na(syminfo.sector) ? "" : str.lower(syminfo.sector)
string ind = na(syminfo.industry) ? "" : str.lower(syminfo.industry)
switch
str.contains(ind, "semiconductor") => "AMEX:XLK"
str.contains(ind, "internet retail") => "AMEX:XLY"
str.contains(ind, "real estate investment trust") or str.contains(ind, "reit") => "AMEX:XLRE"
sec == "health technology" or sec == "health services" => "AMEX:XLV"
sec == "energy minerals" => "AMEX:XLE"
sec == "utilities" => "AMEX:XLU"
sec == "consumer durables" => "AMEX:XLY"
sec == "finance" => "AMEX:XLF"
=> ""
f_sectorName(string etf) =>
switch etf
"AMEX:XLK" => "Information Technology"
"AMEX:XLY" => "Consumer Discretionary"
"AMEX:XLC" => "Communication Services"
"AMEX:XLF" => "Financials"
"AMEX:XLV" => "Health Care"
"AMEX:XLE" => "Energy"
"AMEX:XLI" => "Industrials"
"AMEX:XLB" => "Materials"
"AMEX:XLU" => "Utilities"
"AMEX:XLP" => "Consumer Staples"
"AMEX:XLRE" => "Real Estate"
=> na(syminfo.sector) or syminfo.sector == "" ? "Not available" : syminfo.sector
var string tickerKey = f_key(syminfo.ticker)
var bool usListing = syminfo.prefix == "NASDAQ" or syminfo.prefix == "NYSE" or syminfo.prefix == "AMEX" or syminfo.prefix == "BATS"
var bool eligibleStock = usListing and (syminfo.type == "stock" or syminfo.type == "dr")
var string verifiedETF = eligibleStock ? f_lookupETF(tickerKey) : ""
var string automaticETF = verifiedETF != "" ? verifiedETF : (eligibleStock ? f_metadataProxy() : "")
var bool memberSPY = eligibleStock and f_contains(SPY_MEMBERS, tickerKey)
var bool memberQQQ = eligibleStock and f_contains(QQQ_MEMBERS, tickerKey)
string manualSectorSymbol = switch sectorPreset
"XLK - Technology" => "AMEX:XLK"
"XLY - Consumer discretionary" => "AMEX:XLY"
"XLC - Communication services" => "AMEX:XLC"
"XLF - Financials" => "AMEX:XLF"
"XLV - Health care" => "AMEX:XLV"
"XLE - Energy" => "AMEX:XLE"
"XLI - Industrials" => "AMEX:XLI"
"XLB - Materials" => "AMEX:XLB"
"XLU - Utilities" => "AMEX:XLU"
"XLP - Consumer staples" => "AMEX:XLP"
"XLRE - Real estate" => "AMEX:XLRE"
"SMH - Semiconductors (industry)" => "NASDAQ:SMH"
=> customSector
string sectorSymbol = sectorPreset == "Auto" ? automaticETF : manualSectorSymbol
bool hasSector = sectorSymbol != ""
string mappingMethod = sectorPreset != "Auto" ? "MANUAL" : verifiedETF != "" ? "AUTO" : automaticETF != "" ? "METADATA PROXY" : "NO MATCH"
f_name(string symbol) =>
array<string> pieces = str.split(symbol, ":")
array.get(pieces, array.size(pieces) - 1)
// Standard prices, even if the host chart uses a synthetic candle type.
// Standard time-based candles are recommended for trading decisions.
string chartSymbol = ticker.standard(syminfo.tickerid)
string spySymbol = "AMEX:SPY"
string qqqSymbol = "NASDAQ:QQQ"
sectorSymbol := hasSector ? ticker.standard(sectorSymbol) : ""
string chartData = ticker.modify(chartSymbol, session=dataSession)
string spyData = ticker.modify(spySymbol, session=dataSession)
string qqqData = ticker.modify(qqqSymbol, session=dataSession)
string sectorData = hasSector ? ticker.modify(sectorSymbol, session=dataSession) : chartData
// TradingView sector/industry names can differ from ETF-provider categories.
// Display the actual chart symbol's labels rather than inferring from the ETF.
f_metadata(string value) =>
na(value) or str.length(str.trim(value)) == 0 ? "Not available" : value
string stockSector = verifiedETF != "" ? f_sectorName(verifiedETF) : f_metadata(syminfo.sector)
string stockIndustry = f_metadata(syminfo.industry)
string comparisonETF = hasSector ? f_name(sectorSymbol) : "NO MATCH"
f_direction(float price, float sessionOpen, float vw, float fast, float slow) =>
float b = bufferPct / 100.0
bool ready = switch rule
"RTH open + VWAP" => not na(price) and not na(sessionOpen) and not na(vw)
"RTH open only" => not na(price) and not na(sessionOpen)
"Candle open" => not na(price) and not na(sessionOpen)
"VWAP only" => not na(price) and not na(vw)
=> not na(price) and not na(fast) and not na(slow)
bool up = switch rule
"RTH open + VWAP" => price > sessionOpen * (1 + b) and price > vw * (1 + b)
"RTH open only" => price > sessionOpen * (1 + b)
"Candle open" => price > sessionOpen * (1 + b)
"VWAP only" => price > vw * (1 + b)
=> price > fast * (1 + b) and fast > slow
bool down = switch rule
"RTH open + VWAP" => price < sessionOpen * (1 - b) and price < vw * (1 - b)
"RTH open only" => price < sessionOpen * (1 - b)
"Candle open" => price < sessionOpen * (1 - b)
"VWAP only" => price < vw * (1 - b)
=> price < fast * (1 - b) and fast < slow
ready ? (up ? 1 : down ? -1 : 0) : int(na)
f_payload() =>
// Evaluated independently in each symbol and selected session.
bool reset = timeframe.change("1D") or barstate.isfirst
float sessionOpen = ta.valuewhen(reset, open, 0)
float vw = ta.vwap(hlc3, reset)
float fast = ta.ema(close, fastLen)
float slow = ta.ema(close, slowLen)
float openReference = useSessionOpen ? sessionOpen : open
float secondReference = showVWAP ? vw : fast
int direction = f_direction(close, openReference, vw, fast, slow)
[direction, close, openReference, secondReference, time, time_close, fast, slow]
[td, tp, tOpen, tv, tStart, tEnd, tf, ts] = request.security(chartData, comparisonTF, f_payload(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
[sd, sp, so, sv, sStart, sEnd, sf, ss] = request.security(spyData, comparisonTF, f_payload(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
[qd, qp, qo, qv, qStart, qEnd, qf, qs] = request.security(qqqData, comparisonTF, f_payload(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
[ed, ep, eo, ev, eStart, eEnd, ef, es] = request.security(sectorData, comparisonTF, f_payload(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
// Compare bar START / END identifiers, not a future close timestamp to bar time.
// The old close-time gate would reject the current developing candle.
bool tickerReady = not na(td) and not na(tp) and not na(tStart)
bool spyReady = tickerReady and not na(sd) and sStart == tStart and sEnd == tEnd
bool qqqReady = tickerReady and not na(qd) and qStart == tStart and qEnd == tEnd
bool sectorReady = hasSector and tickerReady and not na(ed) and eStart == tStart and eEnd == tEnd
// These clocks describe when the selected US equity session is active.
// They are not an exchange-quote timestamp or a feed-delay detector.
int nowMinutes = hour(timenow, TZ) * 60 + minute(timenow, TZ)
int nowDay = dayofweek(timenow, TZ)
bool weekdayNow = nowDay >= dayofweek.monday and nowDay <= dayofweek.friday
bool rthNow = weekdayNow and nowMinutes >= 570 and nowMinutes < 960
bool extendedNow = weekdayNow and nowMinutes >= 240 and nowMinutes < 1200
bool sessionNow = comparisonSeconds >= 86400 ? rthNow : (extendedHours ? extendedNow : rthNow)
bool activeData = barstate.isrealtime and tickerReady and sessionNow and not na(tEnd) and timenow >= tStart and timenow < tEnd
bool alertSessionOK = comparisonSeconds >= 86400 or not alertsRTHOnly or rthNow
string liveBadge = activeData ? "DEVELOPING" : "LAST AVAILABLE DATA"
// Display duplicate symbols but count each distinct external peer only once.
bool useSpy = showApplicableIndices and memberSPY and tickerKey != "SPY" and (not hasSector or f_key(sectorSymbol) != "SPY")
bool useQqq = showApplicableIndices and memberQQQ and tickerKey != "QQQ" and (not hasSector or f_key(sectorSymbol) != "QQQ")
bool useSector = hasSector and f_key(sectorSymbol) != tickerKey
int peerCount = (useSpy ? 1 : 0) + (useQqq ? 1 : 0) + (useSector ? 1 : 0)
int available = (useSpy and spyReady ? 1 : 0) + (useQqq and qqqReady ? 1 : 0) + (useSector and sectorReady ? 1 : 0)
bool allData = tickerReady and useSector and available == peerCount
int supporting = (useSpy and spyReady and td != 0 and sd == td ? 1 : 0) + (useQqq and qqqReady and td != 0 and qd == td ? 1 : 0) + (useSector and sectorReady and td != 0 and ed == td ? 1 : 0)
int opposing = (useSpy and spyReady and td != 0 and sd == -td ? 1 : 0) + (useQqq and qqqReady and td != 0 and qd == -td ? 1 : 0) + (useSector and sectorReady and td != 0 and ed == -td ? 1 : 0)
bool fullBull = allData and td == 1 and supporting == peerCount
bool fullBear = allData and td == -1 and supporting == peerCount
bool conflict = allData and td != 0 and opposing > 0
bool fullAligned = fullBull or fullBear
color green = #00C853
color red = #F23645
color amber = #E5A51A
color neutral = #7B8493
color page = whiteTheme ? #FFFFFF : #101319
color ink = whiteTheme ? #141821 : #F3F5F7
color muted = whiteTheme ? #5C6470 : #AEB6C3
color header = whiteTheme ? #E9EDF2 : #202632
color grid = whiteTheme ? #D5DAE2 : #343D4A
string fullFontSize = switch fontInput
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
string fontSize = compactPanel ? size.tiny : fullFontSize
string panelPosition = switch panelLocation
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
f_pct(float price, float reference) =>
float changePct = na(price) or na(reference) or reference == 0 ? na : (price / reference - 1) * 100
na(changePct) ? "N/A" : (changePct > 0 ? "+" : "") + str.tostring(changePct, "0.00") + "%"
f_row(table panel, int row, string name, bool ready, int direction, float price, float openReference, float metricReference, float fast, float slow, bool reference, bool counted) =>
color stateColor = not ready ? neutral : direction == 1 ? green : direction == -1 ? red : amber
string stateText = not ready ? "WAIT / N/A" : direction == 1 ? "BULLISH" : direction == -1 ? "BEARISH" : "NEUTRAL"
string matchText = reference ? "REFERENCE" : not counted ? "DUPLICATE" : not ready ? "WAIT / N/A" : td == 0 or direction == 0 ? "NEUTRAL" : direction == td ? "SUPPORT" : "CONFLICT"
color matchColor = matchText == "SUPPORT" ? green : matchText == "CONFLICT" ? red : muted
string rowName = compactPanel ? str.replace_all(str.replace_all(name, " (sector)", ""), " (member)", "") : name
string priceText = na(price) ? "--" : str.tostring(price, "#.####")
string shortState = not ready ? "WAIT" : direction == 1 ? "BULL" : direction == -1 ? "BEAR" : "NEUT"
string shortMatch = reference ? "--" : not counted ? "DUP" : not ready ? "WAIT" : td == 0 or direction == 0 ? "NEUT" : direction == td ? "YES" : "NO"
string tip = "Rule: " + ruleDisplay + " | " + openHeading + ": " + f_pct(price, openReference) + " | " + referenceHeading + ": " + f_pct(price, metricReference) + " | Fast EMA: " + str.tostring(fast, "#.####") + " | Slow EMA: " + str.tostring(slow, "#.####") + " | Developing readings can change before close."
table.cell(panel, 0, row, rowName, text_color=ink, bgcolor=page, text_size=fontSize, tooltip=name)
table.cell(panel, 1, row, priceText, text_color=ink, bgcolor=page, text_size=fontSize, tooltip="Latest price returned by TradingView. Feed delays and permissions still apply.")
table.cell(panel, 2, row, compactPanel ? shortState : stateText, text_color=stateColor, bgcolor=color.new(stateColor, whiteTheme ? 92 : 86), text_size=fontSize, tooltip=tip)
if compactPanel
table.cell(panel, 3, row, shortMatch, text_color=matchColor, bgcolor=page, text_size=fontSize, tooltip="Versus chart ticker: " + matchText + ". YES supports; NO conflicts; NEUT is neutral. " + tip)
else
table.cell(panel, 3, row, ready ? f_pct(price, openReference) : "--", text_color=ink, bgcolor=page, text_size=fontSize)
table.cell(panel, 4, row, ready ? f_pct(price, metricReference) : "--", text_color=ink, bgcolor=page, text_size=fontSize)
table.cell(panel, 5, row, matchText, text_color=matchColor, bgcolor=page, text_size=fontSize)
// Compact layout: 4 columns, 6-9 rows. Full layout: 6 columns, 11-14 rows.
// Row count depends only on which sector / index peers apply to the ticker.
int panelColumns = compactPanel ? 4 : 6
int lastColumn = panelColumns - 1
int tickerRow = compactPanel ? 3 : 5
int summaryRow = tickerRow + 1 + peerCount
int finalRow = summaryRow + (compactPanel ? 1 : 4)
var table dashboard = table.new(panelPosition, panelColumns, finalRow + 1, bgcolor=page, frame_color=grid, frame_width=1, border_color=grid, border_width=compactPanel ? 0 : 1)
if barstate.isfirst
for row = 0 to (compactPanel ? 1 : 3)
table.merge_cells(dashboard, 0, row, lastColumn, row)
for row = summaryRow to finalRow
table.merge_cells(dashboard, 0, row, lastColumn, row)
string summary = not useSector ? "SELECT A SECTOR ETF - no automatic match / same ticker" : not tickerReady ? "WAIT - price / indicator data" : not allData ? "WAIT - missing or unsynced peer data" : fullBull ? "BULLISH ALIGNMENT" : fullBear ? "BEARISH ALIGNMENT" : td == 0 ? "TICKER NEUTRAL" : conflict ? "CONFLICTING CONDITIONS" : "PARTIAL ALIGNMENT"
color summaryColor = fullBull ? green : fullBear or conflict ? red : amber
string countText = not allData ? "Available peers: " + str.tostring(available) + "/" + str.tostring(peerCount) : td == 0 ? "Ticker neutral | Available peers: " + str.tostring(available) + "/" + str.tostring(peerCount) : "Support " + str.tostring(supporting) + "/" + str.tostring(peerCount) + " | Oppose " + str.tostring(opposing) + " | Neutral " + str.tostring(peerCount - supporting - opposing)
string asOf = barstate.isrealtime ? "Chart update received: " + str.format_time(timenow, "HH:mm:ss", "America/Chicago") + " CT" : "HISTORICAL / CLOSED MARKET - last available values"
string shortSummary = not useSector ? "SET SECTOR ETF" : not tickerReady ? "WAIT: DATA" : not allData ? "WAIT: PEERS" : fullBull ? "BULL ALIGN " + str.tostring(supporting) + "/" + str.tostring(peerCount) : fullBear ? "BEAR ALIGN " + str.tostring(supporting) + "/" + str.tostring(peerCount) : td == 0 ? "TICKER NEUTRAL" : conflict ? "CONFLICT " + str.tostring(opposing) + "/" + str.tostring(peerCount) : "PARTIAL " + str.tostring(supporting) + "/" + str.tostring(peerCount)
string mapTip = "Sector data: ITOT Oct 14 and Select Sector SPDR Oct 15, 2026. SPY / QQQ membership: " + MEMBERSHIP_DATE + ". Embedded lists do not auto-refresh. " + mappingMethod + " ETF: " + comparisonETF + ". Industry: " + stockIndustry + ". A metadata proxy is an inference, not verified ETF ownership."
if barstate.islast
if showPanel
if compactPanel
table.cell(dashboard, 0, 0, "TPC ALIGN | " + comparisonLabel + " | " + (activeData ? "LIVE" : "LAST"), text_color=green, bgcolor=header, text_size=fontSize, tooltip="Live/developing calculations can change before candle close. Rule: " + ruleDisplay + ". " + sessionLabel + ". " + (useChartFallback ? "Comparison uses chart timeframe fallback." : "") + " Data delays follow your TradingView feed.")
table.cell(dashboard, 0, 1, stockSector + " | " + comparisonETF, text_color=ink, bgcolor=page, text_size=fontSize, tooltip=syminfo.ticker + " sector: " + stockSector + ". " + mapTip)
table.cell(dashboard, 0, 2, "TICKER", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 1, 2, "PRICE", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 2, 2, "BIAS", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 3, 2, "MATCH", text_color=ink, bgcolor=header, text_size=fontSize, tooltip="Does the peer support the chart ticker's direction?")
else
table.cell(dashboard, 0, 0, "TPC TRADES | MARKET + SECTOR", text_color=green, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 0, 1, comparisonLabel + " | " + ruleDisplay + " | " + liveBadge + (useChartFallback ? " | CHART TF FALLBACK" : ""), text_color=muted, bgcolor=page, text_size=fontSize)
table.cell(dashboard, 0, 2, syminfo.ticker + " SECTOR: " + stockSector, text_color=ink, bgcolor=header, text_size=fontSize, text_halign=text.align_left, tooltip="Verified sector classification when available; otherwise TradingView metadata. " + mapTip)
table.cell(dashboard, 0, 3, "INDUSTRY: " + stockIndustry, text_color=muted, bgcolor=page, text_size=fontSize, text_halign=text.align_left)
table.cell(dashboard, 0, 4, "ASSET", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 1, 4, "LAST PRICE", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 2, 4, "DIRECTION", text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 3, 4, openHeading, text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 4, 4, referenceHeading, text_color=ink, bgcolor=header, text_size=fontSize)
table.cell(dashboard, 5, 4, "VS TICKER", text_color=ink, bgcolor=header, text_size=fontSize)
f_row(dashboard, tickerRow, syminfo.ticker, tickerReady, td, tp, tOpen, tv, tf, ts, true, true)
int peerRow = tickerRow + 1
if useSector
f_row(dashboard, peerRow, comparisonETF + " (sector)", sectorReady, ed, ep, eo, ev, ef, es, false, true)
peerRow += 1
if useSpy
f_row(dashboard, peerRow, "SPY (member)", spyReady, sd, sp, so, sv, sf, ss, false, true)
peerRow += 1
if useQqq
f_row(dashboard, peerRow, "QQQ (member)", qqqReady, qd, qp, qo, qv, qf, qs, false, true)
table.cell(dashboard, 0, summaryRow, compactPanel ? shortSummary : summary, text_color=summaryColor, bgcolor=color.new(summaryColor, whiteTheme ? 92 : 86), text_size=fontSize, tooltip=summary + ". " + countText + ". Only displayed peers enter the score. This is not a win rate.")
if compactPanel
string shortFooter = (activeData ? str.format_time(timenow, "HH:mm:ss", "America/Chicago") + " CT" : "LAST AVAILABLE") + " | " + (extendedHours ? "EXT" : "RTH")
table.cell(dashboard, 0, finalRow, shortFooter, text_color=muted, bgcolor=page, text_size=fontSize, tooltip=asOf + ". Script update time, not an exchange quote timestamp. " + mapTip + " No trigger, no trade. Your 10m ORB rules still apply.")
else
table.cell(dashboard, 0, summaryRow + 1, countText, text_color=ink, bgcolor=page, text_size=fontSize, tooltip="Only displayed peers enter this count. Index membership date: " + MEMBERSHIP_DATE)
table.cell(dashboard, 0, summaryRow + 2, asOf, text_color=muted, bgcolor=page, text_size=fontSize, tooltip="Script update time, not an exchange quote timestamp. Updates require host-chart ticks.")
string mappingText = hasSector ? "ETF: " + comparisonETF + " | " + mappingMethod + " | " + sessionLabel + " | Map: Oct 14-15, 2026" : "No automatic ETF match. Select a sector ETF in Settings."
table.cell(dashboard, 0, summaryRow + 3, mappingText, text_color=muted, bgcolor=page, text_size=fontSize, tooltip=mapTip)
table.cell(dashboard, 0, finalRow, "No trigger, no trade. Your 10m ORB rules still apply.", text_color=green, bgcolor=header, text_size=fontSize)
else
table.clear(dashboard, 0, 0, lastColumn, finalRow)
// Intrabar state memory catches live changes without waiting for a new bar.
// varip survives Pine's intrabar rollback. Reloading loses tick-level history.
int currentState = not allData ? 0 : fullBull ? 1 : fullBear ? -1 : conflict ? 2 : td == 0 ? 3 : 4
varip int previousState = na
bool stateChanged = not na(previousState) and currentState != previousState
bool allowLiveAlert = activeData and alertSessionOK and allData
bool newBull = allowLiveAlert and stateChanged and currentState == 1
bool newBear = allowLiveAlert and stateChanged and currentState == -1
bool newConflict = allowLiveAlert and stateChanged and currentState == 2
bool lostAlignment = allowLiveAlert and stateChanged and math.abs(previousState) == 1 and not fullAligned
alertcondition(newBull, "TPC - Bullish alignment", "{{ticker}}: LIVE bullish alignment across the ticker and all unique selected market/sector peers. Developing readings can change before candle close. Context only; wait for your entry trigger.")
alertcondition(newBear, "TPC - Bearish alignment", "{{ticker}}: LIVE bearish alignment across the ticker and all unique selected market/sector peers. Developing readings can change before candle close. Context only; wait for your entry trigger.")
alertcondition(newConflict, "TPC - Conflict appeared", "{{ticker}}: LIVE conflict: at least one unique market/sector peer opposes the ticker. Developing readings can change before candle close.")
alertcondition(lostAlignment, "TPC - Alignment lost", "{{ticker}}: full market/sector alignment was lost during the developing candle.")
previousState := currentState