PROTECTED SOURCE SCRIPT
מעודכן Swing Data [ATR Ext | RVol | ADR | Ticker/Sector RS]

Disclaimer: This indicator is not financial advice and is strictly for educational and informational purposes only. The metrics and signals provided herein—including ATR extensions, volume projections, and rolling alpha for relative strength — are calculated based on historical market data and do not guarantee future performance. Trading stocks and commodities involves significant risk of loss. The user assumes full responsibility for all trading decisions and should always perform their own due diligence before executing trades.
Hello there. I was inspired after reading this Twitter post by Steve Jacobs regarding the ATR Matrix. I followed Steve's recommendation to the interesting [ATR% Multiple from 50-MA] indicator built by Fred6724 for jfsrev but I couldn't match my manual calculations to their math. So, I threw together this TradingView indicator to match my own manual calculations for the ATR Extension Multiple. And then, I added more quality-of-life features that I found useful in my daily workflow such as table positioning, specific data streams, threshold customization, and conditional coloring. This became quite a snowball.
Data streams available for turning on/off:
Advanced mapping of the Sector string to a specific ETF, GICS Compliant.
Pine Script®
Hello there. I was inspired after reading this Twitter post by Steve Jacobs regarding the ATR Matrix. I followed Steve's recommendation to the interesting [ATR% Multiple from 50-MA] indicator built by Fred6724 for jfsrev but I couldn't match my manual calculations to their math. So, I threw together this TradingView indicator to match my own manual calculations for the ATR Extension Multiple. And then, I added more quality-of-life features that I found useful in my daily workflow such as table positioning, specific data streams, threshold customization, and conditional coloring. This became quite a snowball.
- Daily Chart: Please note that the design for this indicator was focused on the daily chart. Edge case testing has not been fully conducted for other charting periods, although the math should apply agnostically. The calculations of rolling alpha for Ticker RS and Sector RS fetch daily data instead of the displayed chart period, which may affect Ticker RS if you have turned on pre-market and after-market.
- Relative Strength Differential reveals rolling alpha: One way to read the Ticker RS and Sector RS is... this stock is beating SPY by +75% in the past 63 days and blue color means the stock's outperformance is accelerating but the sector of this stock is beating SPY by a sleepy 3% and orange color means the sector's performance against the broader market is shrinking... so at a glance, we can conclude this is a strong stock in a lagging sector.
- Status Line: The script outputs the raw ATR Extension value, ATR%, and a Boolean (0/1) for the ATR Extension alert dot directly to the Status Line. This allows you to hover your mouse over any historical candle to see exactly how extended price was on that specific candle, without needing to calculate it manually. These values are coded to display as text only. They provide the data you need without drawing distracting line plots across your price action. In the Style Tab of the indicator settings, you will see checkboxes for these values. Avoid toggling them off and on. Doing so can override the script’s default "invisible" setting and force TradingView to draw unnecessary lines on the chart.
Data streams available for turning on/off:
- ATR Multiple above SMA (default SMA50, default alert on candle >6 multiple, the simple math is Price minus SMA50 and then divide by ATR)
- ATR Percent (default period length 14)
- ATR Value
- Percent Distance from SMA (default SMA50)
- Projected Relative Volume calculated against Average Volume (default 60 day avg vol)
- Projected Volume (estimates end of day volume based on current volume at elapsed time)
- Projected Dollar Volume (estimates end of day turnover based on projected volume x current price... it's a ballpark for gauging liquidity... time arrays for modestly more accurate turnover projection is compute heavy and low signal intel)
- Average Volume (default 60 day)
- Average Dollar Volume (default 60 day)
- ADR Percent (default period length 20 while TradingView prefers 14)
- ADX (default period length 14)
- Low of Day Price
- Dynamic Stop Loss (default Stop MA length 10 and Stop ATR multiple 0.5, adjust at your preference)
- Market Capitalization (calculates latest Fiscal Quarter's Shares Outstanding x Price)
- Ticker RS vs SPY (calculates the stock's 63-day rolling performance against the broader market to quantify raw outperformance percentage; the text color signals velocity, turning default blue if the relative strength is flying above the 21-day average of this relative strength or default orange if shrinking below)
- Sector RS vs SPY (calculates the sector's 63-day rolling performance against the broader market to quantify raw outperformance percentage; the text color signals velocity, turning default blue if the relative strength is flying above the 21-day average of this relative strength or default orange if shrinking below)
- Sector (basic exception handling such as metal/energy/crypto in ambiguous industries and GICS industry overrides, see code block below)
- Industry (pulls TradingView's syminfo, truncates when too long)
Advanced mapping of the Sector string to a specific ETF, GICS Compliant.
// 1. Get Sector and Industry Strings
// 'str.lower' converts the description to lowercase to make keyword matching easier (case-insensitive).
string sec_raw = syminfo.sector
string ind_raw = syminfo.industry
string desc_raw = str.lower(syminfo.description)
// Default Fallback: If no match is found, we compare against SPY (Market Average).
string sec_etf = "SPY"
// 2. DEFINE CONDITIONAL GATES (The Safeguards)
// CRITICAL: We only want to scan for keywords (like "Silver") if the stock is in a vague industry bucket.
// This prevents "False Positives". For example, we don't want "Silvergate Bank" (Regional Banks)
// to be accidentally reclassified as a Mining stock just because it has "Silver" in the name.
bool is_ambiguous = ind_raw == "Investment Trusts/Mutual Funds" or ind_raw == "Miscellaneous" or ind_raw == "Financial Conglomerates" or ind_raw == "Other Metals/Minerals" or ind_raw == "Precious Metals"
// 3. KEYWORD LOGIC (Only runs inside the Gate)
// RULE A: COMMODITY TRUSTS (Metals -> XLB)
// Fixes: PSLV, PHYS, SPPP, GLD, SLV which are legally "Financial Trusts" but trade like Commodities.
// Logic: If it's a Trust AND mentions "Silver/Gold/Bullion", map to Materials (AMEX:XLB).
bool has_metal = str.contains(desc_raw, "silver") or str.contains(desc_raw, "gold") or str.contains(desc_raw, "bullion") or str.contains(desc_raw, "platinum") or str.contains(desc_raw, "palladium") or str.contains(desc_raw, "precious")
// RULE B: ENERGY TRUSTS (Oil/Uranium -> XLE)
// Fixes: USO, UNG, SPUT (Uranium).
// Logic: Uranium and Oil trusts correlate with Energy (AMEX:XLE), not Financials.
bool has_energy = str.contains(desc_raw, "oil") or str.contains(desc_raw, "natural gas") or str.contains(desc_raw, "petroleum") or str.contains(desc_raw, "uranium") or str.contains(desc_raw, "crude")
// RULE C: CRYPTO PROXIES (Bitcoin/Ether -> XLK)
// Fixes: GBTC, IBIT, FBTC.
// Logic: Crypto equities currently have the highest correlation with High-Beta Tech (AMEX:XLK).
bool has_crypto = str.contains(desc_raw, "bitcoin") or str.contains(desc_raw, "ethereum") or str.contains(desc_raw, "crypto") or str.contains(desc_raw, "coin")
// 4. EXECUTE KEYWORD MAPPING
if is_ambiguous and has_metal
sec_etf := "XLB" // Force Metals to Materials
else if is_ambiguous and has_energy
sec_etf := "XLE" // Force Energy Trusts to Energy
else if is_ambiguous and has_crypto
sec_etf := "XLK" // Force Crypto to Tech (Risk On)
// 5. GICS INDUSTRY OVERRIDES (The "Standard" Fixes)
// These rules fix known classification errors where TradingView data lags behind GICS reclassifications.
// EXCEPTION: PAYMENT PROCESSORS (The "Visa" Rule - 2023 Update)
// Visa ($V), Mastercard (NYSE:MA), and PayPal (NASDAQ:PYPL) are now Financials (AMEX:XLF), not Tech.
else if ind_raw == "Data Processing Services"
sec_etf := "XLF"
// EXCEPTION: COMMUNICATIONS (The "Google/Meta" Rule - 2018 Update)
// Separates "Internet" and "Media" stocks (NASDAQ:GOOGL, NASDAQ:META, NASDAQ:NFLX) from "Packaged Software" (NASDAQ:MSFT).
// These belong in Communications (AMEX:XLC).
else if ind_raw == "Internet Software/Services" or ind_raw == "Advertising/Marketing Services" or ind_raw == "Broadcasting" or ind_raw == "Cable/Satellite TV" or ind_raw == "Movies/Entertainment"
sec_etf := "XLC"
// EXCEPTION: REAL ESTATE (The "REIT" Rule)
// Pulls REITs out of the Financials bucket (AMEX:XLF) and into their own sector (AMEX:XLRE).
else if str.contains(ind_raw, "Real Estate") or str.contains(ind_raw, "REIT")
sec_etf := "XLRE"
// EXCEPTION: AUTO MANUFACTURERS (The "Tesla" Rule)
// Tesla (NASDAQ:TSLA), Ford ($F), and GM are Consumer Discretionary (AMEX:XLY), not Tech or Industrials.
else if ind_raw == "Motor Vehicles"
sec_etf := "XLY"
// EXCEPTION: INTERNET RETAIL (The "Amazon" Rule)
// Amazon (NASDAQ:AMZN) and eBay are Consumer Discretionary (AMEX:XLY), distinct from generic "Retail Trade" (AMEX:XRT).
else if ind_raw == "Internet Retail"
sec_etf := "XLY"
// EXCEPTION: TEXTILES & APPAREL
// Nike (NYSE:NKE), Lululemon (NASDAQ:LULU), and Ralph Lauren are Consumer Discretionary (AMEX:XLY).
else if ind_raw == "Apparel/Footwear" or ind_raw == "Textiles"
sec_etf := "XLY"
// EXCEPTION: AEROSPACE & DEFENSE (The "Lockheed" Rule)
// Often mislabeled as Tech in some feeds, strictly belongs to Industrials (AMEX:XLI).
else if ind_raw == "Aerospace & Defense"
sec_etf := "XLI"
// EXCEPTION: SEMICONDUCTORS
// Explicit check to ensure Semis (NASDAQ:NVDA, NASDAQ:AMD) always stick to Tech (AMEX:XLK).
else if ind_raw == "Semiconductors"
sec_etf := "XLK"
// 6. STANDARD FALLBACKS
// If the stock didn't trigger any exception above, map based on the broad Sector name.
else
sec_etf := switch sec_raw
"Technology Services" => "XLK" // Microsoft, Oracle, Adobe
"Electronic Technology" => "XLK" // Apple, Hardware
"Finance" => "XLF" // Banks, Insurance
"Health Technology" => "XLV" // Pharma, Biotech
"Health Services" => "XLV" // Managed Care (UNH)
"Retail Trade" => "XRT" // Home Depot, Walmart (Retailers)
"Consumer Non-Durables" => "XLP" // Coke, P&G (Staples)
"Energy Minerals" => "XLE" // Exxon, Chevron (Oil)
"Industrial Services" => "XLI" // Construction, Engineering
"Consumer Services" => "XLY" // Restaurants, Hotels
"Consumer Durables" => "XLY" // Homebuilders, Appliances
"Utilities" => "XLU" // Power, Water
"Transportation" => "XTN" // Airlines, Rail, Trucking
"Non-Energy Minerals" => "XLB" // Steel, Copper, Chemicals
"Commercial Services" => "XLC" // Remaining Media/Comms
"Communications" => "XLC" // Legacy tag
"Distribution Services" => "XLY" // Wholesalers
=> "SPY" // Final Catch-All
הערות שחרור
IMPROVED FEATURE Advanced Predictive Volume using Bayesian Stabilization One of the biggest challenges with linear volume projections is the "U-Shape" liquidity curve. In the first 30 minutes of the trading day, volume is naturally massive. Standard linear indicators often mistake this normal morning rush for an explosive breakout, projecting unrealistic end-of-day numbers (e.g., 500% Relative Volume) that collapse an 30min later.
Let's fix this using the Time-Weighted Stabilization method. This algorithm uses a Bayesian approach that "anchors" the projection to the stock's 60-day average at the open. As the trading day progresses, the script gradually shifts its weighted trust away from the historical average toward the real-time data using a Square Root Curve. This allows the indicator to filter out early-morning noise while still accelerating quickly enough to catch legitimate breakouts by 10:30 AM ET or 11:00 AM ET. Users can now toggle between "Standard" (Linear) and "Stabilized" modes, and set the initial weight for live volume (default 0.3).
projVolMethod = input.string("Stabilized (Time-Weighted)", title="Projected Vol Method", options=["Standard (Linear)", "Stabilized (Time-Weighted)"],
tooltip="METHODOLOGY:\n\n" +
"• STANDARD (Linear): Extrapolates current volume run-rate to end-of-day based on elapsed time. \n" +
" Formula = Current Vol x (Total Time / Elapsed Time).\n" +
" Risk for Linear extrapolation is over-estimation in the first 30 mins due to the 'Morning Rush'.)\n\n" +
"• STABILIZED (Time-Weighted): A Bayesian anchor on projected volume to average volume at the open.\n" +
" Then accelerates trusted weight in live data via a Square Root curve based on time elapsed.\n" +
" A starting weight is used, e.g. ticker open 30% live data extrapolation plus 70% average volume.\n" +
" (Benefit: Eliminates false 'Volume Spike' signals in the morning.)",
group=grp_calc)
vol_weight_start = input.float(0.5, title="Initial Weight for Live Vol", minval=0.0, maxval=1.0, step=0.1,
tooltip="TRUST CURVE GUIDANCE on Square Root curve:\n" +
"Controls the starting blend of [Live Data] vs [Daily Average] at 9:30 AM ET.\n\n" +
"• 0.3 (BALANCED / BIAS FOR ACCURACY): Good for general monitoring, but may not signal boost true breakouts early.\n" +
" - 9:35 AM ET: ~38% Trust Live Volume for extrapolation (Filters fake-outs)\n" +
" - 11:00 AM ET: ~65% Trust Live Volume for extrapolation (Locks onto trend)\n" +
" - 2:00 PM ET: ~88% Trust (High confidence)\n\n" +
"• 0.5 (AGGRESSIVE / HUNTER): *Recommended for Breakouts*\n" +
" - 9:35 AM ET: ~56% Trust Live Volume for extrapolation (Captures early explosions)\n" +
" - 11:00 AM ET: ~74% Trust\n" +
" - 2:00 PM ET: ~92% Trust\n\n" +
"• 0.0 (CONSERVATIVE / SLOW):\n" +
" - 9:35 AM ET: ~11% Trust Live Volume for extrapolation (Very dampened)\n" +
" - 11:00 AM ET: ~48% Trust\n" +
" - 2:00 PM ET: ~83% Trust",
group=grp_calc)
ADDED FEATURE Bearish Pressure via Daily Short Volume
Many traders rely on "Short Interest" to gauge squeeze potential, but that data is reported bi-weekly and is often 10–15 days old by the time you see it. To provide a more immediate signal, let's run a FINRA Daily Short Volume Ratio.
This metric tracks the percentage of today's total volume that was initiated by short sellers. Unlike Short Interest, which measures total open positions, Short Volume measures immediate daily flow. A reading above 50% generally signals aggressive bearish pressure or institutional hedging, while readings below 40% suggest buyers are hitting the ask with little resistance. This calculation is strictly locked to the Daily timeframe to ensure accuracy regardless of the chart you are viewing.
ADDED FEATURE Simple Acc/Dist Ratio
Added the Accumulation/Distribution (Acc/Dist) Ratio to help visualize the "footprint" of big money. This metric looks back over the last 50 days and compares the volume traded on Up Days versus Down Days.
// Logic: If Close > Prev Close, it's 'Up Volume'. If Close < Prev Close, it's 'Down Volume'.
// We use math.sum to tally this over the last 50 days.
float up_vol_sum = math.sum(close > close[1] ? volume : 0, ud_len)
float down_vol_sum = math.sum(close < close[1] ? volume : 0, ud_len)
// Avoid division by zero
float ud_ratio = 0.0
if down_vol_sum > 0
ud_ratio := up_vol_sum / down_vol_sum
else
ud_ratio := 1.0 // Neutral fallback
The resulting ratio acts as a conviction gauge for the trend. A value above 1.0 indicates net buying, while a value above 1.2 is a strong signal of institutional support, meaning volume is significantly heavier when the stock is rising than when it is pulling back. Conversely, a value below 1.0 warns of distribution, where sellers are dominating the flow despite price action.
IMPROVED FEATURE Visual Logic for Relative Strength Differential
The visual logic for Ticker and Sector Relative Strength (RS) has been upgraded to filter out "fake" momentum. Previously, a stock could show a "Blue" (Expanding) signal even if it was underperforming the SPY, simply because it was improving slightly.
The new logic implements a strict Noise Filter. If a stock's raw Alpha (performance vs. SPY) is negative, the indicator will now color the value Gray (pick using Trash RS Color), marking it as "Noise" regardless of its short-term momentum. This ensures that the bright "Blue" (Expanding) and "Orange" (Contracting) signals are reserved exclusively for stocks that are actually beating the market.
הערות שחרור
ADDED FEATURE Bar-to-ATR Ratioshow_bar_atr = input.bool(true, title="Show Bar-to-ATR Ratio",
tooltip="ATR UTILIZATION: Gauges 'fuel burn' of current candle vs average ATR over selected ATR length (default 14).\n\n" +
"• TOO COLD (< 60%): 'The Coil'. Energy building. Setup phase. Watch for ignition.\n" +
" [ACTION]: Watchlist only. Do not trade (Dead Money).\n\n" +
"• JUST RIGHT (100% - 250%): 'Conviction'.\n" +
" [ACTION]: Healthy breakout expansion. Buyers in control. Ideal entry window.\n\n" +
"• TOO HOT (> 250%): Extension risk. Entering here requires a wide stop-loss (Low R:R).\n" +
" [BULL]: Do not buy. Wait for an Inside Day (Rest).\n" +
" [BEAR]: Do not short. Expect a snap-back bounce.",
group=grp_add)
Previous metric "ATR Percent" has been renamed more appropriately to "ATR as % / Price", which is a gauge of tightness. Meanwhile, this newly added Bar-to-ATR ratio measures fuel burn of the current candle versus average ATR... a sort of extension risk where the risk-to-reward of a wide stop loss becomes trash on the day of breakout.
ADDED FEATURE Five plot lines for Moving Averages
Everyone loves Moving Averages. One less indicator cluttering the indicator list on my mobile view.
IMPROVED FEATURE Edge Case Handling for the Projected Volume mechanism
Refactored the Projected Volume calculation block to fix critical data distortions when viewing the indicator on Intraday timeframes (e.g., 15m, 1h).
Old Behavior: Ran complex time-weighting math on any chart timeframe. On a 1-hour chart, time_elapsed would be small relative to the 1-hour bar close, but the projection would compare it against Daily Averages, causing mismatched ratios.
New Behavior: The projection logic is now wrapped in a strict timeframe.isdaily check.
Fallback: If the user views the indicator on an Intraday chart, the script defaults vol_proj to the accumulated Daily Volume (d_vol). This disables the "End of Day" forecast on lower timeframes to preserve data integrity.
Explicitly uses d_vol (fetched via request.security), ensuring the calculation base is always the Total Daily Volume, regardless of the chart view.
Condensed the conf_weight and vol_proj_stabilized intermediate variables into a single, cleaner logic block that only executes when valid. This reduces variable clutter and improves script efficiency.
IMPROVED FEATURE Sector Logic Optimization with Static Caching
Refactored the GICS Sector Mapping logic to execute only once upon script initialization, rather than recalculating on every single historical and real-time bar.
Redundant Calculation: The sector of a stock (e.g., Apple is "Technology") never changes during a trading session. However, the original code ran the complex string matching logic (looking for "Silver", "Oil", "REIT", etc.) on every single bar.
Heavy Load: String manipulation functions like str.contains() and str.lower() are computationally expensive. Running these thousands of times (once for every candle on your chart) wastes significant processing power.
The Solution (New Code)
- Static Initialization: Implemented the var keyword to define sec_etf_static. This tells Pine Script to keep the variable's value in memory across all bars, rather than resetting it.
- Execution Gate: Wrapped the entire logic block in if bar_index == 0. This forces the mapping logic to run exactly one time (on the very first bar of history) and never again.
- Persistence: For all subsequent bars, the script simply recalls the saved result (sec_etf = sec_etf_static).
Performance Impact: reduced calculation load of one code section by ~99.9%. The script loads faster, uses less memory, and is far less likely to hit Pine Script execution limits, leaving more resources available for messing around on TradingView.
הערות שחרור
Interface Definitions & Table Legend- Inputs in menu settings labeled "Lookback" define the period length used for calculations.
- Inputs with "Check" in menu settings establish the specific thresholds that trigger visual alerts or table color changes. Please refer to individual tooltips for detailed logic.
- Table Tags [Day]: Indicates the metric is locked to Daily data, ensuring consistent liquidity and trend analysis regardless of the chart view.
- Table Tags [Bar]: Indicates the metric is Adaptive, calculating values based strictly on the current chart's timeframe (e.g., 65m Volume).
IMPROVED FEATURE Universal Volume Projection Engine
Fully Adaptive: Volume projections now automatically switch behavior based on your chart.
- Intraday (e.g., 65m): Projects the closing volume of the current bar only.
- Daily: Projects the closing volume of the trading session.
- Weekly/Monthly: Projects the end of the period using Fractional Day counting (e.g., Monday Noon = 0.5 days elapsed).
Projection Logic:
- Higher Timeframes (Weekly+): Uses standard Linear Projection, as day-counting is stable and does not require complex filtering.
- Fast Timeframes (Daily/Intraday): Continues to use Bayesian Stabilization (if selected) to filter out "infinite volume" anomalies during the market open.
Fractal RVol: Projected Relative Volume is now mathematically precise for every timeframe. It compares the Projected Volume of the current chart (e.g., 65m) against the Historical Average Volume of that same timeframe (e.g., 65m Average). Note that the Lookback length for the Historical Average Volume can be adjusted, default 60.
הערות שחרור
IMPROVED FEATURE Hard Lock optional for Moving AveragesDecoupled the Moving Average Ribbon from the chart's native timeframe. You can now hard-lock specific Moving Averages to higher timeframes (e.g., Daily or Weekly) while viewing Intraday charts. Breakout traders live on the Intraday chart (e.g., 65m or 5m) to time entries, but the institutional support lives on the Daily chart. Previously, to see where the "Daily 50 SMA" was while trading a 5-minute chart, you had to switch screens or guess. Now, you can plot the True Daily 50 SMA directly onto your 5-minute execution chart.
When you plot a Daily MA on an Intraday chart, it will not look like a smooth curve. It will look like a Staircase. This is a feature, not a bug. It represents the distinct "Floor" of that day. As long as price action on the 5m chart stays above that "Step," the Daily trend is intact.
If you leave the Timeframe input Empty, the MA behaves exactly as before (calculates based on the chart you are looking at). MTF Behavior gets activated when you select a specific time-frame in the new dropdown to lock that MA to that timeframe, regardless of how far you zoom in.
Config Example for Traders:
- MA 1 (10 SMA): Leave Timeframe Empty. (Tracks immediate momentum on your 5m/65m chart).
- MA 2 (20 SMA): Leave Timeframe Empty. (Tracks the "surf" of the breakout).
- MA 3 (50 SMA): Set Timeframe to "1 Day". (This becomes your "Anchor." It shows the institutional floor you must not violate).
סקריפט מוגן
סקריפט זה פורסם כמקור סגור. עם זאת, תוכל להשתמש בו בחופשיות וללא כל מגבלות – למד עוד כאן
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.
סקריפט מוגן
סקריפט זה פורסם כמקור סגור. עם זאת, תוכל להשתמש בו בחופשיות וללא כל מגבלות – למד עוד כאן
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.