OPEN-SOURCE SCRIPT
Mis à jour

Trading Toolkit - Comprehensive Analysis

1 211
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)
Notes de version
Added P/E ratio & beta
Notes de version
📊 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.
Notes de version
🔧 Critical Fix: S&P 500 Data Consistency
Fixed 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.
Notes de version
updating the chart
Notes de version
trying again to update the chart
Notes de version
3rd time a charm
Notes de version
trying to make Trading View to update the chart
Notes de version
another try
Notes de version
updated the Risk section name
Notes de version
Trading Toolkit - Release Notes
Major 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

Notes de version
fixes for F&G SPX stability
Notes de version
Version Update Summary - November 29, 2025

Major 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

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.