OPEN-SOURCE SCRIPT
Aggiornato Trading Toolkit - Comprehensive Analysis

Trading Toolkit – Comprehensive Analysis
A unified trading analysis toolkit with four sections:
📊 Company Info
Fundamentals, market cap, sector, and earnings countdown.
📅 Performance
Date‑range analysis with key metrics.
🎯 Market Sentiment
CNN‑style Fear & Greed Index (7 components) + 150‑SMA positioning.
🛡️ Risk Levels
ATR/MAD‑based stop‑loss and take‑profit calculations.
Key Features
CNN‑style Fear & Greed approximation using:
Momentum: S&P 500 vs 125‑DMA
Price Strength: NYSE 52‑week highs vs lows
Market Breadth: McClellan Volume Summation (Up/Down volume)
Put/Call Ratio: 5‑day average (inverted)
Volatility: VIX vs 50‑DMA (inverted)
Safe‑Haven Demand: 20‑day SPY–IEF return spread
Junk‑Bond Demand: HY vs IG credit spread (inverted)
Normalization: z‑score → percentile (0–100) with ±3 clipping.
CNN‑aligned thresholds:
Extreme Fear: 0–24 | Fear: 25–44 | Neutral: 45–54 | Greed: 55–74 | Extreme Greed: 75+.
Risk tools: ATR & MAD volatility measures with configurable multipliers.
Flexible layout: vertical or side‑by‑side columns.
Data Sources
S&P 500: CBOE:SPX or AMEX:SPY
NYSE: INDEX:HIGN, INDEX:LOWN, USI:UVOL, USI:DVOL
Options: USI:PCC (Total PCR), fallback INDEX:CPCS (Equity PCR)
Volatility: CBOE:VIX
Treasuries: NASDAQ:IEF
Credit Spreads: FRED:BAMLH0A0HYM2, FRED:BAMLC0A0CM
Risk Management
ATR risk bands: 🟢 ≤3%, 🟡 3–6%, ⚪ 6–10%, 🟠 10–15%, 🔴 >15%
MAD‑based stop‑loss and take‑profit calculations.
Author: Daniel Dahan
(AI Generated, Merged & enhanced version with CNN‑style Fear & Greed)
A unified trading analysis toolkit with four sections:
📊 Company Info
Fundamentals, market cap, sector, and earnings countdown.
📅 Performance
Date‑range analysis with key metrics.
🎯 Market Sentiment
CNN‑style Fear & Greed Index (7 components) + 150‑SMA positioning.
🛡️ Risk Levels
ATR/MAD‑based stop‑loss and take‑profit calculations.
Key Features
CNN‑style Fear & Greed approximation using:
Momentum: S&P 500 vs 125‑DMA
Price Strength: NYSE 52‑week highs vs lows
Market Breadth: McClellan Volume Summation (Up/Down volume)
Put/Call Ratio: 5‑day average (inverted)
Volatility: VIX vs 50‑DMA (inverted)
Safe‑Haven Demand: 20‑day SPY–IEF return spread
Junk‑Bond Demand: HY vs IG credit spread (inverted)
Normalization: z‑score → percentile (0–100) with ±3 clipping.
CNN‑aligned thresholds:
Extreme Fear: 0–24 | Fear: 25–44 | Neutral: 45–54 | Greed: 55–74 | Extreme Greed: 75+.
Risk tools: ATR & MAD volatility measures with configurable multipliers.
Flexible layout: vertical or side‑by‑side columns.
Data Sources
S&P 500: CBOE:SPX or AMEX:SPY
NYSE: INDEX:HIGN, INDEX:LOWN, USI:UVOL, USI:DVOL
Options: USI:PCC (Total PCR), fallback INDEX:CPCS (Equity PCR)
Volatility: CBOE:VIX
Treasuries: NASDAQ:IEF
Credit Spreads: FRED:BAMLH0A0HYM2, FRED:BAMLC0A0CM
Risk Management
ATR risk bands: 🟢 ≤3%, 🟡 3–6%, ⚪ 6–10%, 🟠 10–15%, 🔴 >15%
MAD‑based stop‑loss and take‑profit calculations.
Author: Daniel Dahan
(AI Generated, Merged & enhanced version with CNN‑style Fear & Greed)
Note di rilascio
Added P/E ratio & betaNote di rilascio
📊 Trading Toolkit v2.0 - Major Feature Update🆕 New Features Added:
1. F&G Acceleration & Trend Analysis
Real-time Fear & Greed momentum tracking with 5-state classification (Strong Up/Up/Flat/Down/Strong Down)
Z-score normalized acceleration analysis with configurable parameters
Color-coded trend indicators with emoji visualization
2. Professional Position Sizing
Portfolio-based position sizing with configurable risk percentage (default 1%)
ATR/MAD-based stop distance calculations
Displays both position value % and actual risk % for clarity
Automatic position limits to prevent over-allocation
3. F&G-Driven Leverage Policy
Dynamic leverage recommendations (0-100%+) based on Fear & Greed sentiment
Dual calculation methods: Sigmoid (smooth curve) vs Piecewise (linear segments)
Acceleration-based adjustments for momentum timing
Visual indicators showing method and acceleration state
🎨 Display Improvements:
Enhanced Market Sentiment section with acceleration states
Consistent text color configuration across all indicators
Emoji-based visual feedback (🟢🟡🟠🔴⚪) for trend and leverage states
Optional trend color override for advanced users
🔧 Technical Enhancements:
Custom slope calculation function for trend analysis
Robust fallback calculations for missing data
Improved code consistency and Pine Script v5 compliance
Comprehensive input parameter organization
Perfect for traders seeking advanced risk management and sentiment-driven position sizing!
Compatible with existing configurations. All new features can be toggled on/off independently.
Note di rilascio
🔧 Critical Fix: S&P 500 Data ConsistencyFixed S&P 500 Fear & Greed Index and SPX-based leverage recommendations incorrectly changing when switching between stocks.
Root cause: Market-wide data sources were using configurable timeframes instead of hardcoded daily timeframes. Now all S&P 500 components (VIX, NYSE data, Put/Call ratios, etc.) use consistent daily data regardless of chart timeframe or stock symbol.
Result: S&P 500 indicators now remain constant across all stocks as intended, while individual stock metrics still update appropriately.
Note di rilascio
updating the chartNote di rilascio
trying again to update the chartNote di rilascio
3rd time a charmNote di rilascio
trying to make Trading View to update the chartNote di rilascio
another tryNote di rilascio
updated the Risk section nameNote di rilascio
Trading Toolkit - Release NotesMajor Updates
🧠 Machine Learning Integration
• Dual ML Prediction System: Integrated two complementary ML methods
o Logistic Regression: Multiple logistic regression with gradient descent (learning rate: 0.08)
o Lorentzian KNN Classification: K-nearest neighbors using Lorentzian distance (k=8 neighbors)
• 5 ML Features: RSI, CCI, DMI, ADX, and EMA-based features with z-score normalization
• ML Risk Assessment: Bearish/Bullish signals with configurable thresholds (default: 0.3/0.7)
• ML Confidence Score: 0-100% confidence based on prediction distance from neutral
• Performance Optimization: Lorentzian calculations run only on last bar for efficiency
🛡️ Enhanced Risk Management
Risk-Off Composite Score
• 5-Component System: F&G Extreme Fear, VIX Risk, ARKK/SPX Ratio, SPX Trend, ML Risk
• Configurable Weights: Independent weights for each component (defaults: 1.0, 1.0, 1.0, 1.0, 2.0 for ML)
• Dynamic Score Display: Shows actual weighted maximum (e.g., "3.5/7.0" instead of "3.5/5")
• 5-Level Status System: Risk-On (100%), Safe (75%), Neutral (50%), Start Packing (25%), Run to the Hills (0%)
Exposure Index & Scaling
• Dynamic Exposure: 0-100% scaling based on risk-off score
• ML Override: Configurable exposure cap when ML is strongly bearish (default: 25%)
• Applied to Leverage: Exposure index multiplies final leverage recommendation
Single Stock Exit Signals
• 3 Red Days Rule: Optional volume confirmation
• Break Support: 20/50/200 SMA options
• Sentiment Exit: Stock F&G threshold (default: 25)
• ML Exit: Integrated with ML bearish signals
📊 Enhanced Position Sizing
• Sentiment Adjustment: Reduces position size in extreme fear (50%) and extreme greed (70%)
• Trade Filter: Blocks new entries when stock F&G < 25 OR ML is bearish
• ML Confirmation: Optional ML bullish confirmation for new entries
🎯 Leverage Enhancements
• SPX Trend Multiplier: Adjusts leverage based on SPX trend (50% in Strong Down, 110% in Strong Up)
• Risk-Off Multiplier: Reduces leverage when risk-off conditions are met
• Exposure Scaling: Final leverage multiplied by exposure index (0-100%)
• Fixed to SPX Only: Leverage now uses only S&P 500 F&G (not stock-specific)
📅 Configuration Improvements
• F&G Index Defaults: Updated to CNN-aligned values (scale: 0.67, offset: -9.0, weights optimized)
• F&G Trend Defaults: slopeLen=10, consistencyPct=0.80
• Input Organization: Clear sections in order: Company Info → Performance → Sentiment → Risk → ML → Display
• Dedicated ML Group: "🧠 Machine Learning" with 9 configurable parameters
🎨 Visual Enhancements
• Color-Coded Risk Score: Red (≥3), Orange (≥2), Yellow (≥1), Green (<1)
• Color-Coded ML: Red (bearish), Green (bullish), Default (neutral)
• ML Display Toggle: Separate "Show ML in Dashboard" option
• Increased Table Size: 25 rows (side-by-side), 50 rows (vertical) to accommodate new features
• Default Layout: Top-right corner with 10px vertical offset
🚨 Alert System
• 3 Alert Conditions:
1. Portfolio Risk-Off Alert (score ≥ threshold)
2. Stock Exit Alert (technical + sentiment + ML signals)
3. ML High Risk Alert (bearish with confidence <20%)
🔧 Technical Fixes
• Fixed variable naming conflicts (vixWeight, fgWeight renamed with "risk" prefix for Risk-Off components)
• Fixed line continuation syntax errors in PineScript
• Fixed ML prediction persistence across bars using var float
• Corrected leverage variable reference (fg_spx instead of fg_spx_lev)
• Fixed table row index out of bounds errors
Configuration Summary
Recommended Defaults Now Active:
• ML: Enabled by default with "Both" methods
• Risk-Off Threshold: 3 (out of weighted max)
• ML Bearish Exposure Cap: 25%
• Display: Top-right, 10px offset
• All component weights properly balanced
Note di rilascio
fixes for F&G SPX stabilityNote di rilascio
Version Update Summary - November 29, 2025Major Enhancements:
Enhanced Stock Risk Status - Now incorporates STK Trend alongside F&G when determining risk levels (Buy vs Strong Buy conditions require code_stk == 1 or 2)
New Feature: Sector Flow Indicator - Added comprehensive sector rotation tracking above Performance section:
Monitors 11 sector ETFs (XLK, XLF, XLI, XLU, XLV, XLP, XLY, XLB, XLRE, XLC, XLE)
Configurable lookback period and display count
Risk-on/Risk-off color coding with performance rankings
ATR/MAD Display Options - Added toggles to show only ATR and MAD values without SL/TP details for cleaner charts
Updated Default Configurations:
F&G component weights: All set to 1.0, scale 0.6, offset -12.0
ML settings: Weight 1.0, thresholds 0.35/0.65, neighbors 5, learning rate 0.1
Critical Bug Fixes:
Chart-Independence for SPX Metrics - Fixed major issue where SPX Fear & Greed and SPX Trend values changed when switching between different stock charts:
All 7 F&G components now calculate in SPX daily context
All acceleration metrics (EMA smoothing, slope, z-scores) now calculate in SPX daily context
SPX metrics remain constant regardless of viewed stock
UI Improvements - Fixed date range display formatting (replaced arrow with dash separator)
Technical Changes:
Wrapped all SPX calculations in request.security() with daily timeframe to ensure consistency
Refactored breadth calculation with ternary operators
Each SPX acceleration metric uses dedicated request.security() call for proper context isolation
Note di rilascio
Trading Toolkit - December 2025 Update: UI Reorganization & Enhanced LayoutMajor Structural Changes:
Company Info Section Reorganization
Sector now displayed inline with company name (comma-separated)
Removed ticker/timeframe row for cleaner display
Combined P/E ratio and Beta into single row
Moved SMA positions (50, 150, 200) from Market Sentiment to Company Info section
New Volatility Spread Section
Created dedicated section for volatility analysis
Moved ATR (Average True Range) and MAD (Mean Absolute Deviation) metrics here
Includes stop-loss and take-profit levels
Separates volatility measures from risk management for better organization
Enhanced Side-by-Side Layout
Upgraded from 3-column to 4-column layout
New layout: Company Info | Market Sentiment | Volatility Spread | Risk Management
Cleaner visual separation with optimized column dividers
Shortened separator bars (7 rows vs 10) for tighter, more professional appearance
Improved Position Display
Expanded to 3-row format for better readability
Row 1: Share count and total dollar value
Row 2: Portfolio percentage and risk percentage
Row 3: Sentiment adjustment and trade filter status
Updated Documentation
Comprehensive header documentation reflects all structural changes
Accurate section descriptions matching current implementation
Result: Cleaner, more organized display with logical grouping of related metrics. Better space utilization and improved readability in both vertical and side-by-side layouts.
Note di rilascio
Trading Toolkit - December 2025 Update🔧 Major Fixes
SPX Fear & Greed Index - Chart Independence
SPX F&G now remains stable across different stock charts
All 7 components fetch daily data via request.security ensuring consistent values
Momentum and VIX scores computed with daily bar context
Calibration updated (scale=0.78) to align with CNN's published Fear & Greed values
Stock Fear & Greed Index - Timeframe Independence
Stock F&G now uses daily data for all calculations
Remains stable when switching between timeframes (1min, 5min, 1H, 1D, etc.)
Enhanced with 7 components: momentum, volatility, returns, RSI, relative strength, PCR contribution, breadth contribution
Risk Management Accuracy Improvements
VIX threshold raised from 20 to 25 (better reflects elevated volatility)
Fixed "3 Red Days" detection - now correctly identifies exactly 3 consecutive down days (was checking 4)
Removed duplicate sentiment reduction in position sizing calculations
Risk-Off Score thresholds now proportional to maximum weighted score
⚡ Performance Optimizations
Consolidated request.security calls from 40+ down to 15
Eliminated nested security calls that caused subscription limit errors
Removed redundant data fetches
🎯 Configuration Updates
Z-score lookback: 252 bars (~1 trading year) for more stable normalization
Consistency lookback: 5 bars (~1 trading week)
ML thresholds: symmetric at 0.30/0.70 for bearish/bullish signals
KNN neighbors: increased to 8 for more stable predictions
Acceleration penalty: reduced from 0.25 to 0.15 per sigma
📝 Notes
Stocks with less than 1 year of trading history may show slight F&G variations
SPX F&G calibrated to match CNN Fear & Greed Index readings
Trend indicators reflect actual market momentum - flat readings indicate stable conditions
Note di rilascio
Changelog - December 27, 2025🔧 Major Stability Fixes
SPX Fear & Greed Index - Now Truly Market-Wide
Fixed critical issue where SPX F&G score would fluctuate when switching between different stocks
All 7 F&G components now compute their normalized scores entirely within daily request.security context
SPX F&G now remains constant regardless of which stock chart you're viewing
SPX Trend Analysis - Consistent Across All Charts
Moved slope, acceleration, z-score, and consistency calculations inside daily context
Trend indicators (Strong Up/Up/Flat/Down/Strong Down) now stable across all timeframes and symbols
Leverage Target - True Portfolio-Level Metric
Fixed issue where Lev Target changed when switching stocks
Created separate macro-only risk score that excludes stock-specific ML predictions
Leverage calculation now uses only market-wide factors: SPX F&G, VIX, ARKK relative strength, SPX Trend
ML signal still contributes to Risk-Off display but no longer affects portfolio leverage recommendation
🛡️ Risk-Off Score Improvements
VIX risk component now computed entirely in daily VIX context
ARKK weakness detection now computed in daily ARKK context
Separated macro risk (for leverage) from full risk (for display)
Stock-specific ML signal properly categorized as "Stock Level" indicator
🎨 UI/UX Enhancements
Stock Signal Emoji Alignment
Fixed mismatch between Stock status text and emoji colors
🟢 Green now properly shows for "Strong Buy" (F&G > 75 OR Strong Up trend)
🟡 Yellow now properly shows for "Buy" (ML Bullish OR Up trend)
⚙️ Calibration
Updated default F&G scale from 0.74 to 0.79 for better CNN alignment
SPX F&G now reads ~55.5 matching CNN's published value
📊 Technical Improvements
Reduced request.security calls to 15 (well under TradingView's 40 limit)
Consolidated multi-symbol data fetches using tuples
Improved code organization with clearer macro vs stock level separation
Note: After updating, your SPX F&G and Leverage Target will now show consistent values across all stock charts. This is the intended behavior for portfolio-level risk management.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.