Files
hyperstitionstudio-core/site/quant/quant-app.js
T

1282 lines
74 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// /workspace/hyperstitionstudio-core/site/quant/quant-app.js
// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.17.0)
(function () {
"use strict";
const DATA = (window.HyperstitionStudio && window.HyperstitionStudio.QuantTimeSeries) || null;
if (!DATA) {
console.error("QuantTimeSeries bundle missing.");
return;
}
// Resolve file:// vs https:// navigation links automatically
if (window.location.protocol === "file:") {
const navHome = document.getElementById("navHome");
const navGraph = document.getElementById("navGraph");
const navLearn = document.getElementById("navLearn");
const navCalc = document.getElementById("navCalc");
const navManual = document.getElementById("navManual");
const navDonate = document.getElementById("navDonate");
if (navHome) navHome.href = "../index.html";
if (navGraph) navGraph.href = "../../../encyclopedia-knowledge-graph/index.html";
if (navLearn) navLearn.href = "../learn/index.html";
if (navCalc) navCalc.href = "../../../haiperdohp-jemaytreeah/index.html";
if (navManual) navManual.href = "./OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf";
if (navDonate) navDonate.href = "../donate/index.html";
}
let activeSpotlight = null;
const GLOSSARY_PDF = "/zoology/technocapital-singularity-zoology-comprehensive-glossary.pdf";
const MANUAL_PDF = "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf";
const QUANT_TERM_GLOSSARY = {
guild_filter: {
title: "Guild Filter (ALL / S1–S6)",
plain_english: "Filters the 24 market tickers by their primary technocapital sector ('Guild'): S1 covers AI models and cloud software, S2 covers high-frequency trading and crypto liquidity, S3 covers semiconductor fabs and defense hardware, S4 covers telecom carrier waves, S5 covers biotech/pharma, and S6 covers giant asset managers and banks.",
glossary_quote: "Co-primary coupling between the Machinic Phylum (Classes S1–S5: models, HFT algorithms, EUV fabs, carrier waves, wetware) and Capital Organizational Capture (Class S6).",
glossary_pdf_link: GLOSSARY_PDF + "#page=3&search=Double%20Articulation",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Periodicity"
},
ticker_select: {
title: "Ticker & TradingView Launcher (↗)",
plain_english: "Selects which of the 24 tracked companies or assets to inspect across all four panels. Clicking 'Open TradingView Chart ↗' (or pressing T) opens that asset's live market chart on TradingView in a new browser tab without loading any external tracking scripts on this page.",
glossary_quote: "A tracked real-world financial or industrial figure attached to an S1–S6 entity (lazarus_heist_6b = '$6B' / 'siks bilyan' [211]; anthropic_ipo_price_83 = '$83' [202] -> '$89' [193]).",
glossary_pdf_link: GLOSSARY_PDF + "#page=8&search=Quantitative%20Economic%20Anchor",
manual_pdf_link: MANUAL_PDF + "#page=2&search=TradingView"
},
projection_lens: {
title: "Projection Lens (LENS_REGISTRY)",
plain_english: "Changes the vocabulary used in Panel 3 to describe the exact same six underlying math scores. You can view the readout in plain math terms (Neutral Math), institutional investing terms (Quant Factor), executive governance terms (Corporate Board), ecological tier ratings (TierZoo), fantasy sports stats (Fantasy Sabermetrics), or Pokédex scanner stats.",
glossary_quote: "The analytical gain achieved by reading Gen 0 (stated legal/filing form) and Gen 1 (operational phonemic stream) stereoscopically across Academic, Corporate Board, Out-of-Sample Fund Manager, and Fantasy Football registers.",
glossary_pdf_link: GLOSSARY_PDF + "#page=7&search=Vector%20G6",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
metric_mode: {
title: "Metric Mode (Spoken AQ / USD / BPS / Digit AQ)",
plain_english: "Chooses what the cyan line in the top chart plots over the 30-day timeline: Spoken AQ (Gen 1) scores the spoken English words for the closing price after stripping silent letters; Close Price (USD) plots the raw dollar price; Move (BPS) plots the daily percentage move in basis points (100 bps = 1%); and Digit AQ sums the raw digits of the price.",
glossary_quote: "Continuous Base-36 character-valuation cipher (formulated by Jim Lees in 1976 and adopted by the Ccru) where digits 0–9 map to face values 0–9 and letters A–Z map to 10–35 (case-insensitive; non-alphanumeric symbols = 0).",
glossary_pdf_link: GLOSSARY_PDF + "#page=1&search=Alphanumeric%20Qabbala",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Spoken"
},
entity_threshold: {
title: "Entity Phonemic Threshold (Dashed Crimson Line)",
plain_english: "The horizontal dashed red line marks the numerical score of the company's own name when spelled strictly by how it sounds out loud in Gen 1 Ingglish (for example, Nvidia -> envideea = 137, ASML -> asml = 81). When the cyan curve touches this line, the market price or daily move matches the company's own name.",
glossary_quote: "Deterministic phonemic English orthography backed by the 126,051-word CMU Pronouncing Dictionary (ingglish npm package) that strips silent etymological letters and maps each ARPAbet phoneme to a single invariant spelling.",
glossary_pdf_link: GLOSSARY_PDF + "#page=1&search=Phonemic%20Ingglish",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Crimson"
},
scope1_self_lock: {
title: "Gold Beacon = Scope 1 Self-Lock or Repdigit Attractor",
plain_english: "A glowing gold circle on the curve means a real exchange bar's closing price or daily basis-point move landed on the exact number of the asset's own name (such as Palantir closing at $159.36 -> 159 == palanter) or hit a repeating three-digit number divisible by 37 (such as Broadcom closing at $333.40 -> 333).",
glossary_quote: "Forbids matching quantitative figures to random unrelated dictionary words; counter-substitutions are strictly restricted to: (1) Intra-Instrument Self-Locks (price or bps == entity's own AQ)...",
glossary_pdf_link: GLOSSARY_PDF + "#page=9&search=Contingent%20Repricing%20Scope%20Rule",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Scope%201"
},
scope2_ring_migration: {
title: "Cyan Beacon = Scope 2 Sector Ring Migration",
plain_english: "A cyan dot on the curve means the asset's price, spoken price score, or daily basis-point move landed on one of the 30 core supply-chain coordinates shared across the S1–S6 ecosystem (such as 71, 81, 125, 137, 163, 193, 211, 256, or 292), linking that day's market action to a broader sector hub.",
glossary_quote: "Tracks which S1–S6 equivalence partners a spoken figure exits and enters when repriced (e.g., 'siks bilyan' [211 == wor masheen == koper waier] migrating to 'sevan bilyan' [222 = 6 x 37]).",
glossary_pdf_link: GLOSSARY_PDF + "#page=9&search=Type%202%20Revision",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Scope%202"
},
scope3_wire_copresence: {
title: "Emerald Bar = Scope 3 News-Wire Co-Presence",
plain_english: "In the middle bar chart, bars turn emerald green on days when that specific company was also named in the breaking midnight (00:00 UTC) news wire. This enforces 'The Room Filter': we only flag a high-conviction signal when the news story and the market observation happen on the same day.",
glossary_quote: "'The Room Filter' requires that equated terms co-occur within a contingent historical event, supply chain, or balance sheet before their AQ identity is admitted as a real singularity.",
glossary_pdf_link: GLOSSARY_PDF + "#page=10&search=Room%20Filter",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Scope%203"
},
wire_velocity_bars: {
title: "Wire Eq (00:00 GMT News-Wire Equation Velocity)",
plain_english: "The middle pane's vertical bars count how many verified 333, 666, and 777 phonemic equations were harvested from that day's breaking midnight (00:00 GMT) news dossier. Taller bars indicate heavier cross-scale resonance in the global news cycle on that date.",
glossary_quote: "The three cross-scale target sums of every archive dossier (10 verified equations per scale = 30 per dossier), all governed by the prime generator 37 (3 x 37 = 111).",
glossary_pdf_link: GLOSSARY_PDF + "#page=1&search=Primary%20Repdigit%20Attractors",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Middle%20Pane"
},
vol20d_regimes: {
title: "Vol20d & M1–M3 Thermodynamic Regimes",
plain_english: "The bottom pane plots the day's trading volume relative to its 20-day average (Vol20d) and colors each bar by market regime: Gold (< 0.45x volume) marks M1 supply freezes/halts; Crimson (>= 2.5x volume or <= -5% drop) marks M2 flash-crash surges; and Sky-Blue marks normal M3 large-cap trading.",
glossary_quote: "Methodological rule forbidding global dictionary fishing of horror/mythic tropes into unrelated stories: a memetic subclass M1–M6 may be invoked ONLY when (Gate 1) the news event exhibits the matching real-world thermodynamic state...",
glossary_pdf_link: GLOSSARY_PDF + "#page=5&search=State-Gated%20Inheritance",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Vol20d"
},
heatmap_matrix: {
title: "Panel 2: 24 × 30 Spatiotemporal Lock Heatmap",
plain_english: "A bird's-eye grid showing all 24 tickers (rows) across all 30 November UTC days (columns). Gold cells mark Scope 1 self-locks, cyan cells mark Scope 2 sector ring hits, green outlines mark midnight news-wire co-presence, and striped cells mark closed/unavailable sessions ('No data available').",
glossary_quote: "Shared numerical coordinates through which one singularity guild feeds or captures another across the technocapital food web (e.g., 211 linking S2 HFT, S3 Copper/War Machine, S4 Carrier Wave, and S6 $6B Heist).",
glossary_pdf_link: GLOSSARY_PDF + "#page=8&search=Trophic%20Supply-Chain%20Bridges",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Heatmap"
},
box_close_usd: {
title: "Close USD (Change bps)",
plain_english: "The official 21:30 UTC (4:30 PM EST) US closing-bell price in US dollars for the selected date, alongside the day's percentage move expressed in basis points (100 bps = 1.00%). When the market was closed or no public feed exists, this box explicitly reports 'No data available'.",
glossary_quote: "CLI mode governing numeric tokens: 'off' (default 100% pure lexical/qualitative mode stripping numeric figures), 'spoken' (converting figures to spoken English -> Ingglish), and 'digit' (literal Base-36 digit sum).",
glossary_pdf_link: GLOSSARY_PDF + "#page=9&search=Tri-Modal%20Quantitative%20Handling",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Close"
},
box_spoken_close: {
title: "Spoken Close (Gen 1 AQ)",
plain_english: "Translates the integer dollar closing price into spoken English words, strips silent letters into Gen 1 phonemic Ingglish (for example, $150 -> 'one hundred fifty' -> 'wuhn huhndrad fiftee'), and sums its Base-36 character score.",
glossary_quote: "Tracks which S1–S6 equivalence partners a spoken figure exits and enters when repriced (e.g., 'siks bilyan' [211 == wor masheen == koper waier] migrating to 'sevan bilyan' [222 = 6 x 37]).",
glossary_pdf_link: GLOSSARY_PDF + "#page=9&search=Type%202%20Revision",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Spoken"
},
box_scaled_cap: {
title: "Scaled Cap (Gen 1 AQ)",
plain_english: "Takes the asset's reported market capitalization string (such as '$1.20T' or '$43B'), expands it into spoken phonemic Ingglish, and computes its Base-36 AQ score. If the feed does not report a daily market cap for that ticker, it explicitly states 'No data available'.",
glossary_quote: "Activates under sovereign megaprojects, tech giants, trillion-dollar consolidation, and grid capture. Signature locks: kansorsheea == 189; leevaiathan == 179; monohpolee == 192.",
glossary_pdf_link: GLOSSARY_PDF + "#page=5&search=Subclass%20M3",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Panel%203"
},
box_bps_vol: {
title: "BPS Spoken AQ / Vol20d",
plain_english: "Shows the phonemic Base-36 AQ score of the day's unsigned basis-point move alongside Vol20d (how many times normal 20-day average trading volume changed hands on that date).",
glossary_quote: "Covers microsecond algorithmic order books, flash crashes, fiber-optic latency, derivatives, and crypto ledgers. Signature coordinates: 256 (akselerayshan == hai-freekwansee), 193 (flash krash == anthropik)...",
glossary_pdf_link: GLOSSARY_PDF + "#page=4&search=Class%20S2",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Vol20d"
},
box_active_locks: {
title: "Active Contingent Locks",
plain_english: "Lists every Scope 1 self-lock (where price or move matches the asset's own name or a 37 × k repdigit) and Scope 2 sector ring coordinate (Ring 71, Ring 81, Ring 125, Ring 163, etc.) triggered by real exchange data on the selected date.",
glossary_quote: "The 13 Ingglish AQ coordinates that simultaneously belong to 2–4 distinct Assemblage Builds and act as regime-reallocation pivots: 292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 95, 91, and 81.",
glossary_pdf_link: GLOSSARY_PDF + "#page=7&search=Multi-Build%20Hybrid",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Scope"
},
box_wire_copresent: {
title: "00:00 GMT Wire Co-Present",
plain_english: "Indicates YES (Scope 3 Lock) when the company's name or ticker symbol appeared verbatim in that same UTC date's midnight news-wire dossier (25..71-dossier-news-YYYY-MM-DD.md), confirming real-world news and market co-presence.",
glossary_quote: "'Grand Central Station' names the statistical crowding of 4-to-5-letter Base-36 words in the 65–140 interval; 'The Room Filter' requires that equated terms co-occur within a contingent historical event, supply chain, or balance sheet...",
glossary_pdf_link: GLOSSARY_PDF + "#page=10&search=Grand%20Central%20Station",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Scope%203"
},
lens_archetype: {
title: "Archetype & Tier Classification",
plain_english: "Summarizes the asset's 30-day behavioral profile—whether it acts as a steady 'Ironclad Floor' chokepoint with consistent daily locks or a high-volatility 'Templex Boom/Bust' surge asset—and grades its overall structural score from Tier S+ (Apex) to Tier D (Periphery).",
glossary_quote: "Tier S+ (88–100 ETI, Crimson #FF4D4D: Apex Predator — #1 S1 AI [93], #2 S2 Liquidity [90]); Tier S (80–87 ETI, Coral #FF7F7F: Keystone Dominator — #3 S6 Capture [87], #4 S3 War Machine [83])...",
glossary_pdf_link: GLOSSARY_PDF + "#page=8&search=Zoological%20Ecological%20Tiers",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
ts_duty_cycle_pct: {
title: "Duty Cycle % / SNAP% / Active Signal Rate",
plain_english: "The percentage of available trading days in the window where this ticker fired at least one verified Scope 1/2 coordinate lock or Scope 3 midnight news-wire match. A higher percentage means the asset is consistently active in the signal stream.",
glossary_quote: "Standalone 0–100 zoological grading standard for Technocapital Singularity Taxa & Assemblage Builds, computed as the weighted composite of six normalized base stats: ETI = round(0.20*CAP + 0.18*COL + 0.18*ARM + 0.16*PRM + 0.14*VEL + 0.14*RES).",
glossary_pdf_link: GLOSSARY_PDF + "#page=7&search=Ecological%20Trophic",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
ts_weighted_resonance: {
title: "Weighted Resonance / WOPR",
plain_english: "Combines how often the ticker appears in the midnight news wire (1.5x weight) with its share of volume-weighted price movement on locked days (0.7x weight). It measures whether an asset is driving both headline attention and capital movement at the same time.",
glossary_quote: "Highest-weighted zoological stat (0.20), scoring S[1–5] x S6 Double Articulation, cross-guild trophic bridge count, and G2 Cross-Generation Twin density.",
glossary_pdf_link: GLOSSARY_PDF + "#page=8&search=CAP",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
ts_excess_over_replacement: {
title: "Excess Value Over Baseline / WAR (30d)",
plain_english: "Measures how many more coordinate locks and resonance points this asset produced over its trading sessions compared to a Tier D replacement baseline. Positive values indicate structural outperformance above random numerical noise.",
glossary_quote: "Plain-English Fantasy Football translations of Vector G1 Variance Collapse ('Stack Lock' — when 3+ assets that look different on paper snap onto the exact same number in Ingglish) and Vector G4 Isometric Invariance ('All-Weather Chokepoint').",
glossary_pdf_link: GLOSSARY_PDF + "#page=10&search=Stack%20Lock",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
ts_quantile_profile: {
title: "Quantile Profile (P20 Floor / P90 Ceiling / Boom% / CV)",
plain_english: "Breaks down the distribution of the asset's daily resonance points: P20 is its quiet-day baseline floor, P90 is its peak-day ceiling, Boom% is the share of days with major multi-lock spikes (>= 3.5 pts), and CV (coefficient of variation) measures how spiky versus steady the signal is.",
glossary_quote: "Quantifies a build's concentration of G4 Isometric Fixed Points (Delta = 0 chokepoints like ASML=81, TSMC=91, GPU=71, kapatal=125, charter=136) that remain numerically unperturbed across orthographic regimes.",
glossary_pdf_link: GLOSSARY_PDF + "#page=7&search=ARM",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
ts_optimal_lag_days: {
title: "Optimal Causal Lag τ* (Days)",
plain_english: "The day offset τ* in [-5, +5] where midnight news-wire activity and the ticker's price volatility correlate most strongly. Positive τ* > 0 means news-wire surges lead price volatility by τ* days; τ* = 0 means they move on the same day; negative τ* < 0 means headlines follow after the price move.",
glossary_quote: "Cybernetic runaway (ruhnaway = 183 == tempaleks == laytansee) in which positive feedback (pozativ feedbak = 269 [57th PRIME]) folds future attractor states backward to assemble their own material preconditions.",
glossary_pdf_link: GLOSSARY_PDF + "#page=3&search=Teleoplexy",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Correlation"
},
ts_regime_splits: {
title: "Conditional Regime Splits (M1 / M2 / M3)",
plain_english: "Shows the ticker's average daily resonance delta during M1 supply-freeze days, M2 flash-crash/high-volume surge days, and M3 mega-cap days. If a regime did not occur during the window, its split is reported as null ('No data available').",
glossary_quote: "Lineup/portfolio pivot at 137 [33rd PRIME] (daireeoh == envideea == hawlts == inersha): if a foundry delay or regulatory freeze halts the offensive line, reallocate immediately across the 137 bridge...",
glossary_pdf_link: GLOSSARY_PDF + "#page=10&search=Supply-Halt%20Insurance%20Pivot",
manual_pdf_link: MANUAL_PDF + "#page=2&search=LENS_REGISTRY"
},
lag_correlation_explorer: {
title: "Lead-Lag Cross-Correlation Explorer r(τ)",
plain_english: "This 11-bar chart measures the statistical correlation r(τ) in [-1, +1] between daily midnight news-wire equation counts and the ticker's daily price swing across time shifts from -5 days to +5 days. The gold bar highlights the strongest lead-lag relationship (τ*).",
glossary_quote: "Landian terms for non-linear temporal folding in cybernetic markets: taim-serkat (207 == terbyalans == Gen 0 'infinitive') and tempaleks (183 == ruhnaway == laytansee == dhrakoola).",
glossary_pdf_link: GLOSSARY_PDF + "#page=3&search=Time-Circuit",
manual_pdf_link: MANUAL_PDF + "#page=2&search=Correlation"
},
periodicity_gate_badge: {
title: "Periodicity Gate Enforced",
plain_english: "Confirms that every data point in /quant/ comes strictly from daily timestamped observations (21:30 UTC market close and 00:00 UTC news rollover), with zero undated dictionary lists or static essays mixed into the time-series math.",
glossary_quote: "'The Room Filter' requires that equated terms co-occur within a contingent historical event, supply chain, or balance sheet before their AQ identity is admitted as a real singularity.",
glossary_pdf_link: GLOSSARY_PDF + "#page=10&search=Room%20Filter",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Periodicity"
},
cidv1_provenance: {
title: "IPLD dag-json CIDv1 (baguqeera...)",
plain_english: "A cryptographic content fingerprint (CIDv1) computed over the entire time-series bundle. If even a single price, date, or equation changes by one character, this baguqeera... hash changes—proving the readout you see matches the verified archive byte-for-byte.",
glossary_quote: "Audit requirement that every Ingglish token in a technocapital dossier match unmodified ingglish.translate() output from CMUdict with 0 ad-hoc spelling tweaks.",
glossary_pdf_link: GLOSSARY_PDF + "#page=1&search=CMUdict%20Purity",
manual_pdf_link: MANUAL_PDF + "#page=1&search=Schema"
}
};
function makeInfoIconHtml(termId) {
const entry = QUANT_TERM_GLOSSARY[termId];
const lbl = entry ? ("Explain " + entry.title) : ("Explain " + termId);
return "<button type='button' class='hs-info-icon' data-term-id='" + termId + "' aria-label='" + lbl.replace(/'/g, "&#39;") + "'>i</button>";
}
function findLatestAvailableDateIdx(sym) {
const inst = DATA.instruments.find((x) => x.symbol === sym) || DATA.instruments[0];
if (!inst || !inst.bars) return DATA.dates_utc.length - 1;
for (let i = inst.bars.length - 1; i >= 0; i--) {
if (inst.bars[i].data_available) return i;
}
return DATA.dates_utc.length - 1;
}
const state = {
guildFilter: "ALL",
selectedSymbol: "NVDA",
selectedLens: DATA.default_lens || "fund_manager",
metricMode: "spoken_aq", // "spoken_aq" | "close_usd" | "change_bps" | "digit_aq"
selectedDateIdx: findLatestAvailableDateIdx("NVDA"),
timeWindowDays: 30, // 30 | 90 | 180 | 0 (ALL)
tickerSearchQuery: "",
heatmapPage: 0,
heatmapPageSize: 25,
heatmapShowAll: false,
wireTapeQuery: "",
};
const guilds = ["ALL", "S1", "S2", "S3", "S4", "S5", "S6", "DOSE_D3"];
const timeWindows = [
{ days: 30, label: "30D" },
{ days: 90, label: "90D" },
{ days: 180, label: "180D" },
{ days: 0, label: "ALL" },
];
const modes = [
{ id: "spoken_aq", label: "Spoken AQ (Gen 1)" },
{ id: "close_usd", label: "Close Price (USD)" },
{ id: "change_bps", label: "Move (BPS)" },
{ id: "digit_aq", label: "Digit AQ" },
];
const elGuildPills = document.getElementById("guildFilterPills");
const elTickerQuickFilter = document.getElementById("tickerQuickFilter");
const elTickerSelect = document.getElementById("tickerSelect");
const elLensSelect = document.getElementById("lensSelect");
const elModePills = document.getElementById("metricModePills");
const elTimeWindowPills = document.getElementById("timeWindowPills");
const elWireTapeFilter = document.getElementById("wireTapeFilterInput");
const elDateBadge = document.getElementById("activeDateBadge");
const elTvBtn = document.getElementById("openTradingViewBtn");
const elPanel3TvBtn = document.getElementById("panel3TvBtn");
const canvas = document.getElementById("tsCanvas");
const ctx = canvas.getContext("2d");
function getActiveDateRange() {
const total = DATA.dates_utc.length;
if (!state.timeWindowDays || state.timeWindowDays <= 0 || state.timeWindowDays >= total) {
return { startIdx: 0, endIdx: total };
}
return { startIdx: Math.max(0, total - state.timeWindowDays), endIdx: total };
}
function instrumentHasDoseD3(inst) {
return (inst.bars || []).some((b) => b.data_available && Number(b.confluence_dose || 0) >= 3);
}
function getFilteredInstruments() {
let base = DATA.instruments;
if (state.guildFilter === "DOSE_D3") {
const d3 = DATA.instruments.filter(instrumentHasDoseD3);
base = d3.length ? d3 : DATA.instruments;
} else if (state.guildFilter !== "ALL") {
base = DATA.instruments.filter((inst) => inst.guilds.indexOf(state.guildFilter) !== -1);
}
const q = (state.tickerSearchQuery || "").trim().toLowerCase();
if (!q) return base;
const matched = base.filter((inst) => {
return (
String(inst.symbol || "").toLowerCase().includes(q) ||
String(inst.entity_eng || "").toLowerCase().includes(q) ||
String(inst.entity_ing || "").toLowerCase().includes(q) ||
String(inst.entity_ing_aq || "") === q ||
String(inst.entity_eng_aq || "") === q
);
});
return matched.length ? matched : base;
}
function getSelectedInstrument() {
return (
DATA.instruments.find((inst) => inst.symbol === state.selectedSymbol) ||
DATA.instruments[0]
);
}
function updateTradingViewLinks() {
const inst = getSelectedInstrument();
const url = inst.tradingview_url || ("https://www.tradingview.com/chart/?symbol=" + encodeURIComponent(inst.symbol));
const label = "Open TradingView (" + (inst.tradingview_symbol || inst.symbol) + ") \u2197";
if (elTvBtn) {
elTvBtn.href = url;
elTvBtn.textContent = label;
}
if (elPanel3TvBtn) {
elPanel3TvBtn.href = url;
elPanel3TvBtn.textContent = (inst.tradingview_symbol || inst.symbol) + " on TradingView \u2197";
}
}
function renderControls() {
// Guild Pills
elGuildPills.innerHTML = "";
guilds.forEach((g) => {
const btn = document.createElement("button");
btn.className = "pill" + (state.guildFilter === g ? " active" : "");
btn.textContent = g === "DOSE_D3" ? "\u0394 Dose D\u22653 (19d)" : g;
btn.onclick = function () {
state.guildFilter = g;
const list = getFilteredInstruments();
if (list.length && !list.some((x) => x.symbol === state.selectedSymbol)) {
state.selectedSymbol = list[0].symbol;
}
renderAll();
};
elGuildPills.appendChild(btn);
});
// Ticker Select
const filtered = getFilteredInstruments();
elTickerSelect.innerHTML = "";
filtered.forEach((inst) => {
const opt = document.createElement("option");
opt.value = inst.symbol;
opt.textContent = inst.symbol + " — " + inst.entity_eng + " [" + inst.guilds.join(",") + "] (AQ " + inst.entity_ing_aq + ")";
if (inst.symbol === state.selectedSymbol) opt.selected = true;
elTickerSelect.appendChild(opt);
});
elTickerSelect.onchange = function () {
state.selectedSymbol = elTickerSelect.value;
renderAll();
};
// Lens Select (populated dynamically from DATA.enabled_lenses)
elLensSelect.innerHTML = "";
(DATA.enabled_lenses || []).forEach((lid) => {
const meta = (DATA.lens_registry_meta && DATA.lens_registry_meta[lid]) || { short_label: lid, title: lid };
const opt = document.createElement("option");
opt.value = lid;
opt.textContent = meta.short_label + " — " + meta.title;
if (lid === state.selectedLens) opt.selected = true;
elLensSelect.appendChild(opt);
});
elLensSelect.onchange = function () {
state.selectedLens = elLensSelect.value;
renderAll();
};
// Metric Mode Pills
elModePills.innerHTML = "";
modes.forEach((m) => {
const btn = document.createElement("button");
btn.className = "pill" + (state.metricMode === m.id ? " active" : "");
btn.textContent = m.label;
btn.onclick = function () {
state.metricMode = m.id;
renderAll();
};
elModePills.appendChild(btn);
});
// Sliding Temporal Window Pills (Strategy 1A: 30D | 90D | 180D | ALL)
if (elTimeWindowPills) {
elTimeWindowPills.innerHTML = "";
timeWindows.forEach((tw) => {
const btn = document.createElement("button");
btn.className = "pill" + (state.timeWindowDays === tw.days ? " active" : "");
btn.textContent = tw.label;
btn.onclick = function () {
state.timeWindowDays = tw.days;
const rng = getActiveDateRange();
if (state.selectedDateIdx < rng.startIdx) state.selectedDateIdx = rng.endIdx - 1;
renderAll();
};
elTimeWindowPills.appendChild(btn);
});
}
elDateBadge.textContent = DATA.dates_utc[state.selectedDateIdx];
updateTradingViewLinks();
}
if (elTickerQuickFilter) {
elTickerQuickFilter.addEventListener("input", function () {
state.tickerSearchQuery = elTickerQuickFilter.value || "";
state.heatmapPage = 0;
const list = getFilteredInstruments();
if (list.length && !list.some((x) => x.symbol === state.selectedSymbol)) {
state.selectedSymbol = list[0].symbol;
}
renderAll();
});
}
if (elWireTapeFilter) {
elWireTapeFilter.addEventListener("input", function () {
state.wireTapeQuery = elWireTapeFilter.value || "";
renderInspectorAndLens();
});
}
function drawCanvas() {
const inst = getSelectedInstrument();
const rng = getActiveDateRange();
const bars = inst.bars.slice(rng.startIdx, rng.endIdx);
const datesSlice = DATA.dates_utc.slice(rng.startIdx, rng.endIdx);
const wireSlice = DATA.daily_wire_series.slice(rng.startIdx, rng.endIdx);
const N = bars.length;
const localSelIdx = Math.max(0, Math.min(N - 1, state.selectedDateIdx - rng.startIdx));
const W = canvas.width;
const H = canvas.height;
ctx.clearRect(0, 0, W, H);
const padL = 62;
const padR = 28;
const plotW = W - padL - padR;
// 3 Panes: Top (20..195), Middle (215..310), Bottom (330..385)
const topY0 = 22, topY1 = 192;
const midY0 = 216, midY1 = 306;
const botY0 = 328, botY1 = 382;
function xAt(i) {
return padL + (i / Math.max(1, N - 1)) * plotW;
}
// Selected date vertical crosshair
const selX = xAt(localSelIdx);
ctx.strokeStyle = "rgba(245, 198, 48, 0.45)";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(selX, 10);
ctx.lineTo(selX, H - 18);
ctx.stroke();
// Pane dividers
ctx.strokeStyle = "#1e293b";
ctx.lineWidth = 1;
[topY1, midY1, botY1].forEach((yLine) => {
ctx.beginPath();
ctx.moveTo(padL, yLine);
ctx.lineTo(W - padR, yLine);
ctx.stroke();
});
// Top Pane: Selected Metric Trajectory (strictly over real available bars; never synthesized or interpolated)
const vals = bars.map((b) => {
if (!b || !b.data_available || b.close_usd === null || b.close_usd === undefined) return null;
if (state.metricMode === "close_usd") return Number(b.close_usd);
if (state.metricMode === "change_bps") return b.change_bps !== null && b.change_bps !== undefined ? Number(b.change_bps) : null;
if (state.metricMode === "digit_aq") return b.close_digit_aq !== null && b.close_digit_aq !== undefined ? Number(b.close_digit_aq) : null;
return b.close_spoken_ing_aq !== null && b.close_spoken_ing_aq !== undefined ? Number(b.close_spoken_ing_aq) : null;
});
const validVals = vals.filter((v) => v !== null && !Number.isNaN(v));
if (!inst.data_available || validVals.length === 0) {
ctx.fillStyle = "rgba(15, 23, 42, 0.94)";
ctx.fillRect(padL + 40, topY0 + 36, plotW - 80, 92);
ctx.strokeStyle = "#f5c630";
ctx.strokeRect(padL + 40, topY0 + 36, plotW - 80, 92);
ctx.fillStyle = "#f5c630";
ctx.font = "bold 13px monospace";
ctx.textAlign = "center";
ctx.fillText("NO MARKET DATA AVAILABLE FOR " + inst.symbol, padL + plotW / 2, topY0 + 74);
ctx.fillStyle = "#94a3b8";
ctx.font = "11px monospace";
ctx.fillText(inst.status || "No public exchange feed available (0 synthetic bars generated).", padL + plotW / 2, topY0 + 98);
ctx.textAlign = "left";
} else {
const minV = Math.min.apply(null, validVals);
const maxV = Math.max.apply(null, validVals);
const spanV = Math.max(1e-3, maxV - minV);
function yTop(v) {
return topY1 - ((v - minV) / spanV) * (topY1 - topY0 - 14) - 6;
}
// Draw entity AQ horizontal reference line if within range
const refAq = inst.entity_ing_aq;
if (refAq >= minV && refAq <= maxV) {
const ry = yTop(refAq);
ctx.strokeStyle = "rgba(255, 77, 77, 0.45)";
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(padL, ry);
ctx.lineTo(W - padR, ry);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#ff4d4d";
ctx.font = "10px monospace";
ctx.fillText(inst.entity_ing + "=" + refAq, padL + 6, ry - 4);
}
// Plot curve across available trading days
ctx.strokeStyle = "#22d3ee";
ctx.lineWidth = 2.2;
ctx.beginPath();
let started = false;
vals.forEach((v, idx) => {
if (v === null || Number.isNaN(v)) return;
const px = xAt(idx);
const py = yTop(v);
if (!started) {
ctx.moveTo(px, py);
started = true;
} else {
ctx.lineTo(px, py);
}
});
ctx.stroke();
// Lock beacon markers on Top Pane
bars.forEach((b, idx) => {
if (vals[idx] === null || Number.isNaN(vals[idx])) return;
const px = xAt(idx);
const py = yTop(vals[idx]);
if (b.scope1_locks && b.scope1_locks.length > 0) {
ctx.fillStyle = "#f5c630";
ctx.beginPath();
ctx.arc(px, py, 5.2, 0, Math.PI * 2);
ctx.fill();
} else if (b.scope2_ring_coordinates && b.scope2_ring_coordinates.length > 0) {
ctx.fillStyle = "#22d3ee";
ctx.beginPath();
ctx.arc(px, py, 3.8, 0, Math.PI * 2);
ctx.fill();
}
});
ctx.fillStyle = "#94a3b8";
ctx.font = "10px monospace";
ctx.fillText(maxV.toFixed(1), 6, topY0 + 8);
ctx.fillText(minV.toFixed(1), 6, topY1 - 4);
}
// Middle Pane: 00:00 GMT News Wire Equation Counts + Co-Presence Diamonds
const wireTotals = wireSlice.map((d) => Number(d.equation_counts.total || 0));
const maxW = Math.max(10, Math.max.apply(null, wireTotals));
const barW = Math.max(2, Math.floor(plotW / Math.max(1, N)) - 3);
wireTotals.forEach((wt, idx) => {
const px = xAt(idx);
const bh = (wt / maxW) * (midY1 - midY0 - 14);
ctx.fillStyle = bars[idx] && bars[idx].co_present_in_news_wire ? "#34d399" : "#a78bfa";
ctx.fillRect(px - barW / 2, midY1 - bh, barW, bh);
});
// Bottom Pane: 20-Day Volume Ratio & Regime Color Strip
const vols = bars.map((b) => (b && b.data_available && b.volume_ratio_20d !== null && b.volume_ratio_20d !== undefined) ? Number(b.volume_ratio_20d) : null);
const validVols = vols.filter((v) => v !== null && v > 0);
const maxVol = validVols.length > 0 ? Math.max(2.6, Math.max.apply(null, validVols)) : 2.6;
vols.forEach((vr, idx) => {
if (vr === null) return;
const px = xAt(idx);
const bh = (vr / maxVol) * (botY1 - botY0 - 8);
const b = bars[idx];
const chgP = b.change_pct !== null && b.change_pct !== undefined ? Number(b.change_pct) : 0.0;
ctx.fillStyle = chgP <= -5.0 || vr >= 2.5 ? "#ff4d4d" : (vr < 0.45 ? "#f5c630" : "#38bdf8");
ctx.fillRect(px - barW / 2, botY1 - bh, barW, bh);
});
// Axis labels
ctx.fillStyle = "#94a3b8";
ctx.font = "10px monospace";
ctx.fillText("Wire Eq", 6, midY0 + 12);
ctx.fillText("Vol20d", 6, botY0 + 12);
// Date ticks along bottom (adaptive step so labels never overlap as N grows)
const tickStep = Math.max(4, Math.ceil(N / 8));
for (let i = 0; i < N; i += tickStep) {
ctx.fillText(datesSlice[i].slice(5), xAt(i) - 14, H - 4);
}
// Optional Tutorial Spotlight Ring & Callout Banner on Canvas
if (activeSpotlight && activeSpotlight.target === "canvas") {
const spX = padL + (activeSpotlight.xRatio || 0.9) * plotW;
const spY = (activeSpotlight.yRatio || 0.25) * H;
ctx.save();
ctx.strokeStyle = "#f5c630";
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.arc(spX, spY, 18, 0, Math.PI * 2);
ctx.stroke();
ctx.strokeStyle = "rgba(251, 113, 133, 0.85)";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(spX, spY, 25, 0, Math.PI * 2);
ctx.stroke();
const lbl = activeSpotlight.label || "Spotlight";
ctx.font = "bold 11px monospace";
const tw = ctx.measureText(lbl).width + 16;
const bx = Math.max(padL + 6, Math.min(W - tw - 12, spX - tw - 24));
const by = Math.max(18, spY - 14);
ctx.fillStyle = "rgba(2, 6, 23, 0.92)";
ctx.fillRect(bx, by, tw, 24);
ctx.strokeStyle = "#f5c630";
ctx.strokeRect(bx, by, tw, 24);
ctx.fillStyle = "#f5c630";
ctx.fillText(lbl, bx + 8, by + 16);
ctx.restore();
}
}
function renderHeatmap() {
const tbl = document.getElementById("heatmapTable");
const pagBar = document.getElementById("heatmapPaginationBar");
const filtered = getFilteredInstruments();
const rng = getActiveDateRange();
const totalRows = filtered.length;
const pageSize = state.heatmapShowAll ? Math.max(1, totalRows) : state.heatmapPageSize;
const totalPages = Math.max(1, Math.ceil(totalRows / pageSize));
if (state.heatmapPage >= totalPages) state.heatmapPage = totalPages - 1;
const rowStart = state.heatmapShowAll ? 0 : state.heatmapPage * pageSize;
const pageSlice = filtered.slice(rowStart, rowStart + pageSize);
let html = "<thead><tr><th class='sym-col'>Ticker (TV)</th>";
for (let idx = rng.startIdx; idx < rng.endIdx; idx++) {
const dt = DATA.dates_utc[idx];
const selStyle = idx === state.selectedDateIdx ? "color:var(--gold);font-weight:700;" : "color:var(--text-muted);";
html += "<th style='" + selStyle + "'>" + dt.slice(8) + "</th>";
}
html += "</tr></thead><tbody>";
pageSlice.forEach((inst) => {
const rowSel = inst.symbol === state.selectedSymbol ? "background:rgba(34,211,238,0.12);" : "";
html += "<tr style='" + rowSel + "'><th class='sym-col'>";
html += "<span style='cursor:pointer;color:var(--text-main);' data-sym='" + inst.symbol + "' class='hm-sym-pick'>" + inst.symbol + "</span> ";
html += "<a href='" + inst.tradingview_url + "' target='_blank' rel='noopener noreferrer' style='color:var(--gold);text-decoration:none;' title='Open " + inst.tradingview_symbol + " on TradingView'>\u2197</a>";
html += "</th>";
for (let dIdx = rng.startIdx; dIdx < rng.endIdx; dIdx++) {
const b = inst.bars[dIdx];
let cls = "hm-cell hm-none";
if (!b.data_available) cls = "hm-cell hm-nodata";
else if (b.scope1_locks && b.scope1_locks.length > 0) cls = "hm-cell hm-scope1";
else if (b.scope2_ring_coordinates && b.scope2_ring_coordinates.length > 0) cls = "hm-cell hm-scope2";
if (b.co_present_in_news_wire) cls += " hm-wire";
if (inst.symbol === state.selectedSymbol && dIdx === state.selectedDateIdx) cls += " hm-selected";
const tip = !b.data_available
? (inst.symbol + " (" + b.date_utc + "): No data available")
: (inst.symbol + " (" + b.date_utc + "): $" + b.close_usd + " (" + (b.change_bps !== null ? b.change_bps + " bps" : "No bps data") + ") | Spoken AQ=" + b.close_spoken_ing_aq);
html += "<td><span class='" + cls + "' data-sym='" + inst.symbol + "' data-didx='" + dIdx + "' title='" + tip + "'></span></td>";
}
html += "</tr>";
});
html += "</tbody>";
tbl.innerHTML = html;
if (pagBar) {
if (totalRows <= state.heatmapPageSize) {
pagBar.style.display = "none";
pagBar.innerHTML = "";
} else {
pagBar.style.display = "flex";
pagBar.innerHTML =
"<span style='color:var(--text-muted);'>Showing " + (rowStart + 1) + "&ndash;" + Math.min(totalRows, rowStart + pageSize) + " of " + totalRows + " tickers</span>" +
"<div style='display:flex;gap:0.4rem;'>" +
"<button type='button' class='pill' id='hmPrevPageBtn'>&larr; Prev</button>" +
"<span style='padding:0.2rem 0.4rem;color:var(--gold);'>Page " + (state.heatmapPage + 1) + "/" + totalPages + "</span>" +
"<button type='button' class='pill' id='hmNextPageBtn'>Next &rarr;</button>" +
"<button type='button' class='pill' id='hmToggleAllBtn'>" + (state.heatmapShowAll ? "Paginate (25/p)" : "Show All (" + totalRows + ")") + "</button>" +
"</div>";
const pBtn = document.getElementById("hmPrevPageBtn");
const nBtn = document.getElementById("hmNextPageBtn");
const aBtn = document.getElementById("hmToggleAllBtn");
if (pBtn) pBtn.onclick = function () { state.heatmapPage = Math.max(0, state.heatmapPage - 1); renderHeatmap(); };
if (nBtn) nBtn.onclick = function () { state.heatmapPage = Math.min(totalPages - 1, state.heatmapPage + 1); renderHeatmap(); };
if (aBtn) aBtn.onclick = function () { state.heatmapShowAll = !state.heatmapShowAll; state.heatmapPage = 0; renderHeatmap(); };
}
}
tbl.querySelectorAll(".hm-cell").forEach((cell) => {
cell.addEventListener("click", function () {
state.selectedSymbol = cell.getAttribute("data-sym");
state.selectedDateIdx = parseInt(cell.getAttribute("data-didx"), 10);
renderAll();
});
});
tbl.querySelectorAll(".hm-sym-pick").forEach((sp) => {
sp.addEventListener("click", function () {
state.selectedSymbol = sp.getAttribute("data-sym");
renderAll();
});
});
}
function renderInspectorAndLens() {
const inst = getSelectedInstrument();
const bar = inst.bars[state.selectedDateIdx];
const dt = bar.date_utc;
const proj = (inst.lens_projections && inst.lens_projections[state.selectedLens]) || null;
document.getElementById("panel3Title").textContent =
"PANEL 3: " + inst.symbol + " (" + inst.entity_eng + " \u2192 " + inst.entity_ing + "=" + inst.entity_ing_aq + ") @ " + dt;
const metricsGrid = document.getElementById("dateMetricsGrid");
if (!bar.data_available || bar.close_usd === null || bar.close_usd === undefined) {
metricsGrid.innerHTML = [
{ l: "Close USD (Change)", tid: "box_close_usd", v: "No data available" },
{ l: "Spoken Close (Gen 1 AQ)", tid: "box_spoken_close", v: "No data available" },
{ l: "Scaled Cap (Gen 1 AQ)", tid: "box_scaled_cap", v: "No data available" },
{ l: "BPS Spoken AQ / Vol20d", tid: "box_bps_vol", v: "No data available" },
{ l: "Active Contingent Locks", tid: "box_active_locks", v: "No data available" },
{ l: "00:00 GMT Wire Co-Present", tid: "box_wire_copresent", v: bar.co_present_in_news_wire ? "YES (Scope 3 Lock)" : "No" },
]
.map((m) => "<div class='stat-box'><div class='stat-label'>" + m.l + makeInfoIconHtml(m.tid) + "</div><div class='stat-val' style='color:var(--text-muted);'>" + m.v + "</div></div>")
.join("");
} else {
const lockSummary = (bar.scope1_locks || []).concat((bar.scope2_ring_coordinates || []).map((c) => "Ring " + c)).join(", ") || "None";
const chgStr = bar.change_bps !== null && bar.change_bps !== undefined
? (" (" + (bar.change_bps >= 0 ? "+" : "") + bar.change_bps + " bps)")
: " (No prior day data)";
const capDisp = (bar.market_cap_str && bar.market_cap_str !== "No data available" && bar.scaled_cap_spoken_ing_aq !== null)
? (bar.market_cap_str + " (" + bar.scaled_cap_spoken_ing_aq + ")")
: "No data available";
const bpsDisp = bar.bps_spoken_ing_aq !== null && bar.bps_spoken_ing_aq !== undefined
? ((bar.bps_spoken_eng_aq ? bar.bps_spoken_eng_aq + "\u2192" : "") + bar.bps_spoken_ing_aq)
: "No data available";
const volDisp = bar.volume_ratio_20d !== null && bar.volume_ratio_20d !== undefined ? (bar.volume_ratio_20d + "x") : "No data available";
const doseDisp = bar.confluence_dose !== null && bar.confluence_dose !== undefined
? ("Dose " + bar.confluence_dose + "/4 (" + (bar.dose_taxon_label || "") + ")")
: "No data available";
const closeSpDisp = (bar.close_spoken_eng_aq ? bar.close_spoken_eng_aq + "\u2192" : "") + bar.close_spoken_ing_aq + " (" + bar.close_spoken_ing + ")";
metricsGrid.innerHTML = [
{ l: "Close USD (Change)", tid: "box_close_usd", v: "$" + bar.close_usd + chgStr },
{ l: "Spoken Close (Gen 0\u2192Gen 1 AQ)", tid: "box_spoken_close", v: closeSpDisp },
{ l: "Scaled Cap (Gen 1 AQ)", tid: "box_scaled_cap", v: capDisp },
{ l: "BPS Spoken (Gen 0\u21921) / Vol20d", tid: "box_bps_vol", v: bpsDisp + " / " + volDisp },
{ l: "Active Contingent Locks", tid: "box_active_locks", v: lockSummary },
{ l: "Confluence Dose & Wire", tid: "box_wire_copresent", v: doseDisp },
]
.map((m) => "<div class='stat-box'><div class='stat-label'>" + m.l + makeInfoIconHtml(m.tid) + "</div><div class='stat-val'>" + m.v + "</div></div>")
.join("");
}
// Render Active Lens Projection Card (LENS_REGISTRY)
const lensCard = document.getElementById("lensProjectionCard");
if (proj) {
const lensMeta = (DATA.lens_registry_meta && DATA.lens_registry_meta[state.selectedLens]) || {};
const tsLabelsMap = lensMeta.timeseries_labels || {};
const reverseLabelToKey = {};
Object.keys(tsLabelsMap).forEach((canonicalKey) => {
reverseLabelToKey[tsLabelsMap[canonicalKey]] = canonicalKey;
});
let rowsHtml = "";
Object.keys(proj.labeled_timeseries || {}).forEach((k) => {
const val = proj.labeled_timeseries[k];
const canonicalKey = reverseLabelToKey[k] || "ts_duty_cycle_pct";
let disp = "No data available";
if (val !== null && val !== undefined) {
if (typeof val === "object") {
const nonNull = Object.values(val).some((x) => x !== null && x !== undefined);
disp = nonNull ? JSON.stringify(val) : "No data available";
} else {
disp = String(val);
}
}
rowsHtml += "<div style='display:flex;justify-content:space-between;font-size:0.69rem;border-bottom:1px solid #162032;padding:0.18rem 0;'>" +
"<span style='color:var(--text-muted);'>" + k + makeInfoIconHtml(canonicalKey) + ":</span><span style='color:var(--text-main);font-weight:600;'>" + disp + "</span></div>";
});
const archDisp = (proj.qualitative_profile && proj.qualitative_profile.archetype) || "No data available";
const regDisp = (proj.qualitative_profile && proj.qualitative_profile.regime_specialization) || "No data available";
const sparkDisp = inst.timeseries_moments.ts_sparkline_30d || "No data available";
lensCard.innerHTML =
"<div style='display:flex;justify-content:space-between;align-items:center;margin-bottom:0.4rem;'>" +
"<span style='font-size:0.76rem;font-weight:700;color:var(--gold);'>Lens: " + proj.lens_title + makeInfoIconHtml("projection_lens") + "</span>" +
"<span style='font-size:0.7rem;color:var(--cyan);'>" + proj.tier_classification + "</span></div>" +
"<div style='font-size:0.71rem;color:var(--emerald);margin-bottom:0.4rem;'>" +
"Archetype" + makeInfoIconHtml("lens_archetype") + ": " + archDisp + " &bull; " + regDisp +
" &bull; 30d: " + sparkDisp + "</div>" +
rowsHtml;
}
// Render Knowledge-Graph-Modeled Documentation & Cited Passages Card
const docCard = document.getElementById("docReferencesCard");
if (docCard && inst.doc_references) {
const dr = inst.doc_references;
const resolveUrl = (window.HyperstitionStudio.QuantTutorials && window.HyperstitionStudio.QuantTutorials.adaptHrefForFileProtocol) || function (u) { return u; };
const encUrl = resolveUrl(dr.encyclopedia_deep_link);
const kgUrl = resolveUrl(dr.knowledge_graph_deep_link);
const dosUrl = resolveUrl(dr.exemplar_dossier_deep_link);
const apiUrl = dr.rest_api_deep_link;
docCard.innerHTML =
"<div style='font-size:0.74rem;font-weight:700;color:var(--cyan);margin-bottom:0.3rem;'>Documentation &amp; Passage-Encoded Deep Citations</div>" +
"<div style='font-size:0.68rem;color:var(--text-muted);margin-bottom:0.4rem;'>" + (dr.verbatim_citation_passage || "") + "</div>" +
"<div style='display:flex;flex-wrap:wrap;gap:0.35rem;'>" +
"<a class='pill' style='text-decoration:none;color:var(--gold);border-color:var(--gold);' href='" + encUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCC4 Encyclopedia PDF (#page &amp; search) \u2197</a>" +
"<a class='pill' style='text-decoration:none;color:var(--cyan);border-color:var(--cyan);' href='" + kgUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDD78\uFE0F Knowledge Graph (aq:" + inst.entity_ing_aq + ") \u2197</a>" +
"<a class='pill' style='text-decoration:none;color:var(--emerald);border-color:var(--emerald);' href='" + dosUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCDC Dossier Passage (#:~:text=) \u2197</a>" +
"<button type='button' class='pill preview-api-btn' data-api='" + apiUrl + "' style='color:var(--violet);border-color:var(--violet);'>\uD83D\uDD0D Inline Passage Preview</button>" +
"</div>";
}
// Render Dated 00:00 GMT News-Wire Equation Tape
const wireDay = DATA.daily_wire_series[state.selectedDateIdx];
const tapeEl = document.getElementById("wireEqTape");
const hdrEl = document.getElementById("wireTapeHeader");
const resolveUrl = (window.HyperstitionStudio.QuantTutorials && window.HyperstitionStudio.QuantTutorials.adaptHrefForFileProtocol) || function (u) { return u; };
if (wireDay && wireDay.dossier_file) {
hdrEl.innerHTML =
"Dated 00:00 GMT Wire Dossier (<a href='" + resolveUrl(wireDay.archive_route) + "' target='_blank' style='color:var(--cyan);'>" +
wireDay.dossier_file + "</a> &bull; " + wireDay.equation_counts.total + " Verified Equations):";
const wq = (state.wireTapeQuery || "").trim().toLowerCase();
const rawEqs = wireDay.sample_equations || [];
const filteredEqs = !wq ? rawEqs : rawEqs.filter((eq) => {
return (
String(eq.ing || "").toLowerCase().includes(wq) ||
String(eq.eng || "").toLowerCase().includes(wq) ||
String(eq.target || "") === wq ||
String(eq.breakdown || "").toLowerCase().includes(wq)
);
});
tapeEl.innerHTML = filteredEqs
.map(
(eq) => {
const dLink = resolveUrl(eq.dossier_deep_link || wireDay.archive_route);
const gLink = resolveUrl((eq.graph_hub_links && eq.graph_hub_links[0]) || ("/graph/index.html?select=aq:" + eq.target));
const aLink = eq.api_highlight_link || ("/api/v1/dossiers/" + wireDay.dossier_number + "?highlight=" + encodeURIComponent(eq.ing.slice(0, 20)));
return "<div class='eq-item'><div><strong style='color:var(--gold);'>[" + eq.target + "]</strong> " +
"<code>" + eq.ing + "</code> (\"" + eq.eng + "\")</div>" +
"<div style='color:var(--text-muted);font-size:0.65rem;margin-bottom:0.2rem;'>" + eq.breakdown + " = " + eq.target + "</div>" +
"<div style='display:flex;flex-wrap:wrap;gap:0.3rem;'>" +
"<a class='pill' style='text-decoration:none;font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--emerald);' href='" + dLink + "' target='_blank'>Passage #:~:text= \u2197</a>" +
"<a class='pill' style='text-decoration:none;font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--cyan);' href='" + gLink + "' target='_blank'>Graph Hub \u2197</a>" +
"<button type='button' class='pill preview-api-btn' data-api='" + aLink + "' data-fallback='" + eq.ing + " (\"" + eq.eng + "\") = " + eq.target + "' style='font-size:0.62rem;padding:0.12rem 0.4rem;color:var(--violet);'>Preview Passage</button>" +
"</div></div>";
}
)
.join("");
} else {
hdrEl.textContent = "Dated 00:00 GMT Wire Dossier (" + dt + "):";
tapeEl.innerHTML = "<div style='color:var(--text-muted);'>No separate dated news dossier archived on " + dt + " (US Closing-Bell Market Telemetry Bar active).</div>";
}
document.querySelectorAll(".preview-api-btn").forEach(function (btn) {
btn.onclick = function () {
const apiTarget = btn.getAttribute("data-api");
const fallbackTxt = btn.getAttribute("data-fallback") || (inst.doc_references && inst.doc_references.verbatim_citation_passage) || "";
const previewBox = document.getElementById("passagePreviewBox");
if (!previewBox) return;
previewBox.style.display = "block";
previewBox.textContent = "Loading passage preview from " + apiTarget + " ...";
fetch(apiTarget)
.then(function (r) { return r.json(); })
.then(function (j) {
const d = (j && j.data) || j || {};
const matches = d.matched_passages || [];
if (matches.length > 0) {
previewBox.textContent =
"[REST API Passage Match in " + (d.uri || apiTarget) + " — Line " + matches[0].line_number + "]\n" +
matches[0].context;
} else {
previewBox.textContent = "[Passage Preview]\n" + fallbackTxt;
}
})
.catch(function () {
previewBox.textContent = "[Offline Passage Preview]\n" + fallbackTxt;
});
};
});
}
function renderLagExplorer() {
const inst = getSelectedInstrument();
const curve = inst.timeseries_moments.ts_lag_correlation_curve || {};
const optLag = inst.timeseries_moments.ts_optimal_lag_days;
const container = document.getElementById("lagBarsContainer");
let html = "";
for (let tau = -5; tau <= 5; tau++) {
const rawR = curve[String(tau)];
if (rawR === null || rawR === undefined) {
html +=
"<div class='lag-col' title='Lag tau=" + tau + "d: No data available'>" +
"<div style='font-size:0.62rem;color:var(--text-muted);'>N/A</div>" +
"<div class='lag-bar' style='height:4px;background:#334155;'></div>" +
"<div class='lag-lbl'>&tau;=" + (tau >= 0 ? "+" + tau : tau) + "d</div></div>";
} else {
const r = Number(rawR);
const hPct = Math.max(6, Math.round(Math.abs(r) * 85));
const color = tau === optLag ? "var(--gold)" : (r >= 0 ? "var(--cyan)" : "var(--rose)");
html +=
"<div class='lag-col' title='Lag tau=" + tau + "d: r=" + r.toFixed(3) + "'>" +
"<div style='font-size:0.62rem;color:var(--text-main);'>" + r.toFixed(2) + "</div>" +
"<div class='lag-bar' style='height:" + hPct + "px;background:" + color + ";'></div>" +
"<div class='lag-lbl'>&tau;=" + (tau >= 0 ? "+" + tau : tau) + "d</div></div>";
}
}
container.innerHTML = html;
const pGate = DATA.periodicity_gate || {};
const optLagDisp = optLag !== null && optLag !== undefined ? ((optLag >= 0 ? "+" + optLag : optLag) + "d") : "No data available";
document.getElementById("periodicityAuditFooter").innerHTML =
"Periodicity Gate Enforced" + makeInfoIconHtml("periodicity_gate_badge") + ": " +
pGate.dated_news_dossiers_ingested + " dated 00:00 UTC news dossiers + real exchange closing-bell bars (" +
pGate.non_periodic_records_ingested + " non-periodic/static records ingested; missing bars = null / No data available) | Optimal Lag &tau;*" +
makeInfoIconHtml("ts_optimal_lag_days") + " = " + optLagDisp + " | CIDv1" + makeInfoIconHtml("cidv1_provenance") + ": <code>" +
((DATA.ipld_dag_json_cidv1 && DATA.ipld_dag_json_cidv1["/"]) || "") + "</code>";
}
function renderMacroIndicators() {
const grid = document.getElementById("macroIndicatorsGrid");
if (!grid) return;
const M = window.HYPERSTITION_MACRO_DATA;
if (!M || !M.series) {
grid.innerHTML = "<div class='stat-box'><div class='stat-val'>No data available</div></div>";
return;
}
const S = M.series;
const D = M.derived_indicators || {};
const cards = [
{
title: "CPI (CPIAUCSL, 1mo)",
val: S.cpi && S.cpi.data_available ? (S.cpi.latest_value + " (" + (S.cpi.period_change_bps >= 0 ? "+" : "") + S.cpi.period_change_bps + " bps MoM)") : "No data available",
sub: S.cpi && S.cpi.change_aq_evaluation ? ("MoM Spoken: '" + S.cpi.change_aq_evaluation.spoken_ing + "' = " + S.cpi.change_aq_evaluation.spoken_ing_aq + " [S2]") : "No data available",
cls: "",
},
{
title: "PPI (PPIACO, 1mo) & Margin",
val: S.ppi && S.ppi.data_available ? (S.ppi.latest_value + " (" + S.ppi.period_change_bps + " bps MoM)") : "No data available",
sub: "PPI - CPI Spread: " + ((D.pipeline_inflation_margin && D.pipeline_inflation_margin.ppi_minus_cpi_mom_spread_bps) || "N/A") + " bps | 'nainteen' = 137 [Iso]",
cls: "plate-lock-emerald",
},
{
title: "US10Y Treasury (DGS10, 1d)",
val: S.us10y && S.us10y.data_available ? (S.us10y.latest_value + "% (" + S.us10y.latest_date_utc + ")") : "No data available",
sub: "10Y - EFFR Curve Slope: +" + ((D.overnight_and_curve_spreads && D.overnight_and_curve_spreads.us10y_minus_effr_curve_slope_bps) || "N/A") + " bps (-> 237 [S6])",
cls: "",
},
{
title: "Overnight Rates (EFFR / SOFR, 1d)",
val: (S.effr && S.effr.data_available ? ("EFFR " + S.effr.latest_value + "% (388 bps)") : "No data") + " | " + (S.sofr && S.sofr.data_available ? ("SOFR " + S.sofr.latest_value + "%") : "No data"),
sub: "★ EFFR 388 bps == 388 KG Nodes! | SOFR-EFFR: +" + ((D.overnight_and_curve_spreads && D.overnight_and_curve_spreads.sofr_minus_effr_repo_spread_bps) || "0") + " bps",
cls: "plate-lock-gold",
},
{
title: "M2 & M1 vs. M2 Spread (1mo)",
val: S.m2 && S.m2.data_available ? ("M2 $" + (S.m2.latest_value / 1000).toFixed(2) + "T | Spread " + (D.m1_vs_m2_spread && D.m1_vs_m2_spread.m2_minus_m1_trillions_str)) : "No data available",
sub: "M1/M2 Liquidity Ratio: " + ((D.m1_vs_m2_spread && D.m1_vs_m2_spread.m1_to_m2_liquidity_ratio_pct) || "N/A") + "% ($3.37T -> 337 [P68])",
cls: "",
},
{
title: "Real M2 & Real M2 Growth (1mo)",
val: S.real_m2 && S.real_m2.data_available ? ("$" + S.real_m2.latest_value + "B (" + (S.real_m2.period_change_bps >= 0 ? "+" : "") + S.real_m2.period_change_bps + " bps MoM)") : "No data available",
sub: "YoY Real M2 Growth: " + ((D.real_m2_growth && D.real_m2_growth.yoy_growth_pct !== null) ? (D.real_m2_growth.yoy_growth_pct + "%") : "No data available"),
cls: "",
},
{
title: "Nominal & Real GDP (1q)",
val: S.gdp_nominal && S.gdp_nominal.data_available ? ("$" + (S.gdp_nominal.latest_value / 1000).toFixed(2) + "T (Real $" + (S.gdp_real.latest_value / 1000).toFixed(2) + "T)") : "No data available",
sub: "GDP / M2 Monetary Velocity: " + ((D.aggregate_output_and_velocity && D.aggregate_output_and_velocity.gdp_to_m2_monetary_velocity) || "N/A") + "x",
cls: "",
},
{
title: "Gross Product & Output (GNP / OUTBS / INDPRO)",
val: S.gnp_gross_product && S.gnp_gross_product.data_available ? ("GNP $" + (S.gnp_gross_product.latest_value / 1000).toFixed(2) + "T | OUTBS " + S.business_gross_output.latest_value) : "No data available",
sub: "★ OUTBS 128.97 -> 129 == blakwel [S3] | INDPRO: " + (S.industrial_production ? (S.industrial_production.latest_value + " (" + S.industrial_production.period_change_bps + " bps)") : "N/A"),
cls: "plate-lock-gold",
},
];
grid.innerHTML = cards.map(function (c) {
return "<div class='stat-box hs-plate-g3 " + c.cls + "'><div class='stat-label'>" + c.title + "</div><div class='stat-val' style='font-size:0.78rem;'>" + c.val + "</div><div style='font-size:0.66rem;color:var(--text-muted);margin-top:0.2rem;'>" + c.sub + "</div></div>";
}).join("");
}
function renderDailyBrief() {
const container = document.getElementById("dailyBriefContainer");
if (!container) return;
const B = window.HYPERSTITION_DAILY_BRIEF;
if (!B || !B.agenda_1_executive_summary) {
container.innerHTML = "<div class='stat-box'><div class='stat-val'>No data available</div></div>";
return;
}
const a1 = B.agenda_1_executive_summary;
const a2 = B.agenda_2_confirming_signals;
const a3 = B.agenda_3_challenging_divergences;
const a4 = B.agenda_4_delta_since_last_run;
const a5 = B.agenda_5_daily_key_macro_question_and_rigor;
const post = (a1.bayesian_regime_inference && a1.bayesian_regime_inference.posterior_probabilities) || {};
const scen = (a1.bayesian_regime_inference && a1.bayesian_regime_inference.scenarios) || {};
container.innerHTML = [
"<div class='stat-box hs-plate-g3 plate-lock-gold'><div class='stat-label' style='color:var(--gold);'>AGENDA 1: EXECUTIVE SUMMARY & BAYESIAN SCENARIOS (RUN #" + B.run_number + ")</div>" +
"<div style='font-size:0.72rem;margin:0.3rem 0;color:var(--text-main);'>" + a1.headline_finding + "</div>" +
"<div style='font-size:0.67rem;color:var(--emerald);'>• Best Case (R1 Bull): " + ((post.R1_BULL_RISK_ON * 100) || 0).toFixed(1) + "% — " + ((scen.best_case_r1_bull_risk_on && scen.best_case_r1_bull_risk_on.expected_daily_excursion_bps) || "") + "</div>" +
"<div style='font-size:0.67rem;color:var(--cyan);'>• Base Case (R2 Pinned Dose 2): " + ((post.R2_PINNED_ISOMETRIC * 100) || 0).toFixed(1) + "% — " + ((scen.base_case_r2_pinned_isometric && scen.base_case_r2_pinned_isometric.expected_daily_excursion_bps) || "") + "</div>" +
"<div style='font-size:0.67rem;color:var(--rose);'>• Worst Case (R3 Tail Drawdown): " + ((post.R3_TAIL_DRAWDOWN_RISK_OFF * 100) || 0).toFixed(1) + "% — " + ((scen.worst_case_r3_tail_drawdown && scen.worst_case_r3_tail_drawdown.expected_daily_excursion_bps) || "") + "</div></div>",
"<div class='stat-box hs-plate-g3 plate-lock-emerald'><div class='stat-label' style='color:var(--emerald);'>AGENDA 2: SUBSTANTIVE SUPPORT FOR ACTIVE THEMES</div>" +
"<div style='font-size:0.70rem;margin:0.3rem 0;color:var(--text-main);'>" + a2.summary + "</div>" +
(a2.active_dose2_confirmations || []).slice(0, 3).map(function (ev) {
return "<div style='font-size:0.66rem;color:var(--text-secondary);'>• " + ev.date_utc + " <b>" + ev.symbol + "</b> ($" + ev.close_usd + ", " + ev.change_bps + " bps): Dose 2 Pin on [" + (ev.shared_dossier_coordinates || []).join(",") + "]</div>";
}).join("") + "</div>",
"<div class='stat-box hs-plate-g3 plate-lock-rose'><div class='stat-label' style='color:var(--rose);'>AGENDA 3: SUBSTANTIVE CHALLENGES & DIVERGENCES</div>" +
(a3.macro_and_memetic_challenges || []).map(function (ch) {
return "<div style='font-size:0.66rem;margin-top:0.22rem;color:var(--text-secondary);'>• <b>" + ch.indicator + ":</b> " + ch.observation + " — " + ch.impact + "</div>";
}).join("") + "</div>",
"<div class='stat-box hs-plate-g3'><div class='stat-label'>AGENDA 4: DELTA SINCE LAST RUN & STRICT NULL AUDIT</div>" +
"<div style='font-size:0.66rem;color:var(--text-secondary);margin-top:0.22rem;'>• Latest Wire: " + ((a4.latest_wire_dossier && a4.latest_wire_dossier.dossier_file) || "N/A") + "</div>" +
"<div style='font-size:0.66rem;color:var(--text-secondary);'>• CPI/PPI: " + ((a4.macro_releases_ingested && a4.macro_releases_ingested.cpi_latest) || "") + " | " + ((a4.macro_releases_ingested && a4.macro_releases_ingested.ppi_latest) || "") + "</div>" +
"<div style='font-size:0.66rem;color:var(--text-muted);'>• Strict Nulls: ANTHR-PVT (0/30d = null); 2026-11-26 Thanksgiving (equities/rates = null)</div></div>",
"<div class='stat-box hs-plate-g3' style='grid-column: 1 / -1;'><div class='stat-label' style='color:var(--cyan);'>AGENDA 5: DAILY KEY MACRO QUESTION (" + ((a5.active_daily_question && a5.active_daily_question.question_id) || "") + ") & COMPOUNDING QUALITATIVE / QUANTITATIVE RIGOR</div>" +
"<div style='font-size:0.72rem;margin:0.28rem 0;color:var(--gold);font-weight:600;'>Q: " + ((a5.active_daily_question && a5.active_daily_question.question_text) || "") + "</div>" +
"<div style='font-size:0.66rem;color:var(--text-secondary);'>• Qualitative Rigor (The Room Filter): " + ((a5.compounding_qualitative_rigor && a5.compounding_qualitative_rigor.room_filter_gate) || "") + "</div>" +
"<div style='font-size:0.66rem;color:var(--text-secondary);margin-top:0.18rem;'>• Quantitative & Statistical Rigor (n=440 bars, 412 t+1 pairs): " + ((a5.compounding_quantitative_rigor && a5.compounding_quantitative_rigor.methodological_applicability_and_significance) || "") + "</div></div>",
].join("");
}
function renderAll() {
renderControls();
drawCanvas();
renderHeatmap();
renderInspectorAndLens();
renderLagExplorer();
renderMacroIndicators();
renderDailyBrief();
}
// Canvas scrub interaction (mouse click + Strategy 4A mobile touchstart/touchmove scrubbing)
function scrubCanvasAtClientX(clientX) {
const rect = canvas.getBoundingClientRect();
const relX = ((clientX - rect.left) / Math.max(1, rect.width)) * canvas.width;
const padL = 62, padR = 28;
const ratio = (relX - padL) / (canvas.width - padL - padR);
const rng = getActiveDateRange();
const span = Math.max(1, rng.endIdx - rng.startIdx - 1);
const idx = rng.startIdx + Math.round(ratio * span);
const nextIdx = Math.max(rng.startIdx, Math.min(rng.endIdx - 1, idx));
if (nextIdx !== state.selectedDateIdx) {
state.selectedDateIdx = nextIdx;
renderAll();
}
}
canvas.addEventListener("click", function (ev) {
scrubCanvasAtClientX(ev.clientX);
});
canvas.addEventListener("touchstart", function (ev) {
if (ev.touches && ev.touches.length === 1) {
scrubCanvasAtClientX(ev.touches[0].clientX);
}
}, { passive: true });
canvas.addEventListener("touchmove", function (ev) {
if (ev.touches && ev.touches.length === 1) {
scrubCanvasAtClientX(ev.touches[0].clientX);
}
}, { passive: true });
document.getElementById("prevDateBtn").onclick = function () {
state.selectedDateIdx = Math.max(0, state.selectedDateIdx - 1);
renderAll();
};
document.getElementById("nextDateBtn").onclick = function () {
state.selectedDateIdx = Math.min(DATA.dates_utc.length - 1, state.selectedDateIdx + 1);
renderAll();
};
// Keyboard shortcuts: Left/Right arrows step UTC dates; 'T' opens TradingView chart in new window
window.addEventListener("keydown", function (ev) {
if (ev.target && (ev.target.tagName === "INPUT" || ev.target.tagName === "SELECT" || ev.target.tagName === "TEXTAREA")) {
return;
}
if (ev.key === "ArrowLeft") {
state.selectedDateIdx = Math.max(0, state.selectedDateIdx - 1);
renderAll();
} else if (ev.key === "ArrowRight") {
state.selectedDateIdx = Math.min(DATA.dates_utc.length - 1, state.selectedDateIdx + 1);
renderAll();
} else if (ev.key === "t" || ev.key === "T") {
const inst = getSelectedInstrument();
window.open(inst.tradingview_url, "_blank", "noopener,noreferrer");
}
});
// CSV & JSON Exports
document.getElementById("exportCsvBtn").onclick = function () {
const inst = getSelectedInstrument();
const headers = ["date_utc", "symbol", "close_usd", "change_bps", "volume_ratio_20d", "close_spoken_ing_aq", "bps_spoken_ing_aq", "co_present_in_news_wire", "contingent_points"];
const lines = [headers.join(",")];
inst.bars.forEach((b) => {
lines.push([b.date_utc, inst.symbol, b.close_usd, b.change_bps, b.volume_ratio_20d, b.close_spoken_ing_aq, b.bps_spoken_ing_aq, b.co_present_in_news_wire, b.contingent_points].join(","));
});
const blob = new Blob([lines.join("\n") + "\n"], { type: "text/csv;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = inst.symbol + "-quant-timeseries.csv";
a.click();
};
document.getElementById("exportJsonBtn").onclick = function () {
const inst = getSelectedInstrument();
const blob = new Blob([JSON.stringify(inst, null, 2) + "\n"], { type: "application/json;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = inst.symbol + "-lens-neutral-slice.json";
a.click();
};
// Interactive Info Icon & Viewport-Clamped PDF Glossary Popover Controller
let pinnedTermId = null;
let activeTriggerEl = null;
function showInfoPopover(termId, triggerEl, pinNow) {
const entry = QUANT_TERM_GLOSSARY[termId];
const pop = document.getElementById("quantInfoPopover");
if (!entry || !pop || !triggerEl) return;
if (pinNow) {
pinnedTermId = termId;
}
activeTriggerEl = triggerEl;
document.querySelectorAll(".hs-info-icon.pinned").forEach((el) => el.classList.remove("pinned"));
if (pinnedTermId) {
triggerEl.classList.add("pinned");
}
const resolveUrl = (window.HyperstitionStudio.QuantTutorials && window.HyperstitionStudio.QuantTutorials.adaptHrefForFileProtocol) || function (u) { return u; };
const glUrl = resolveUrl(entry.glossary_pdf_link);
const mnUrl = resolveUrl(entry.manual_pdf_link);
const pgMatch = entry.glossary_pdf_link.match(/#page=(\d+)/);
const pgNum = pgMatch ? pgMatch[1] : "1";
pop.innerHTML =
"<div class='pop-hdr'>" +
"<span class='pop-title'>\u24D8 " + entry.title + "</span>" +
"<button type='button' class='pop-close' id='popCloseBtn'>" + (pinnedTermId ? "Pinned \u00D7" : "Close \u00D7") + "</button>" +
"</div>" +
"<p class='pop-plain'>" + entry.plain_english + "</p>" +
"<blockquote class='pop-quote'>" +
"<a href='" + glUrl + "' target='_blank' rel='noopener noreferrer' style='color:inherit;text-decoration:none;' title='Click to open PDF Glossary at page " + pgNum + "'>" +
"&ldquo;" + entry.glossary_quote + "&rdquo;</a>" +
"</blockquote>" +
"<div class='pop-links'>" +
"<a class='pill' style='text-decoration:none;color:var(--gold);border-color:var(--gold);' href='" + glUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCD6 Open PDF Glossary (p." + pgNum + ") \u2197</a>" +
"<a class='pill' style='text-decoration:none;color:var(--cyan);border-color:var(--cyan);' href='" + mnUrl + "' target='_blank' rel='noopener noreferrer'>\uD83D\uDCC4 Operator's Manual \u2197</a>" +
"</div>";
pop.style.display = "flex";
pop.setAttribute("aria-hidden", "false");
const rect = triggerEl.getBoundingClientRect();
const popRect = pop.getBoundingClientRect();
let left = rect.left;
let top = rect.bottom + 8;
if (left + popRect.width > window.innerWidth - 14) {
left = Math.max(12, window.innerWidth - popRect.width - 14);
}
if (top + popRect.height > window.innerHeight - 14) {
top = Math.max(12, rect.top - popRect.height - 8);
}
pop.style.left = Math.round(left) + "px";
pop.style.top = Math.round(top) + "px";
const closeBtn = document.getElementById("popCloseBtn");
if (closeBtn) {
closeBtn.onclick = function () {
hideInfoPopover(true);
};
}
}
function hideInfoPopover(forceUnpin) {
if (pinnedTermId && !forceUnpin) return;
pinnedTermId = null;
activeTriggerEl = null;
document.querySelectorAll(".hs-info-icon.pinned").forEach((el) => el.classList.remove("pinned"));
const pop = document.getElementById("quantInfoPopover");
if (pop) {
pop.style.display = "none";
pop.setAttribute("aria-hidden", "true");
}
}
document.addEventListener("mouseover", function (ev) {
const btn = ev.target && ev.target.closest && ev.target.closest(".hs-info-icon");
if (btn && !pinnedTermId) {
showInfoPopover(btn.getAttribute("data-term-id"), btn, false);
}
});
document.addEventListener("focusin", function (ev) {
const btn = ev.target && ev.target.closest && ev.target.closest(".hs-info-icon");
if (btn && !pinnedTermId) {
showInfoPopover(btn.getAttribute("data-term-id"), btn, false);
}
});
document.addEventListener("click", function (ev) {
const btn = ev.target && ev.target.closest && ev.target.closest(".hs-info-icon");
const pop = document.getElementById("quantInfoPopover");
if (btn) {
ev.preventDefault();
ev.stopPropagation();
const tid = btn.getAttribute("data-term-id");
if (pinnedTermId === tid && activeTriggerEl === btn) {
hideInfoPopover(true);
} else {
showInfoPopover(tid, btn, true);
}
return;
}
if (pop && !pop.contains(ev.target)) {
hideInfoPopover(true);
}
});
window.addEventListener("keydown", function (ev) {
if (ev.key === "Escape") {
hideInfoPopover(true);
}
});
window.HyperstitionStudio = window.HyperstitionStudio || {};
window.HyperstitionStudio.QuantTermGlossary = QUANT_TERM_GLOSSARY;
window.HyperstitionStudio.QuantWorkbenchApp = {
getState: function () { return Object.assign({}, state); },
setStateAndRender: function (nextState, spotlight) {
if (nextState) {
if (nextState.guildFilter) state.guildFilter = nextState.guildFilter;
if (nextState.selectedSymbol) state.selectedSymbol = nextState.selectedSymbol;
if (nextState.selectedLens && DATA.lens_registry_meta[nextState.selectedLens]) {
state.selectedLens = nextState.selectedLens;
}
if (nextState.metricMode) state.metricMode = nextState.metricMode;
if (typeof nextState.selectedDateIdx === "number") {
state.selectedDateIdx = Math.max(0, Math.min(DATA.dates_utc.length - 1, nextState.selectedDateIdx));
}
}
activeSpotlight = spotlight || null;
renderAll();
}
};
const qParams = new URLSearchParams(window.location.search || "");
if (qParams.get("screen") === "dose-d3") {
state.guildFilter = "DOSE_D3";
const d3List = getFilteredInstruments();
if (d3List.length) {
state.selectedSymbol = d3List[0].symbol;
const d3BarIdx = (d3List[0].bars || []).findIndex((b) => b.data_available && Number(b.confluence_dose || 0) >= 3);
if (d3BarIdx >= 0) state.selectedDateIdx = d3BarIdx;
}
}
renderAll();
})();