本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZurvanEG
// @version=6
// In the Name of God of Infinite Time and Space
// ───────────────────────────────────────────────────────────────── ─── ─
// Title : 𝗜𝗠𝗖 - 𝗜nter𝗠arket 𝗖ompare [𝗭urvān𝗘𝗚]
// draws up to five markets on the chart's own price scale with
// their true shape, measures how strongly the chart is coupled
// to each, and explains its move with a macro score (−1 … +1).
// Language : TradingView's Pine Script® v6
// ───────────────────────────────────────────────────────────────── ─── ─
// #START_REGION
// ▾▾▾▾▾▾▾▾▾▾▾▾▾
const string TITLE = '𝗜𝗠𝗖 - 𝗜nter𝗠arket 𝗖ompare: Multi-Asset Correlation & Macro Score [𝗭urvān𝗘𝗚]'
const string SHORT = '⧕𝗜𝗠𝗖'
indicator(title = TITLE, shorttitle = SHORT, overlay = true, max_polylines_count = 13, max_labels_count = 13, max_boxes_count = 13)
// ───────────────────
// >CONSTANTS & ENUMS< ⑴
// ────────────────▾──
// @enum catalog choice of an asset slot (titles are the official names shown in the inputs).
enum AssetPick
none = 'None'
spx = 'S&P 500 Index'
ndx = 'Nasdaq 100 Index'
iwm = 'iShares Russell 2000 ETF'
vix = 'CBOE Volatility Index (VIX)'
move = 'ICE BofA MOVE Index'
sox = 'PHLX Semiconductor Index'
dax = 'DAX 40 Index'
nky = 'Nikkei 225 Index'
hsi = 'Hang Seng Index'
eem = 'iShares MSCI Emerging Markets ETF'
us10y = 'US 10-Year Treasury Yield'
us02y = 'US 2-Year Treasury Yield'
us30y = 'US 30-Year Treasury Yield'
tip = 'iShares TIPS Bond ETF'
hyg = 'iShares High Yield Corp Bond ETF'
de10y = 'Germany 10-Year Bund Yield'
jp10y = 'Japan 10-Year JGB Yield'
dxy = 'US Dollar Index'
eur = 'Euro / US Dollar'
jpy = 'US Dollar / Japanese Yen'
gbp = 'British Pound / US Dollar'
cnh = 'US Dollar / Offshore Yuan'
aud = 'Australian Dollar / US Dollar'
chf = 'US Dollar / Swiss Franc'
gold = 'Gold Spot'
gdx = 'VanEck Gold Miners ETF'
silver = 'Silver Spot'
brent = 'Brent Crude Oil'
copper = 'Copper Futures'
ttf = 'Dutch TTF Natural Gas'
nvda = 'NVIDIA Corporation'
btc = 'Bitcoin'
eth = 'Ethereum'
btcd = 'Bitcoin Dominance'
custom = 'Custom Symbol'
enum Palette
custom = 'Custom'
vivid = 'Vivid'
pastel = 'Pastel'
cb = 'Colorblind-safe'
mono = 'Mono'
enum TextSize
auto = 'Auto'
tiny = 'Tiny'
small = 'Small'
normal = 'Normal'
large = 'Large'
huge = 'Huge'
enum TablePos
tl = 'Top Left'
tc = 'Top Center'
tr = 'Top Right'
ml = 'Middle Left'
mc = 'Middle Center'
mr = 'Middle Right'
bl = 'Bottom Left'
bc = 'Bottom Center'
br = 'Bottom Right'
enum Layout
lanes = 'Lanes'
overlay = 'Overlay'
enum LineStyle
solid = 'Solid'
dashed = 'Dashed'
dotted = 'Dotted'
enum LabelMode
compact = 'Simple'
full = 'Full'
enum TableMode
full = 'Full'
hud = 'HUD'
enum Basis
day = 'Day'
sess = 'Session'
win = 'Window'
const string TIP_CAT = 'One asset per group gives the best model · yields in bp\n\nS&P 500 Index: SP:SPX · US equities · global risk benchmark\nNasdaq 100 Index: NASDAQ:NDX · US equities · tech risk\niShares Russell 2000 ETF: AMEX:IWM · US small caps · domestic risk appetite\nCBOE Volatility Index (VIX): TVC:VIX · volatility · equity fear\nICE BofA MOVE Index: TVC:MOVE · volatility · bond-market fear\nPHLX Semiconductor Index: PHLX:SOX · semis · chip supply chain\nDAX 40 Index: XETR:DAX · EU equities · European risk\nNikkei 225 Index: TVC:NI225 · JP equities · Japanese risk\nHang Seng Index: HKEX:HSI · CN equities · Chinese risk\niShares MSCI Emerging Markets ETF: AMEX:EEM · EM equities · emerging-market risk\nUS 10-Year Treasury Yield: TVC:US10Y · US rates · world price of money\nUS 2-Year Treasury Yield: TVC:US02Y · US rates · Fed expectations\nUS 30-Year Treasury Yield: TVC:US30Y · US rates · long end / term premium\niShares TIPS Bond ETF: AMEX:TIP · real rates · intraday real-yield proxy\niShares High Yield Corp Bond ETF: AMEX:HYG · credit · credit-market health\nGermany 10-Year Bund Yield: TVC:DE10Y · EU rates · ECB policy\nJapan 10-Year JGB Yield: TVC:JP10Y · JP rates · Japanese capital flows\nUS Dollar Index: TVC:DXY · USD · reserve-currency strength\nEuro / US Dollar: FX:EURUSD · USD · most traded pair\nUS Dollar / Japanese Yen: FX:USDJPY · JPY · carry trade\nBritish Pound / US Dollar: FX:GBPUSD · USD · UK risk\nUS Dollar / Offshore Yuan: FX:USDCNH · China · Chinese flows\nAustralian Dollar / US Dollar: FX:AUDUSD · commodity FX · commodity / China risk\nUS Dollar / Swiss Franc: FX:USDCHF · CHF · European safe haven\nGold Spot: OANDA:XAUUSD · gold · safe haven\nVanEck Gold Miners ETF: AMEX:GDX · gold miners · leveraged gold equity\nSilver Spot: TVC:SILVER · precious · sibling of gold\nBrent Crude Oil: TVC:UKOIL · oil · inflation / geopolitics\nCopper Futures: COMEX:HG1! · industrial · global growth\nDutch TTF Natural Gas: ICEEUR:TFM1! · gas · European energy\nNVIDIA Corporation: NASDAQ:NVDA · semis · AI cycle\nBitcoin: BINANCE:BTCUSDT · crypto · speculative liquidity\nEthereum: BINANCE:ETHUSDT · crypto · #2 crypto asset\nBitcoin Dominance: CRYPTOCAP:BTC.D · crypto · rotation inside crypto'
const string TIP_INV = 'Flips the line vertically, so an inversely related asset (e.g. DXY or yields vs. gold) moves with the chart while the relation holds. Prices and statistics are never inverted.'
// ────────
// >INPUTS< ⑵
// ─────▾──
const string g_a1 = 'Asset 1'
bool i_a1On = input.bool (true, 'Symbol', group = g_a1, display = display.none, inline = 'a1')
AssetPick i_a1 = input.enum (AssetPick.us10y, '', group = g_a1, display = display.none, inline = 'a1')
color i_a1Col = input.color (#E91E63, '', group = g_a1, display = display.none, inline = 'a1', tooltip = TIP_CAT + '\n\nColor: used when Lines · Palette = Custom.')
bool i_a1Inv = input.bool (true, 'Invert Line', group = g_a1, display = display.none, tooltip = TIP_INV)
string i_a1Sym = input.symbol ('OANDA:XAUUSD', 'Custom Symbol', group = g_a1, display = display.none, active = i_a1 == AssetPick.custom, tooltip = 'Used only when Symbol = Custom Symbol.\nCustom symbols are measured as prices (log returns); pick yields from the catalog so they are measured in bp.')
const string g_a2 = 'Asset 2'
bool i_a2On = input.bool (true, 'Symbol', group = g_a2, display = display.none, inline = 'a2')
AssetPick i_a2 = input.enum (AssetPick.dxy, '', group = g_a2, display = display.none, inline = 'a2')
color i_a2Col = input.color (#2196F3, '', group = g_a2, display = display.none, inline = 'a2', tooltip = TIP_CAT + '\n\nColor: used when Lines · Palette = Custom.')
bool i_a2Inv = input.bool (true, 'Invert Line', group = g_a2, display = display.none, tooltip = TIP_INV)
string i_a2Sym = input.symbol ('OANDA:XAUUSD', 'Custom Symbol', group = g_a2, display = display.none, active = i_a2 == AssetPick.custom, tooltip = 'Used only when Symbol = Custom Symbol.\nCustom symbols are measured as prices (log returns); pick yields from the catalog so they are measured in bp.')
const string g_a3 = 'Asset 3'
bool i_a3On = input.bool (true, 'Symbol', group = g_a3, display = display.none, inline = 'a3')
AssetPick i_a3 = input.enum (AssetPick.brent, '', group = g_a3, display = display.none, inline = 'a3')
color i_a3Col = input.color (#4CAF50, '', group = g_a3, display = display.none, inline = 'a3', tooltip = TIP_CAT + '\n\nColor: used when Lines · Palette = Custom.')
bool i_a3Inv = input.bool (false, 'Invert Line', group = g_a3, display = display.none, tooltip = TIP_INV)
string i_a3Sym = input.symbol ('OANDA:XAUUSD', 'Custom Symbol', group = g_a3, display = display.none, active = i_a3 == AssetPick.custom, tooltip = 'Used only when Symbol = Custom Symbol.\nCustom symbols are measured as prices (log returns); pick yields from the catalog so they are measured in bp.')
const string g_a4 = 'Asset 4'
bool i_a4On = input.bool (true, 'Symbol', group = g_a4, display = display.none, inline = 'a4')
AssetPick i_a4 = input.enum (AssetPick.spx, '', group = g_a4, display = display.none, inline = 'a4')
color i_a4Col = input.color (#AB47BC, '', group = g_a4, display = display.none, inline = 'a4', tooltip = TIP_CAT + '\n\nColor: used when Lines · Palette = Custom.')
bool i_a4Inv = input.bool (false, 'Invert Line', group = g_a4, display = display.none, tooltip = TIP_INV)
string i_a4Sym = input.symbol ('OANDA:XAUUSD', 'Custom Symbol', group = g_a4, display = display.none, active = i_a4 == AssetPick.custom, tooltip = 'Used only when Symbol = Custom Symbol.\nCustom symbols are measured as prices (log returns); pick yields from the catalog so they are measured in bp.')
const string g_a5 = 'Asset 5'
bool i_a5On = input.bool (true, 'Symbol', group = g_a5, display = display.none, inline = 'a5')
AssetPick i_a5 = input.enum (AssetPick.jpy, '', group = g_a5, display = display.none, inline = 'a5')
color i_a5Col = input.color (#B0BEC5, '', group = g_a5, display = display.none, inline = 'a5', tooltip = TIP_CAT + '\n\nColor: used when Lines · Palette = Custom.')
bool i_a5Inv = input.bool (true, 'Invert Line', group = g_a5, display = display.none, tooltip = TIP_INV)
string i_a5Sym = input.symbol ('OANDA:XAUUSD', 'Custom Symbol', group = g_a5, display = display.none, active = i_a5 == AssetPick.custom, tooltip = 'Used only when Symbol = Custom Symbol.\nCustom symbols are measured as prices (log returns); pick yields from the catalog so they are measured in bp.')
const string g_lne = 'Lines'
Palette i_palette = input.enum (Palette.custom, 'Lines · Palette', group = g_lne, display = display.none, tooltip = 'Custom uses the color set in each Asset group.')
Layout i_layout = input.enum (Layout.lanes, 'Lines · Layout', group = g_lne, display = display.none, tooltip = 'Lanes: one lane per asset, so the lines never pile up at the live price.\nOverlay: every line uses the full chart range.')
bool i_laneBox = input.bool (true, 'Lane · Boxes', group = g_lne, display = display.none, active = i_layout == Layout.lanes, tooltip = 'Faint lane background with the asset name and its real price at the lane top and bottom.')
int i_laneGap = input.int (15, 'Lane · Gap %', group = g_lne, display = display.none, minval = 0, maxval = 60, active = i_layout == Layout.lanes, tooltip = 'Empty space between lanes, as % of a lane height.')
int i_window = input.int (300, 'Lines · Window (bars)', group = g_lne, display = display.none, minval = 20, maxval = 2000, tooltip = 'Bars drawn back from the last bar. Each line is fitted to its lane by ONE linear transform, so its shape is kept.\nMust cover the start of the change basis (a full day on intraday charts).')
int i_lineW = input.int (1, 'Lines · Width', group = g_lne, display = display.none, minval = 1, maxval = 4)
LineStyle i_lineStyle = input.enum (LineStyle.solid, 'Lines · Style', group = g_lne, display = display.none)
bool i_focus = input.bool (false, 'Lines · Focus Mode', group = g_lne, display = display.none, tooltip = 'Dims every line except the main driver (★) and assets with an unusual move (⚡).')
const string g_ovl = 'Overlays'
bool i_tailOn = input.bool (true, 'Tail · Show', group = g_ovl, display = display.none, tooltip = 'Redraws the last bars of an asset in the warning color while its move is unusual (⚡).')
int i_tailLen = input.int (20, 'Tail · Length (bars)', group = g_ovl, display = display.none, minval = 3, maxval = 200, active = i_tailOn)
color i_warnCol = input.color (#FF9800, 'Warning Color', group = g_ovl, display = display.none, tooltip = 'Tails, gap zone and flagged table cells.')
bool i_anchorDot = input.bool (true, 'Basis · Anchor Arrows', group = g_ovl, display = display.none, tooltip = '▼ above every line at the bar the change basis is measured from.\nHover it for the base price and the change since then.')
bool i_ghostOn = input.bool (true, 'Macro · Ghost Line', group = g_ovl, display = display.none, tooltip = 'Dotted path the chart symbol would have followed since the basis start if it had moved exactly as the macro model implies.')
bool i_gapZone = input.bool (true, 'Macro · Gap Zone', group = g_ovl, display = display.none, active = i_ghostOn, tooltip = 'Shaded zone at the last bar between the actual price and the macro-implied price.')
const string g_lbl = 'Labels'
bool i_lblOn = input.bool (true, 'Labels · Show', group = g_lbl, display = display.none)
LabelMode i_lblMode = input.enum (LabelMode.full, 'Labels · Mode', group = g_lbl, display = display.none, tooltip = 'Simple: asset name only, in the asset color.\nFull: name, price, change, impact arrow and flags.\nDetails are always in the tooltip.')
TextSize i_lblSz = input.enum (TextSize.small, 'Labels · Size', group = g_lbl, display = display.none)
int i_lblShift = input.int (2, 'Labels · Offset (bars)', group = g_lbl, display = display.none, minval = 0, maxval = 50)
const string g_tbl = 'Table'
bool i_tblOn = input.bool (true, 'Table · Show', group = g_tbl, display = display.none)
TableMode i_tblMode = input.enum (TableMode.full, 'Table · Mode', group = g_tbl, display = display.none, tooltip = 'Full: one row per asset plus the macro row.\nHUD: a compact one-line strip.')
TablePos i_tblPosE = input.enum (TablePos.tr, 'Table · Position', group = g_tbl, display = display.none)
TextSize i_tblSz = input.enum (TextSize.small, 'Table · Text Size', group = g_tbl, display = display.none)
const string g_sta = 'Statistics'
Basis i_basis = input.enum (Basis.day, 'Change · Basis', group = g_sta, display = display.none, tooltip = 'Moment every change, σ-move and macro value is measured from (the same bar for all assets):\nDay: start of the chart\'s trading day (previous bar above D).\nSession: start of the session below (intraday only).\nWindow: first bar of the window.\nYields in basis points (bp).')
string i_sess = input.session ('0930-1600', 'Change · Session', group = g_sta, display = display.none, active = i_basis == Basis.sess)
string i_tz = input.string ('America/New_York', 'Change · Timezone', group = g_sta, display = display.none, options = ['America/New_York', 'Europe/London', 'Asia/Tokyo', 'UTC'], active = i_basis == Basis.sess, tooltip = 'New York handles DST.')
string i_corrTf = input.timeframe('D', 'Statistics · Timeframe', group = g_sta, display = display.none, tooltip = 'All statistics use completed bars of this FIXED timeframe, so they do not change with the chart timeframe. Periods are matched by calendar; only periods where the symbols traded together count. D is recommended.')
int i_corrLen = input.int (60, 'Statistics · Length', group = g_sta, display = display.none, minval = 30, maxval = 400, tooltip = 'Matched periods used by every statistic and by the macro model.\n⇈ ⇊ strong · ↑ ↓ significant (95% interval excludes 0) · ○ none · ⟳ changing.')
bool i_robust = input.bool (true, 'Statistics · Clip ±3σ', group = g_sta, display = display.none, tooltip = 'Clips news-day spikes before every statistic, so one extreme day cannot dominate.')
const string g_thr = 'Thresholds & Model'
float i_rStrong = input.float (0.70, 'Relation · Strong |r|', group = g_thr, display = display.none, minval = 0.3, maxval = 0.95, step = 0.05, tooltip = 'Correlation at or above this level is marked strong (⇈ ⇊).')
float i_zFlag = input.float (2.0, 'Flag · Level (σ)', group = g_thr, display = display.none, minval = 1.0, maxval = 4.0, step = 0.1, tooltip = 'Unusual move (⚡) and macro gap (⚠) are flagged at or above this many σ.')
int i_stabLen = input.int (20, 'Stability · Window', group = g_thr, display = display.none, minval = 10, maxval = 100, tooltip = 'Recent periods compared with the full Statistics · Length.')
float i_stabShift = input.float (0.30, 'Stability · Shift |Δr|', group = g_thr, display = display.none, minval = 0.1, maxval = 1.0, step = 0.05, tooltip = 'Relation is marked changing (⟳) when the recent r differs from the full r by at least this much.')
float i_ridge = input.float (0.05, 'Model · Ridge λ', group = g_thr, display = display.none, minval = 0.0, maxval = 1.0, step = 0.01, tooltip = 'Shrinks the model β toward zero. Higher = more stable when the selected assets move together (e.g. DXY + EURUSD); 0 = plain least squares.')
float i_macroK = input.float (2.0, 'Model · Score Scale (σ)', group = g_thr, display = display.none, minval = 0.5, maxval = 5.0, step = 0.5, tooltip = 'Implied move (in σ of the chart symbol) that maps to a macro score of ±0.76. Lower = a more sensitive score.')
const string g_alr = 'Alerts'
bool i_alGap = input.bool (true, 'Alert · Macro Gap', group = g_alr, display = display.none, tooltip = 'Fires once when the macro gap reaches Flag · Level (realtime). Create the alert with "Any alert() function call".')
bool i_alMove = input.bool (true, 'Alert · Unusual Move', group = g_alr, display = display.none, tooltip = 'Fires once when an asset move reaches Flag · Level (realtime).')
// ────────────
// >VALIDATION< ⑶
// ─────────▾──
if i_stabLen >= i_corrLen
runtime.error('Stability · Window must be shorter than Statistics · Length.')
if i_tailLen > i_window
runtime.error('Tail · Length must not exceed Lines · Window.')
// ───────
// >TYPES< ⑷
// ────▾──
// @type one catalog entry.
type CatItem
string name
string sym
string tag
string grp
bool isY = false
// @type one asset slot: inputs, data, cached statistics and drawings.
type Asset
string name
string sym
string tag
string grp
bool isY = false
bool inv = false
bool on = false
color col
array<float> buf // chart-timeframe closes over the window
array<float> hist // [key, close] on the statistics timeframe (last bar only)
float x // live close
float pd // previous daily close (Day-basis fallback)
int ageMin = 0 // minutes since the asset's last bar
// statistics, cached per completed period (varip: kept across realtime ticks)
varip float r
varip float rLo
varip float rHi
varip float r20
varip float sdA // σ per period (log return, or bp for yields)
varip int k = 0
varip float bm // model β: chart log move per unit of this asset's move
varip bool flMove = false // alert state
// analytics of the current bar
float base
float move // since the basis (log, or bp)
float zMove // move in σ, scaled to the elapsed time
float impact // model contribution to the chart move (log)
bool unusual = false
bool stale = false
bool changing = false
float hSc // σ scale of this asset's move (√ elapsed share of a period)
// drawing state
bool drawn = false
float xLo
float xHi
float kf
float tHi
float tLo
float yEnd
float pos
polyline pl
polyline plw
label lb
label dot
box bx
// @type collections cannot hold collections: a calendar map wrapped in an object.
type KeyMap
map<float, float> m
// ─────────
// >CATALOG< ⑸
// ──────▾──
var array<CatItem> CAT = array.from(
CatItem.new('S&P 500 Index', 'SP:SPX', 'SPX', 'US equities', false),
CatItem.new('Nasdaq 100 Index', 'NASDAQ:NDX', 'NDX', 'US equities', false),
CatItem.new('iShares Russell 2000 ETF', 'AMEX:IWM', 'IWM', 'US small caps', false),
CatItem.new('CBOE Volatility Index (VIX)', 'TVC:VIX', 'VIX', 'volatility', false),
CatItem.new('ICE BofA MOVE Index', 'TVC:MOVE', 'MOVE', 'volatility', false),
CatItem.new('PHLX Semiconductor Index', 'PHLX:SOX', 'SOX', 'semis', false),
CatItem.new('DAX 40 Index', 'XETR:DAX', 'DAX', 'EU equities', false),
CatItem.new('Nikkei 225 Index', 'TVC:NI225', 'NI225', 'JP equities', false),
CatItem.new('Hang Seng Index', 'HKEX:HSI', 'HSI', 'CN equities', false),
CatItem.new('iShares MSCI Emerging Markets ETF', 'AMEX:EEM', 'EEM', 'EM equities', false),
CatItem.new('US 10-Year Treasury Yield', 'TVC:US10Y', 'US10Y', 'US rates', true),
CatItem.new('US 2-Year Treasury Yield', 'TVC:US02Y', 'US02Y', 'US rates', true),
CatItem.new('US 30-Year Treasury Yield', 'TVC:US30Y', 'US30Y', 'US rates', true),
CatItem.new('iShares TIPS Bond ETF', 'AMEX:TIP', 'TIP', 'real rates', false),
CatItem.new('iShares High Yield Corp Bond ETF', 'AMEX:HYG', 'HYG', 'credit', false),
CatItem.new('Germany 10-Year Bund Yield', 'TVC:DE10Y', 'DE10Y', 'EU rates', true),
CatItem.new('Japan 10-Year JGB Yield', 'TVC:JP10Y', 'JP10Y', 'JP rates', true),
CatItem.new('US Dollar Index', 'TVC:DXY', 'DXY', 'USD', false),
CatItem.new('Euro / US Dollar', 'FX:EURUSD', 'EURUSD', 'USD', false),
CatItem.new('US Dollar / Japanese Yen', 'FX:USDJPY', 'USDJPY', 'JPY', false),
CatItem.new('British Pound / US Dollar', 'FX:GBPUSD', 'GBPUSD', 'USD', false),
CatItem.new('US Dollar / Offshore Yuan', 'FX:USDCNH', 'USDCNH', 'China', false),
CatItem.new('Australian Dollar / US Dollar', 'FX:AUDUSD', 'AUDUSD', 'commodity FX', false),
CatItem.new('US Dollar / Swiss Franc', 'FX:USDCHF', 'USDCHF', 'CHF', false),
CatItem.new('Gold Spot', 'OANDA:XAUUSD', 'XAUUSD', 'gold', false),
CatItem.new('VanEck Gold Miners ETF', 'AMEX:GDX', 'GDX', 'gold miners', false),
CatItem.new('Silver Spot', 'TVC:SILVER', 'SILVER', 'precious', false),
CatItem.new('Brent Crude Oil', 'TVC:UKOIL', 'BRENT', 'oil', false),
CatItem.new('Copper Futures', 'COMEX:HG1!', 'COPPER', 'industrial', false),
CatItem.new('Dutch TTF Natural Gas', 'ICEEUR:TFM1!', 'TTF', 'gas', false),
CatItem.new('NVIDIA Corporation', 'NASDAQ:NVDA', 'NVDA', 'semis', false),
CatItem.new('Bitcoin', 'BINANCE:BTCUSDT', 'BTC', 'crypto', false),
CatItem.new('Ethereum', 'BINANCE:ETHUSDT', 'ETH', 'crypto', false),
CatItem.new('Bitcoin Dominance', 'CRYPTOCAP:BTC.D', 'BTC.D', 'crypto', false))
// @function catalog index of a pick (−1 for None / Custom).
f_catIndex(AssetPick p) =>
switch p
AssetPick.spx => 0
AssetPick.ndx => 1
AssetPick.iwm => 2
AssetPick.vix => 3
AssetPick.move => 4
AssetPick.sox => 5
AssetPick.dax => 6
AssetPick.nky => 7
AssetPick.hsi => 8
AssetPick.eem => 9
AssetPick.us10y => 10
AssetPick.us02y => 11
AssetPick.us30y => 12
AssetPick.tip => 13
AssetPick.hyg => 14
AssetPick.de10y => 15
AssetPick.jp10y => 16
AssetPick.dxy => 17
AssetPick.eur => 18
AssetPick.jpy => 19
AssetPick.gbp => 20
AssetPick.cnh => 21
AssetPick.aud => 22
AssetPick.chf => 23
AssetPick.gold => 24
AssetPick.gdx => 25
AssetPick.silver => 26
AssetPick.brent => 27
AssetPick.copper => 28
AssetPick.ttf => 29
AssetPick.nvda => 30
AssetPick.btc => 31
AssetPick.eth => 32
AssetPick.btcd => 33
=> -1
// ─────────
// >HELPERS< ⑹
// ──────▾──
// @function ticker without exchange prefix.
f_ticker(string sym) =>
array<string> p = str.split(sym, ':')
p.size() > 0 ? p.last() : sym
// @function signed number ('—' when na).
f_sgn(float v, string fmt) =>
na(v) ? '—' : (v >= 0 ? '+' : '') + str.tostring(v, fmt)
// @function log move → signed % text.
f_pct(float lg) =>
na(lg) ? '—' : f_sgn((math.exp(lg) - 1.0) * 100.0, '0.00') + '%'
// @function price with decimals adapted to its size (4,152.3 · 99.85 · 4.251 · 0.6543).
f_px(float v) =>
float a = math.abs(nz(v))
na(v) ? '—' : str.tostring(v, a >= 1000 ? '#,##0.0' : a >= 10 ? '#,##0.00' : a >= 1 ? '0.000' : '0.0000')
// @function readable text color for a background.
f_ink(color bg) =>
0.299 * color.r(bg) + 0.587 * color.g(bg) + 0.114 * color.b(bg) > 150 ? color.black : color.white
// @function text size option → size.* constant.
f_size(TextSize t) =>
switch t
TextSize.auto => size.auto
TextSize.tiny => size.tiny
TextSize.normal => size.normal
TextSize.large => size.large
TextSize.huge => size.huge
=> size.small
// @function table position option → position.* constant.
f_tblPos(TablePos p) =>
switch p
TablePos.tl => position.top_left
TablePos.tc => position.top_center
TablePos.ml => position.middle_left
TablePos.mc => position.middle_center
TablePos.mr => position.middle_right
TablePos.bl => position.bottom_left
TablePos.bc => position.bottom_center
TablePos.br => position.bottom_right
=> position.top_right
// @function slot color from the palette.
f_palette(int i, color custom) =>
switch i_palette
Palette.vivid => array.from(#FF1744, #2979FF, #00E676, #FFC400, #D500F9).get(i)
Palette.pastel => array.from(#F48FB1, #90CAF9, #A5D6A7, #FFE082, #CE93D8).get(i)
Palette.cb => array.from(#E69F00, #56B4E9, #009E73, #F0E442, #CC79A7).get(i)
Palette.mono => color.new(chart.fg_color, 10 + i * 15)
=> custom
// @function bounded tanh.
f_tanh(float x) =>
float e = math.exp(2.0 * math.max(math.min(x, 20.0), -20.0))
(e - 1.0) / (e + 1.0)
// @function move from a to b in model units: bp for yields, log return otherwise.
f_ret(float a, float b, bool isY) =>
isY ? (b - a) * 100.0 : a > 0 and b > 0 ? math.log(b / a) : na
// @function clip to mean ± 3σ in place (when Statistics · Clip is on).
f_clip(array<float> v) =>
if i_robust and v.size() > 2
float m = v.avg()
float sd = v.stdev()
for [i, e] in v
v.set(i, math.max(m - 3.0 * sd, math.min(m + 3.0 * sd, e)))
// @function Pearson r of the last cnt values of two equal-length arrays.
f_pearson(array<float> x, array<float> y, int cnt) =>
int m = x.size()
bool ok = cnt >= 10 and cnt <= m
float sx = 0.0
float sy = 0.0
float sxy = 0.0
float sxx = 0.0
float syy = 0.0
if ok
for t = m - cnt to m - 1
float a = x.get(t)
float b = y.get(t)
sx += a
sy += b
sxy += a * b
sxx += a * a
syy += b * b
float vx = ok ? sxx - sx * sx / cnt : 0.0
float vy = ok ? syy - sy * sy / cnt : 0.0
vx > 0 and vy > 0 ? (sxy - sx * sy / cnt) / math.sqrt(vx * vy) : na
// resolved display settings
string lblSize = f_size(i_lblSz)
string tblSize = f_size(i_tblSz)
string tblPos = f_tblPos(i_tblPosE)
// ────────────
// >STATISTICS< ⑺
// ─────────▾──
// @function true when the chart symbol is a catalog yield (its moves are then measured in bp, like any yield).
f_chartIsY() =>
bool y = false
for c in CAT
if c.isY and f_ticker(c.sym) == syminfo.ticker
y := true
y
var bool chartIsY = f_chartIsY()
// @function chart-unit move text: bp for a yield chart, % otherwise.
f_chg(float v) =>
na(v) ? '—' : chartIsY ? f_sgn(v, '0.0') + 'bp' : f_pct(v)
// @function runs in the requested context: interleaved [periodKey, close] of the last `cap` completed bars.
// periodKey = calendar bucket of the bar close (UTC day for D, calendar month for M); pMs comes from the chart,
// so every symbol uses the same buckets.
f_hist(simple int cap, simple float pMs) =>
var array<float> h = array.new<float>()
float c1 = close[1]
int tc = time_close[1] - 1
float k1 = na(tc) ? na : pMs >= 2419200000.0 ? year(tc, 'UTC') * 12 + month(tc, 'UTC') : math.floor(tc / pMs) // ≥ 28 days: real calendar months
if not na(c1) and not na(k1)
h.push(k1)
h.push(c1)
if h.size() > cap * 2
h.shift()
h.shift()
h
// @function last period key of a history (na when empty).
f_lastKey(array<float> h) =>
na(h) or h.size() < 2 ? na : h.get(h.size() - 2)
// @function pairwise statistics of an asset vs. the chart over the last n periods both traded.
// @returns [r, rLo, rHi, rRecent, assetσ, pairs] — rLo/rHi: 95% Fisher interval.
f_pairStats(array<float> ha, array<float> hb, int n, bool isY) =>
array<float> ra = array.new<float>()
array<float> rb = array.new<float>()
float pa = na
float pb = na
int i = 0
int j = 0
while i < ha.size() and j < hb.size()
float ka = ha.get(i)
float kb = hb.get(j)
if ka == kb
float a = ha.get(i + 1)
float b = hb.get(j + 1)
if not na(pa)
float x = f_ret(pa, a, isY)
float y = f_ret(pb, b, chartIsY)
if not na(x) and not na(y)
ra.push(x)
rb.push(y)
pa := a
pb := b
i += 2
j += 2
else if ka < kb
i += 2
else
j += 2
int m = ra.size()
if m > n
ra := ra.slice(m - n, m).copy()
rb := rb.slice(m - n, m).copy()
f_clip(ra)
f_clip(rb)
int k = ra.size()
float r = f_pearson(ra, rb, k)
float rR = f_pearson(ra, rb, math.min(i_stabLen, k))
float se = k > 3 ? 1.0 / math.sqrt(k - 3) : na
float rc = na(r) ? na : math.max(-0.9999, math.min(0.9999, r))
float fz = na(rc) ? na : 0.5 * math.log((1.0 + rc) / (1.0 - rc))
float lo = na(fz) or na(se) ? na : f_tanh(fz - 1.96 * se)
float hi = na(fz) or na(se) ? na : f_tanh(fz + 1.96 * se)
[r, lo, hi, rR, k > 2 ? ra.stdev() : na, k]
// @function solves A·x = b (p×p, row-major) by Gaussian elimination with partial pivoting; x = na when singular.
// Inner loops run only when c < p − 1: a Pine `for` with from > to runs BACKWARDS and would leave the matrix.
f_solve(array<float> A, array<float> b, int p) =>
array<float> M = A.copy()
array<float> v = b.copy()
array<float> x = array.new<float>(p, na)
bool ok = true
for c = 0 to p - 1
bool more = c < p - 1
int piv = c
float big = math.abs(M.get(c * p + c))
if more
for rr = c + 1 to p - 1
if math.abs(M.get(rr * p + c)) > big
big := math.abs(M.get(rr * p + c))
piv := rr
if big < 1e-12
ok := false
break
if piv != c
for cc = 0 to p - 1
float t = M.get(c * p + cc)
M.set(c * p + cc, M.get(piv * p + cc))
M.set(piv * p + cc, t)
float tv = v.get(c)
v.set(c, v.get(piv))
v.set(piv, tv)
if more
for rr = c + 1 to p - 1
float f = M.get(rr * p + c) / M.get(c * p + c)
for cc = c to p - 1
M.set(rr * p + cc, M.get(rr * p + cc) - f * M.get(c * p + cc))
v.set(rr, v.get(rr) - f * v.get(c))
if ok
for c = p - 1 to 0
float s = v.get(c)
if c < p - 1
for cc = c + 1 to p - 1
s -= M.get(c * p + cc) * x.get(cc)
x.set(c, s / M.get(c * p + c))
x
// @function ridge fit of Y on X over rows [t0, t1): standardized normal equations + λ.
// @returns [β in real units, regressor means, Y mean]
f_ridge(array<float> X, array<float> Y, int p, int t0, int t1) =>
int k = t1 - t0
array<float> mx = array.new<float>(p, 0.0)
array<float> sx = array.new<float>(p, 0.0)
float my = 0.0
float sy = 0.0
for t = t0 to t1 - 1
my += Y.get(t) / k
for c = 0 to p - 1
mx.set(c, mx.get(c) + X.get(t * p + c) / k)
for t = t0 to t1 - 1
sy += math.pow(Y.get(t) - my, 2) / k
for c = 0 to p - 1
sx.set(c, sx.get(c) + math.pow(X.get(t * p + c) - mx.get(c), 2) / k)
sy := math.sqrt(sy)
for c = 0 to p - 1
sx.set(c, math.sqrt(sx.get(c)))
array<float> A = array.new<float>(p * p, 0.0)
array<float> g = array.new<float>(p, 0.0)
for t = t0 to t1 - 1
float zy = sy > 0 ? (Y.get(t) - my) / sy : 0.0
for c = 0 to p - 1
float zc = sx.get(c) > 0 ? (X.get(t * p + c) - mx.get(c)) / sx.get(c) : 0.0
g.set(c, g.get(c) + zc * zy / k)
for d = 0 to p - 1
float zd = sx.get(d) > 0 ? (X.get(t * p + d) - mx.get(d)) / sx.get(d) : 0.0
A.set(c * p + d, A.get(c * p + d) + zc * zd / k)
for c = 0 to p - 1
A.set(c * p + c, A.get(c * p + c) + i_ridge)
array<float> bz = f_solve(A, g, p)
array<float> b = array.new<float>(p, na)
if not na(bz.get(0))
for c = 0 to p - 1
b.set(c, sx.get(c) > 0 ? bz.get(c) * sy / sx.get(c) : 0.0)
[b, mx, my]
// @function residual and total sum of squares of a fit over rows [t0, t1) (total vs. the fit's own Y mean).
f_sse(array<float> X, array<float> Y, int p, int t0, int t1, array<float> b, array<float> mx, float my) =>
float ssr = 0.0
float sst = 0.0
for t = t0 to t1 - 1
float fit = my
for c = 0 to p - 1
fit += b.get(c) * (X.get(t * p + c) - mx.get(c))
ssr += math.pow(Y.get(t) - fit, 2)
sst += math.pow(Y.get(t) - my, 2)
[ssr, sst]
// @function macro model: ridge regression of the chart's returns on ALL active assets at once, over calendar-matched
// periods where every symbol traded. Each β is the asset's independent effect (overlapping assets are not
// counted twice). Writes β into Asset.bm.
// @returns [adjusted R², residual σ per period, periods, out-of-sample R² (fit on first ⅔, tested on last ⅓)]
f_model(array<Asset> slots, array<float> hb, int n) =>
array<int> act = array.new<int>()
for [i, a] in slots
a.bm := na
if a.on and not na(a.hist) and a.hist.size() >= 4
act.push(i)
int p = act.size()
float r2 = na
float sd = na
float oos = na
int k = 0
if p > 0 and not na(hb) and hb.size() >= 4
// calendar map of every active asset
array<KeyMap> maps = array.new<KeyMap>()
for i in act
map<float, float> m = map.new<float, float>()
array<float> h = slots.get(i).hist
for t = 0 to h.size() - 2 by 2
m.put(h.get(t), h.get(t + 1))
maps.push(KeyMap.new(m))
// returns between consecutive periods where ALL symbols traded
array<float> Y = array.new<float>()
array<float> X = array.new<float>() // row-major, p columns
array<float> pr = array.new<float>(p, na)
float pb = na
for t = 0 to hb.size() - 2 by 2
float kb = hb.get(t)
bool both = true
for w in maps
both := both and w.m.contains(kb)
if both
float b = hb.get(t + 1)
bool ok = not na(pb)
array<float> row = array.new<float>()
for [c, w] in maps
float v = w.m.get(kb)
float x = ok ? f_ret(pr.get(c), v, slots.get(act.get(c)).isY) : na
ok := ok and not na(x)
row.push(x)
pr.set(c, v)
float y = ok ? f_ret(pb, b, chartIsY) : na
if ok and not na(y)
Y.push(y)
X.concat(row)
pb := b
int m0 = Y.size()
if m0 > n
Y := Y.slice(m0 - n, m0).copy()
X := X.slice((m0 - n) * p, m0 * p).copy()
k := Y.size()
if k >= 20 + p
// clip every column once, for both fits
f_clip(Y)
for c = 0 to p - 1
array<float> col = array.new<float>()
for t = 0 to k - 1
col.push(X.get(t * p + c))
f_clip(col)
for t = 0 to k - 1
X.set(t * p + c, col.get(t))
// full fit → β, adjusted R², residual σ
[bf, mxf, myf] = f_ridge(X, Y, p, 0, k)
if not na(bf.get(0))
for c = 0 to p - 1
Asset q = slots.get(act.get(c))
q.bm := bf.get(c)
[ssr, sst] = f_sse(X, Y, p, 0, k, bf, mxf, myf)
float r2r = sst > 0 ? 1.0 - ssr / sst : na
r2 := na(r2r) ? na : math.max(0.0, 1.0 - (1.0 - r2r) * (k - 1) / math.max(k - p - 1, 1))
sd := math.sqrt(ssr / math.max(k - p - 1, 1))
// honest fit: train on the first ⅔, score the last ⅓ against the training mean
int cut = int(math.floor(k * 2.0 / 3.0))
if cut >= 20 + p and k - cut >= 10
[bt, mxt, myt] = f_ridge(X, Y, p, 0, cut)
if not na(bt.get(0))
[sse, sso] = f_sse(X, Y, p, cut, k, bt, mxt, myt)
oos := sso > 0 ? 1.0 - sse / sso : na
[r2, sd, k, oos]
// @function share of a typical statistics period elapsed since bar jB, measured on the series' own activity
// (bars where its price changed), so a 6.5 h stock session and a 23 h gold session are both scaled
// correctly. na when the window holds fewer than two periods (caller falls back to clock time).
f_elapsed(array<float> v, array<bool> pf, int jB) =>
int periods = 0
for f in pf
periods += f ? 1 : 0
int tot = 0
int el = 0
if v.size() > 1
for j = 1 to v.size() - 1
float a = v.get(j - 1)
float b = v.get(j)
if not na(a) and not na(b) and a != b
tot += 1
el += j > jB ? 1 : 0
periods >= 2 and tot > 0 ? float(el) / (float(tot) / periods) : na
// @function relation icon, wording and significance from r and its 95% interval.
// @returns [icon, wording, significant]
f_relation(float r, float lo, float hi) =>
bool nd = na(r) or na(lo)
bool sig = not nd and (lo > 0 or hi < 0)
string ic = nd ? '·' : not sig ? '○' : r >= i_rStrong ? '⇈' : r > 0 ? '↑' : r <= -i_rStrong ? '⇊' : '↓'
string rw = nd ? 'not enough data' : not sig ? 'no significant relation' : (math.abs(r) >= i_rStrong ? 'strong ' : '') + (r > 0 ? 'positive' : 'negative')
[ic, rw, sig]
// ──────
// >DATA< ⑻
// ───▾──
// @function builds one asset slot from its inputs.
f_newAsset(int slot, AssetPick pick, string custom, bool show, bool inv, color col) =>
int i = f_catIndex(pick)
bool cus = pick == AssetPick.custom
CatItem c = i >= 0 ? CAT.get(i) : na
string sym = cus ? custom : i >= 0 ? c.sym : ''
bool on = show and sym != '' and f_ticker(sym) != syminfo.ticker // never compare the chart with itself
Asset.new(cus ? custom : i >= 0 ? c.name : '', sym, cus ? f_ticker(custom) : i >= 0 ? c.tag : '', cus ? 'custom' : i >= 0 ? c.grp : '',
i >= 0 ? c.isY : false, inv, on, f_palette(slot, col), array.new<float>())
var array<Asset> assets = array.from(
f_newAsset(0, i_a1, i_a1Sym, i_a1On, i_a1Inv, i_a1Col),
f_newAsset(1, i_a2, i_a2Sym, i_a2On, i_a2Inv, i_a2Col),
f_newAsset(2, i_a3, i_a3Sym, i_a3On, i_a3Inv, i_a3Col),
f_newAsset(3, i_a4, i_a4Sym, i_a4On, i_a4Inv, i_a4Col),
f_newAsset(4, i_a5, i_a5Sym, i_a5On, i_a5Inv, i_a5Col))
// the same symbol in two slots adds nothing: keep the first
if barstate.isfirst
for i = 1 to assets.size() - 1
for j = 0 to i - 1
Asset ai = assets.get(i)
Asset aj = assets.get(j)
if ai.on and aj.on and ai.sym == aj.sym
ai.on := false
// >state
var array<float> chartBuf = array.new<float>() // chart closes over the window
var array<bool> periodBuf = array.new<bool>() // statistics-period starts over the window
var int dayStart = na
var int sessStart = na
varip float chartSd = na // chart σ per statistics period
varip float modelR2 = na // adjusted R² (in sample)
varip float modelOos = na // out-of-sample R²
varip float modelSd = na // residual σ per period
varip int modelN = 0 // periods in the model
varip float cacheKey = na // latest completed period already processed
varip bool gapFlag = false // macro-gap alert state
varip float macroScore = na // composite macro score, −1 … +1
int secChart = timeframe.in_seconds()
int secStat = timeframe.in_seconds(i_corrTf)
int histCap = int(math.ceil(i_corrLen * 1.5)) + 10 // own bars kept per symbol (room for non-shared periods)
int calcLtf = i_window * 3 + 5 // chart-TF bars: ×3 so 24/7 assets still cover a window that spans a weekend
int calcHtf = secStat == secChart ? calcLtf : histCap + 5 // identical contexts must use identical calc_bars_count
int calcDay = secStat == 86400 ? calcHtf : secChart == 86400 ? calcLtf : 5
float periodMs = secStat * 1000.0
bool intraday = secChart < 86400
bool inSession = intraday and not na(time(timeframe.period, i_sess, i_tz))
float chartHi = ta.highest(high, i_window)
float chartLo = ta.lowest (low, i_window)
float atr = ta.atr(14)
if timeframe.change('D')
dayStart := bar_index
if inSession and not inSession[1]
sessStart := bar_index
chartBuf.push(close)
periodBuf.push(timeframe.change(i_corrTf))
if chartBuf.size() > i_window
chartBuf.shift()
periodBuf.shift()
// >requests · chart symbol
array<float> chartHist = request.security(syminfo.tickerid, i_corrTf, f_hist(histCap, periodMs), lookahead = barmerge.lookahead_on, calc_bars_count = calcHtf)
float chartPd = request.security(syminfo.tickerid, 'D', close[1], lookahead = barmerge.lookahead_on, calc_bars_count = calcDay)
// >requests · assets (active slots only; the condition never changes between bars)
float keyNew = f_lastKey(chartHist)
for a in assets
if a.on
[x, t] = request.security(a.sym, timeframe.period, [close, time], ignore_invalid_symbol = true, calc_bars_count = calcLtf)
a.x := x
a.ageMin := na(t) ? 0 : int((time - t) / 60000)
a.pd := request.security(a.sym, 'D', close[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true, calc_bars_count = calcDay)
array<float> ha = request.security(a.sym, i_corrTf, f_hist(histCap, periodMs), lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true, calc_bars_count = calcHtf)
a.buf.push(x)
if a.buf.size() > i_window
a.buf.shift()
if barstate.islast
a.hist := ha
keyNew := math.max(nz(keyNew), nz(f_lastKey(ha)))
// >statistics · recomputed only when a new period has completed (cache hit on every other tick)
if barstate.islast and not na(chartHist) and (na(cacheKey) or keyNew != cacheKey)
for a in assets
if a.on and not na(a.hist)
[r, lo, hi, rR, sdA, k] = f_pairStats(a.hist, chartHist, i_corrLen, a.isY)
a.r := r
a.rLo := lo
a.rHi := hi
a.r20 := rR
a.sdA := sdA
a.k := k
array<float> gr = array.new<float>()
if chartHist.size() >= 4
for t = 2 to chartHist.size() - 2 by 2
float v = f_ret(chartHist.get(t - 1), chartHist.get(t + 1), chartIsY)
if not na(v)
gr.push(v)
if gr.size() > i_corrLen
gr := gr.slice(gr.size() - i_corrLen, gr.size()).copy()
f_clip(gr)
chartSd := gr.size() > 2 ? gr.stdev() : na
[r2, sd, mk, oos] = f_model(assets, chartHist, i_corrLen)
modelR2 := r2
modelOos := oos
modelSd := sd
modelN := mk
cacheKey := keyNew
// ───────────
// >ANALYTICS< ⑼
// ────────▾──
// basis and macro values of the current bar (filled on the last bar, used by the rendering below)
int nWin = chartBuf.size()
int n0 = bar_index - nWin + 1
string bTag = na
int jB = -1
bool inBuf = false
float hSc = na
float gB = na
float gMv = na
float impl = na
float zImp = na
float zAct = na
float zGap = na
bool gapOn = false
bool reliable = false
int star = -1
if barstate.islast
// every move is measured from the same bar: the one just before the basis starts
Basis bSel = i_basis == Basis.sess and not intraday ? Basis.day : i_basis
bTag := bSel == Basis.win ? 'Window' : bSel == Basis.sess ? 'Session' : timeframe.in_seconds() > 86400 ? 'Bar' : 'Day' // above D the Day basis is the previous bar
int aIdx = bSel == Basis.win ? n0 : bSel == Basis.sess ? sessStart : dayStart
jB := bSel == Basis.win ? 0 : na(aIdx) ? -1 : aIdx - 1 - n0
inBuf := jB >= 0 and jB < nWin
// σ scales with √(share of a period elapsed since the base bar); clock time is only the fallback
float pDays = math.max(timeframe.in_seconds(i_corrTf), 60) / 86400.0
float hClk = inBuf ? math.max(nWin - 1 - jB, 1) * timeframe.in_seconds() / 86400.0 / pDays : 1.0
float hCh = inBuf ? f_elapsed(chartBuf, periodBuf, jB) : na
hSc := math.sqrt(math.max(nz(hCh, hClk), 0.001))
gB := inBuf ? chartBuf.get(jB) : bSel == Basis.day ? chartPd : na
gMv := f_ret(gB, close, chartIsY)
// per asset: move, σ-move, model impact, flags
float impSum = 0.0
bool impAny = false
bool impGap = false // a model asset without a move → the implied move would be partial
for a in assets
a.base := na
a.move := na
a.zMove := na
a.impact := na
a.unusual := false
if a.on and not na(a.x)
a.base := inBuf ? a.buf.get(jB) : bSel == Basis.day ? a.pd : na
a.move := f_ret(a.base, a.x, a.isY)
float hA = inBuf ? f_elapsed(a.buf, periodBuf, jB) : na
a.hSc := math.sqrt(math.max(nz(hA, hClk), 0.001))
a.zMove := a.sdA > 0 and not na(a.move) ? a.move / (a.sdA * a.hSc) : na
a.unusual := math.abs(nz(a.zMove)) >= i_zFlag
a.stale := a.ageMin > 2 * timeframe.in_seconds() / 60
a.changing := not na(a.r20) and not na(a.r) and math.abs(a.r20 - a.r) >= i_stabShift
if not na(a.bm) and not na(a.move)
a.impact := a.bm * a.move
impSum += a.impact
impAny := true
else if not na(a.bm)
impGap := true
if barstate.isrealtime and i_alMove and a.unusual and not a.flMove
alert('IMC · unusual ' + a.tag + ' move: ' + f_sgn(a.zMove, '0.0') + 'σ (' + bTag + ' basis)', alert.freq_once_per_bar)
a.flMove := a.unusual
// macro: implied chart move in chart σ → tanh; gap = actual − implied in model residual σ
impl := impAny and not impGap ? impSum : na
zImp := chartSd > 0 and not na(impl) ? impl / (chartSd * hSc) : na
zAct := chartSd > 0 and not na(gMv) ? gMv / (chartSd * hSc) : na
zGap := modelSd > 0 and not na(impl) and not na(gMv) ? (gMv - impl) / (modelSd * hSc) : na
macroScore := na(zImp) ? na : f_tanh(zImp / i_macroK)
reliable := not na(modelOos) and modelOos > 0
gapOn := reliable and math.abs(nz(zGap)) >= i_zFlag // no gap flag from a model that fails out of sample
if barstate.isrealtime and i_alGap and gapOn and not gapFlag
alert('IMC · ' + syminfo.ticker + ' departs from the macro picture: gap ' + f_sgn(zGap, '0.0') + 'σ, macro ' + f_sgn(macroScore, '0.00'), alert.freq_once_per_bar)
gapFlag := gapOn
// main driver = largest |impact|
float best = 0.0
for [i, a] in assets
if not na(a.impact) and math.abs(a.impact) > best
best := math.abs(a.impact)
star := i
// ───────────
// >RENDERING< ⑽
// ────────▾──
var table tbl = i_tblOn ? table.new(tblPos, 7, 8, bgcolor = color.new(chart.bg_color, 8), border_color = color.new(chart.fg_color, 85),
border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1) : na
var polyline ghostLine = na
var box gapBox = na
if barstate.islast
int nAct = 0
for a in assets
float lo = na
float hi = na
if a.on and not na(a.x)
for v in a.buf
if not na(v)
hi := na(hi) ? v : math.max(hi, v)
lo := na(lo) ? v : math.min(lo, v)
a.drawn := not na(lo) and hi > lo
nAct += a.drawn ? 1 : 0
bool isSmp = i_lblMode == LabelMode.compact
bool one = i_layout == Layout.overlay or nAct <= 1
float laneH = (chartHi - chartLo) / math.max(nAct, 1)
string sty = i_lineStyle == LineStyle.dashed ? line.style_dashed : i_lineStyle == LineStyle.dotted ? line.style_dotted : line.style_solid
// >lines · lanes, tails, anchor dots, lane boxes
int lane = 0
for [i, a] in assets
polyline.delete(a.pl)
polyline.delete(a.plw)
a.pl := na
a.plw := na
a.yEnd := na
a.pos := na
bool shown = false
if a.drawn
a.tHi := one ? chartHi : chartHi - lane * laneH - laneH * i_laneGap / 200.0
a.tLo := one ? chartLo : chartHi - (lane + 1) * laneH + laneH * i_laneGap / 200.0
lane += 1
a.xHi := na
a.xLo := na
for v in a.buf
if not na(v)
a.xHi := na(a.xHi) ? v : math.max(a.xHi, v)
a.xLo := na(a.xLo) ? v : math.min(a.xLo, v)
float xr = a.xHi - a.xLo
if not na(xr) and xr > 0.0 and not na(a.x)
shown := true
a.kf := (a.tHi - a.tLo) / xr // one fixed transform: shape preserved
color lc = i_focus and i != star and not a.unusual ? color.new(a.col, 75) : a.col
array<chart.point> pts = array.new<chart.point>()
array<chart.point> tail = array.new<chart.point>()
for [j, v] in a.buf
if not na(v)
chart.point pt = chart.point.from_index(n0 + j, a.inv ? a.tHi - (v - a.xLo) * a.kf : a.tLo + (v - a.xLo) * a.kf)
pts.push(pt)
if i_tailOn and a.unusual and j >= nWin - i_tailLen
tail.push(pt)
a.pl := pts.size() > 1 ? polyline.new(pts, line_color = lc, line_width = i_lineW, line_style = sty) : na
a.plw := tail.size() > 1 ? polyline.new(tail, line_color = i_warnCol, line_width = i_lineW + 1) : na
a.yEnd := a.inv ? a.tHi - (a.x - a.xLo) * a.kf : a.tLo + (a.x - a.xLo) * a.kf
a.pos := (a.x - a.xLo) / xr
// anchor arrow at the base bar (tooltip: base price and change since then)
float vA = shown and inBuf ? a.buf.get(jB) : na
bool dO = i_anchorDot and not na(vA)
float yA = dO ? (a.inv ? a.tHi - (vA - a.xLo) * a.kf : a.tLo + (vA - a.xLo) * a.kf) : close
if na(a.dot)
a.dot := label.new(bar_index, close, '▼', style = label.style_none, size = size.tiny, textcolor = color(na))
a.dot.set_xy(dO ? n0 + jB : bar_index, dO ? yA + nz(atr) * 0.17 : close) // lifted so the tip sits on the line
a.dot.set_textcolor(dO ? a.col : color(na))
a.dot.set_tooltip(dO ? 'Basis start (' + bTag + ')' +
'\n' + a.tag + ' base: ' + f_px(vA) +
'\nNow: ' + f_px(a.x) + ' (' + (a.isY ? f_sgn(a.move, '0.0') + 'bp' : f_pct(a.move)) + ')' : '')
// lane box: name + real price at the lane top / bottom
bool bO = shown and i_laneBox and not one
if na(a.bx)
a.bx := box.new(n0, close, bar_index, close, border_color = color(na), bgcolor = color(na), text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_top)
if bO
a.bx.set_lefttop(n0, a.tHi)
a.bx.set_rightbottom(bar_index + i_lblShift, a.tLo)
a.bx.set_bgcolor(bO ? color.new(a.col, 94) : color(na))
a.bx.set_text(bO ? a.name + ' ▲ ' + f_px(a.inv ? a.xLo : a.xHi) + ' ▼ ' + f_px(a.inv ? a.xHi : a.xLo) : '')
a.bx.set_text_color(color.new(a.col, 35))
// >macro · ghost path since the base bar (model β on every bar) and gap zone at the last bar
polyline.delete(ghostLine)
ghostLine := na
float ghEnd = na
if i_ghostOn and inBuf and not na(gB) and not na(impl)
array<chart.point> gp = array.new<chart.point>()
for t = jB to nWin - 1
float s = 0.0
bool ok = true
for a in assets
if not na(a.bm) and not na(a.base)
float m = f_ret(a.base, a.buf.get(t), a.isY)
ok := ok and not na(m)
s += nz(a.bm * m)
if ok
gp.push(chart.point.from_index(n0 + t, chartIsY ? gB + s / 100.0 : gB * math.exp(s)))
ghostLine := gp.size() > 1 ? polyline.new(gp, line_color = color.new(chart.fg_color, 30), line_width = 1, line_style = line.style_dotted) : na
ghEnd := chartIsY ? gB + impl / 100.0 : gB * math.exp(impl)
if na(gapBox)
gapBox := box.new(bar_index, close, bar_index, close, border_color = color(na), bgcolor = color(na))
bool gzO = i_gapZone and i_ghostOn and not na(ghEnd)
gapBox.set_lefttop (bar_index - 1, gzO ? math.max(close, ghEnd) : close)
gapBox.set_rightbottom(bar_index + 1, gzO ? math.min(close, ghEnd) : close)
gapBox.set_bgcolor(gzO ? color.new(gapOn ? i_warnCol : close > ghEnd ? color.teal : color.red, 70) : color(na))
// >texts · label text and tooltip per asset (one item per line)
array<string> txts = array.new<string>(5, '')
array<string> tips = array.new<string>(5, '')
array<string> chgT = array.new<string>(5, '—')
array<string> relT = array.new<string>(5, '·')
for [i, a] in assets
if a.on and not na(a.x)
[ic, rw, sig] = f_relation(a.r, a.rLo, a.rHi)
string ch = na(a.move) ? '—' : a.isY ? f_sgn(a.move, '0.0') + 'bp' : f_pct(a.move)
string arw = na(a.impact) ? '' : a.impact >= 0 ? ' ▲' : ' ▼'
string nm = a.tag + (a.inv ? ' ⁻¹' : '') + (i == star ? ' ★' : '')
chgT.set(i, ch)
relT.set(i, ic)
txts.set(i, isSmp ? nm : nm + ' ' + f_px(a.x) + ' ' + ch + arw + (a.unusual ? ' ⚡' : '') + (a.stale ? ' ⏸' : ''))
tips.set(i,
'Asset: ' + a.name + ' (' + a.sym + ')' +
'\nPrice: ' + f_px(a.x) + (a.isY ? '%' : '') +
'\nGroup: ' + a.grp + (a.inv ? ' · line inverted' : '') +
'\nData: ' + (a.stale ? 'closed or delayed · last update ' + str.tostring(a.ageMin) + ' min ago ⏸' : 'live') +
'\nChange (' + bTag + '): ' + ch +
'\nMove size: ' + f_sgn(a.zMove, '0.0') + 'σ' + (a.unusual ? ' · unusual ⚡' : ' · normal') +
'\nRelation: ' + ic + ' ' + rw +
'\nCorrelation: r ' + f_sgn(a.r, '0.00') + ' (95%: ' + f_sgn(a.rLo, '0.00') + ' … ' + f_sgn(a.rHi, '0.00') + ')' +
'\nSample: ' + str.tostring(a.k) + ' × ' + i_corrTf + ' periods traded together' +
'\nStability: last ' + str.tostring(i_stabLen) + ' r ' + f_sgn(a.r20, '0.00') + (a.changing ? ' · changing ⟳' : ' · stable') +
'\nImpact on ' + syminfo.ticker + ': ' + (na(a.impact) ? '— (not in model)' : f_chg(a.impact) + arw + (i == star ? ' · main driver ★' : '')) +
'\nWindow range: ' + f_px(a.xLo) + ' … ' + f_px(a.xHi) + (na(a.pos) ? '' : ' · now at ' + str.tostring(a.pos * 100.0, '0') + '%'))
string mTx = na(macroScore) ? '—' : f_sgn(macroScore, '0.00') + (reliable ? '' : ' ?')
string mTip = 'Macro score: ' + mTx + ' (−1 bearish … +1 bullish for ' + syminfo.ticker + ')' +
'\nModel fit (adjusted R²): ' + (na(modelR2) ? '—' : str.tostring(modelR2 * 100.0, '0') + '%') + ' over ' + str.tostring(modelN) + ' × ' + i_corrTf +
'\nOut-of-sample fit: ' + (na(modelOos) ? '—' : str.tostring(modelOos * 100.0, '0') + '%') + (reliable ? '' : ' · model not reliable now: score marked ?, gap flag off') +
'\nImplied move: ' + f_chg(impl) + ' (' + f_sgn(zImp, '0.0') + 'σ)' +
'\nActual move: ' + f_chg(gMv) + ' (' + f_sgn(zAct, '0.0') + 'σ)' +
'\nGap: ' + f_sgn(zGap, '0.0') + 'σ' + (gapOn ? ' · departs from the macro picture ⚠' : ' · in line') +
'\nMain driver: ' + (star >= 0 ? assets.get(star).tag + ' ★' : '—') +
'\nBasis: ' + bTag + ' · statistics: ' + str.tostring(i_corrLen) + ' × ' + i_corrTf + (i_robust ? ' · outliers clipped' : '')
// >labels · created once, then moved; spread upward so they never overlap
array<float> ys = array.new<float>()
array<int> ix = array.new<int>()
for [i, a] in assets
if not na(a.lb)
a.lb.set_text('')
a.lb.set_tooltip('')
a.lb.set_color(color(na))
if i_lblOn and a.on and not na(a.yEnd)
ys.push(a.yEnd)
ix.push(i)
if ys.size() > 0
array<int> ord = ys.sort_indices(order.ascending)
float gap = nz(atr, close * 0.002) * (isSmp ? 0.6 : 0.8)
float prv = na
for o in ord
int i = ix.get(o)
Asset a = assets.get(i)
float y = na(prv) ? ys.get(o) : math.max(ys.get(o), prv + gap)
prv := y
if na(a.lb)
a.lb := label.new(bar_index, y, '', style = label.style_label_left)
a.lb.set_xy(bar_index + i_lblShift, y)
a.lb.set_text(txts.get(i))
a.lb.set_tooltip(tips.get(i))
a.lb.set_size(lblSize)
a.lb.set_color(isSmp ? color(na) : color.new(a.col, 10))
a.lb.set_textcolor(isSmp ? a.col : f_ink(a.col))
// >table
if not na(tbl)
tbl.clear(0, 0, 6, 7)
color fg = chart.fg_color
color dim = color.new(fg, 40)
color mBg = na(macroScore) ? color.new(fg, 85) : color.from_gradient(macroScore, -1.0, 1.0, #C62828, #2E7D32)
color band = color.new(#5C6BC0, 70) // distinct background of the macro row
if i_tblMode == TableMode.hud
int c = 0
for [i, a] in assets
if a.on and not na(a.x) and c < 5
string arw = na(a.impact) ? '' : a.impact >= 0 ? ' ▲' : ' ▼'
tbl.cell(c, 0, a.tag + (i == star ? '★' : '') + ' ' + chgT.get(i) + arw + (a.unusual ? ' ⚡' : ''), text_color = a.col, text_size = tblSize, tooltip = tips.get(i))
c += 1
tbl.cell(c, 0, 'MACRO ' + mTx + (gapOn ? ' ⚠' : ''), text_color = f_ink(mBg), bgcolor = mBg, text_size = tblSize, tooltip = mTip)
else
array<string> hdr = array.from('Asset', 'Price', bTag, 'σ', 'r', 'Impact', 'Range')
array<string> hTp = array.from(
'Asset tag · ⁻¹ line inverted · ★ main driver of ' + syminfo.ticker,
'Live price of the asset',
'Change since the basis start (' + bTag + ') · yields in bp',
'Move in σ of the asset\'s own ' + i_corrTf + ' moves, scaled to the elapsed time · ⚡ at ≥ ' + str.tostring(i_zFlag) + 'σ',
'Correlation with ' + syminfo.ticker + ' over ' + str.tostring(i_corrLen) + ' × ' + i_corrTf + ' · shaded when significant · ⟳ changing',
'Independent effect of this asset\'s move on ' + syminfo.ticker + ' (macro model) · ▲ bullish ▼ bearish',
'Position of the price inside its window range (0% low … 100% high)')
for [c, t] in hdr
tbl.cell(c, 0, t, text_color = dim, text_size = tblSize, tooltip = hTp.get(c))
int row = 1
for [i, a] in assets
if a.on and not na(a.x)
[ic, rw, sig] = f_relation(a.r, a.rLo, a.rHi)
color rc = color.from_gradient(nz(a.r), -1.0, 1.0, color.new(color.red, 55), color.new(color.green, 55))
color zc = color.from_gradient(math.min(math.abs(nz(a.zMove)), 3.0), 0.0, 3.0, color.new(i_warnCol, 100), color.new(i_warnCol, 40))
color ec = na(a.impact) ? color(na) : a.impact >= 0 ? color.new(color.green, 60) : color.new(color.red, 60)
string tp = tips.get(i)
tbl.cell(0, row, a.tag + (a.inv ? ' ⁻¹' : '') + (i == star ? ' ★' : ''), text_color = a.col, text_size = tblSize, text_halign = text.align_left, tooltip = tp)
tbl.cell(1, row, f_px(a.x), text_color = fg, text_size = tblSize, text_halign = text.align_right, tooltip = tp)
tbl.cell(2, row, chgT.get(i), text_color = fg, text_size = tblSize, text_halign = text.align_right, tooltip = tp)
tbl.cell(3, row, f_sgn(a.zMove, '0.0') + (a.unusual ? ' ⚡' : ''), text_color = fg, bgcolor = zc, text_size = tblSize, text_halign = text.align_right, tooltip = tp)
tbl.cell(4, row, relT.get(i) + ' ' + f_sgn(a.r, '0.00') + (a.changing ? ' ⟳' : ''), text_color = sig ? f_ink(rc) : fg, bgcolor = sig ? rc : color(na), text_size = tblSize, text_halign = text.align_right, tooltip = tp)
tbl.cell(5, row, f_chg(a.impact), text_color = na(a.impact) ? fg : f_ink(ec), bgcolor = ec, text_size = tblSize, text_halign = text.align_right, tooltip = tp)
tbl.cell(6, row, na(a.pos) ? '—' : str.tostring(a.pos * 100.0, '0') + '%', text_color = fg, text_size = tblSize, text_halign = text.align_right, tooltip = tp)
row += 1
else if a.on
tbl.cell(0, row, a.tag, text_color = a.col, text_size = tblSize, text_halign = text.align_left, tooltip = a.name + ' (' + a.sym + ')')
tbl.cell(1, row, 'no data · check the symbol or its data subscription', text_color = dim, text_size = tblSize, text_halign = text.align_left)
tbl.merge_cells(1, row, 6, row)
row += 1
// macro row: own band, score cell colored by the score
tbl.cell(0, row, 'MACRO', text_color = fg, bgcolor = band, text_size = tblSize, text_halign = text.align_left, tooltip = mTip)
tbl.cell(1, row, mTx, text_color = f_ink(mBg), bgcolor = mBg, text_size = tblSize, tooltip = mTip)
tbl.cell(2, row, 'fit ' + (na(modelR2) ? '—' : str.tostring(modelR2 * 100.0, '0') + '%') + ' · oos ' + (na(modelOos) ? '—' : str.tostring(modelOos * 100.0, '0') + '%'), text_color = fg, bgcolor = band, text_size = tblSize, tooltip = mTip)
tbl.cell(3, row, 'gap ' + f_sgn(zGap, '0.0') + 'σ' + (gapOn ? ' ⚠' : ''), text_color = gapOn ? f_ink(i_warnCol) : fg, bgcolor = gapOn ? i_warnCol : band, text_size = tblSize, tooltip = mTip)
tbl.cell(4, row, 'implied ' + f_chg(impl) + ' · actual ' + f_chg(gMv), text_color = fg, bgcolor = band, text_size = tblSize, tooltip = mTip)
tbl.merge_cells(4, row, 6, row)
// ▴▴▴▴▴▴▴▴▴▴
// #endRegion