Bullish Bearish Signal with EMA Color + LabelsThis script generates clear BUY and SELL signals based on a combination of trend direction, momentum, and confirmation from multiple indicators. It is intended to help traders identify strong bullish or bearish conditions using commonly trusted tools: EMA 200, MACD, and RSI.
🔍 How it works:
The strategy combines three key elements:
EMA 200 Trend Filter
Identifies the long-term trend:
Price above EMA200 → Bullish trend bias
Price below EMA200 → Bearish trend bias
The EMA line is color-coded:
🔵 Blue for bullish
🔴 Red for bearish
⚪ Gray for neutral/unclear
MACD Crossover
Detects shifts in market momentum:
Bullish: MACD line crosses above signal line
Bearish: MACD line crosses below signal line
RSI Confirmation
Adds an extra layer of confirmation:
Bullish: RSI is above its signal line
Bearish: RSI is below its signal line
✅ Signal Logic:
BUY Signal appears when:
Price > EMA200
MACD crosses up
RSI > its signal line
SELL Signal appears when:
Price < EMA200
MACD crosses down
RSI < its signal line
Labels will appear on the chart to highlight these events.
🔔 Alerts:
The script includes alerts for both Buy and Sell conditions, so you can be notified in real-time when they occur.
📈 How to Use:
Best used in trending markets.
Recommended for higher timeframes (1H and above).
May be combined with other tools such as support/resistance or candlestick analysis.
⚠️ Disclaimer: This script is intended for educational purposes only and does not constitute financial advice or a trading recommendation.
Educational
Abusuhil Bullish Candles (Label + Table)Abusuhil Bullish Candles is a pattern recognition indicator designed to identify key bullish reversal candlestick formations including Hammer, Bullish Engulfing, Morning Star, Piercing Line, Three White Soldiers, and Three Inside Up.
The script includes optional filters such as Stochastic and Volume Confirmation, providing more precise signal detection.
Each pattern and filter is fully customizable via settings. Alerts are also included to support active trading workflows.
This script was written originally and does not copy open-source indicators. It's ideal for traders seeking visual clarity on bullish opportunities with professional-grade logic.
مؤشر الشموع الصعودية هو مؤشر احترافي يكتشف أبرز نماذج الانعكاس الصعودي في الشموع اليابانية مثل: Hammer، Bullish Engulfing، Morning Star، Piercing Line، Three White Soldiers، و Three Inside Up.
يوفر المؤشر فلاتر إضافية مثل فلتر Stochastic وفلتر الفوليوم لتعزيز دقة الإشارات. جميع الإعدادات قابلة للتعديل بما يتناسب مع احتياج كل متداول.
يحتوي المؤشر أيضًا على تنبيهات تلقائية لدعم استراتيجيات التداول اللحظي. تمت برمجة المؤشر من الصفر ويعتمد على منطق خاص غير منسوخ من سكربتات مفتوحة المصدر.
--------------------------------------------------------------------------------------------------------------------
🇸🇦 التحديثات – النسخة الجديدة (Abusuhil Bullish Candles)
✅ تم تغيير الملصقات بشكل أوضح: باستخدام دوائر ملونة أسفل الشموع بدلًا من المربعات لتفادي التراكب.
🟦 إضافة جدول تفاعلي على الشارت يعرض أسماء النماذج وألوانها المخصصة.
🎨 إمكانية تغيير ألوان كل نموذج من الإعدادات حسب رغبة المستخدم.
🧩 تفعيل/تعطيل كل نموذج على حدة من خلال إعدادات منفصلة.
🔔 إضافة تنبيه احترافي واحد يتم تفعيله عند تحقق أي نموذج نشط من النماذج المحددة.
📋 توافق كامل مع سياسة TradingView:
لا يحتوي على أكواد منسوخة أو مبنية على مؤشرات داخلية.
لا تكرار للوظائف أو العناوين.
وصف واضح مع تحكم كامل للمستخدم.
🇬🇧 Updates – Latest Version (Abusuhil Bullish Candles)
✅ Clearer Signal Labels: Now uses colored circles under candles instead of labels to avoid overlapping.
🟦 Interactive Table showing pattern names and user-defined colors.
🎨 Customizable colors for each candlestick pattern from the settings menu.
🧩 Toggle each pattern independently using dedicated checkboxes.
🔔 Single professional alert condition that triggers only when any enabled pattern is detected.
📋 Fully compliant with TradingView's publishing policy:
No reused or built-in indicator code.
No duplicated logic or misleading titles.
Clean and modular design with full user customization.
NoNoiseMA & SlopeHappy trade,
This is a noise-reduced moving average — let's call it the No-Noise MA. A MA where false breakout price action should have little to no impact, while the main trend remains fully represented. In comparison to previous MAs this one's trend appear more linear, and sideways price actions becomes easier to detect thanks to it's unique two filter stages.
In short, the No-Noise-MA (Noise-Reduced Moving Average) is calculated as the cumulative sum of the slopes derived from the center line of the last x pivot points. Let’s break it down step by step:
Pivot Detection:
A pivot algorithm (an adapted variant of the Bilson-Gann-Count method) identifies consecutive pivot points (high, low, high, low, etc.) in the close price series. Let's call this set of Pivots S.
Center Line Calculation:
Out of the set S the last x pivots are used to compute a center line (linear regression line). Always when a new pivot is confirmed, the oldest pivot in the queue is removed, and the new pivot is added.
Slope Extraction:
The center line is defined by its equation shown in the image below
Image 1
Cumulative Slope Sum:
As shown in the image 1 the slope is a series with values around zero. The No-Noise-MA is then just the cumulative sum of the slope series and a correction term. A correction term is needed otherwise the No-Noise-MA would run away over time from the original close price. The correction term is just the deviation between close price and cumulative slope sum multiply with a factor around 0.01 added to the No-Noise-MA.
Noise Reduction:
The goal of noise reduction is done by two filter stages. First Filter is the reduction of the input values. As shown above not all bars close prices are use, instead it uses just the pivot points delivered by the Bilson-Gann-Count method. Favorable the Bilson-Gann-Count method delivers the Pivot points in most cases much faster as other Pivot methods. Already after two bars a new Pivot is confirmed. This takes out all ups and downs between two consecutive Pivots. This first filter stage is legit because all price action in between is hedged by the Pivots.
The second filter stage is the done by the length of the center line. As more pivots are used to calculate the center line as smoother the slope becomes. Out liners just gets less impact if the base is bigger. So the number of involved Pivots has the same meaning as the lengths in any other MA.
Comparison with usual MAs:
For a comparison with other MAs this script also calculate the average lengths of the center line, shown in the upper right chart. So choose for example SMA and set the length parameter to the average length of the center line. As shown in the following image 2.
Image 2
This way both MAs have the same data base and can be objectively compared.
Trend detection:
The slope of the center line can be used for trend confirmation. A slope bigger then zero is an up trend while a slope smaller then zero is a down trend. And side way price action is indicated when the slope is around zero within a certain threshold.
Image 3
One hint should be mentioned here. The side way section gets indicated much later. About the number of bars as the center line is long. Before that there are just up or down trend predicted. In the image 2 you see the slope is firstly tin and as more bars past by the slope becomes more thick. This should indicate the point where no side way predictions will happens anymore.
Variation of calculation
In the settings menu you can find the setting "Include last close to center line". With this activated the center line is calculated with the last pivots and the last close price. The last close price is assumed as a pivot too. This gives the slope a more early reaction to volatile price action. But also brings back some noise.
Abusuhil Bullish CandlesAbusuhil Bullish Candles is a pattern recognition indicator designed to identify key bullish reversal candlestick formations including Hammer, Bullish Engulfing, Morning Star, Piercing Line, Three White Soldiers, and Three Inside Up.
The script includes optional filters such as Stochastic and Volume Confirmation, providing more precise signal detection.
Each pattern and filter is fully customizable via settings. Alerts are also included to support active trading workflows.
This script was written originally and does not copy open-source indicators. It's ideal for traders seeking visual clarity on bullish opportunities with professional-grade logic.
مؤشر الشموع الصعودية هو مؤشر احترافي يكتشف أبرز نماذج الانعكاس الصعودي في الشموع اليابانية مثل: Hammer، Bullish Engulfing، Morning Star، Piercing Line، Three White Soldiers، و Three Inside Up.
يوفر المؤشر فلاتر إضافية مثل فلتر Stochastic وفلتر الفوليوم لتعزيز دقة الإشارات. جميع الإعدادات قابلة للتعديل بما يتناسب مع احتياج كل متداول.
يحتوي المؤشر أيضًا على تنبيهات تلقائية لدعم استراتيجيات التداول اللحظي. تمت برمجة المؤشر من الصفر ويعتمد على منطق خاص غير منسوخ من سكربتات مفتوحة المصدر.
SD Median NUPL-Z🧠 Overview
SD Median NUPL-Z is a trend-following indicator that leverages a normalized version of Bitcoin’s Net Unrealized Profit/Loss (NUPL) metric, filtered through a median-based volatility band. Unlike traditional NUPL which is often used to spot extremes, this indicator is designed to identify sustained directional trends — entering only when both on-chain momentum and price structure align.
🧩 Key Features
Z-Scored NUPL Trend Engine: Normalizes NUPL using rolling mean and standard deviation to create a smoothed trend signal.
Price Structure Filter: Implements a median-based price band to avoid false entries during short-term volatility.
Custom Thresholds: User-defined thresholds determine when the trend signal is strong enough to justify a long or short directional bias.
Directional Candle Coloring: Reinforces current trend regime visually with aqua (bullish) and red (bearish) plots and candles.
Optimized for BTC: Uses Bitcoin’s Market Cap and Realized Cap to construct the NUPL input.
🔍 How It Works
On-Chain Core: NUPL is calculated as the percentage of unrealized profit in the market: (Market Cap - Realized Cap) / Market Cap * 100.
Z-Score Transformation: The raw NUPL value is normalized using a rolling average and standard deviation over a set window (default 134 days), producing the NUPL-Z series.
Median-Based Price Filter: A rolling 50th percentile (median) of price is used alongside its own standard deviation to create upper and lower bounds.
These bounds define a "volatility corridor" around price; the trend signal is only acted upon if price confirms by staying outside these bands.
Signal Logic:
A Long signal is triggered when NUPL-Z rises above the long threshold and price is not below the lower band.
A Short signal is triggered when NUPL-Z falls below the short threshold.
State Variable (CD): Tracks the current market regime, used to control plotting and color changes.
🔁 Use Cases & Applications
Momentum-Based Trend Following: Helps traders align with directional moves backed by both on-chain sentiment and supportive price structure.
Filtered Entry Timing: Reduces premature or noise-based entries by requiring price confirmation before committing to NUPL-based signals.
Best Suited for BTC: This tool is designed specifically around Bitcoin’s on-chain metrics and is not intended for altcoins or low-volume assets.
✅ Conclusion
SD Median NUPL-Z repurposes a traditionally cyclical valuation tool into a modern trend-following signal by combining statistical normalization with dynamic price structure filtering. It offers a more robust way to participate in high-conviction directional trends, reducing the likelihood of entering during short-lived counter moves.
⚠️ Disclaimer
The content provided by this indicator is for educational and informational purposes only. Nothing herein constitutes financial or investment advice. Trading and investing involve risk, including the potential loss of capital. Always backtest and apply risk management suited to your strategy.
NUPL-Z For Loop🧠 Overview
NUPL-Z For Loop is a trend-following indicator built on Bitcoin’s on-chain Net Unrealized Profit/Loss (NUPL) metric. It uses a Z-scored transformation of NUPL and a custom loop-based scoring system to measure the consistency of directional movement. Rather than identifying tops and bottoms, this tool is designed to track sustained trends and filter out short-term noise, making it ideal for momentum-aligned strategies.
🧩 Key Features
Loop-Based Trend Logic: Assesses trend strength by summing the number of upward vs. downward moves in Z-scored NUPL across a custom lookback.
Z-Score Normalization: Applies long-term statistical normalization to NUPL to emphasize deviation from average behavior over time.
Threshold-Based Regime Shifts: Custom input thresholds define when trend strength is significant enough to trigger long or short signals.
Directional Market State Tracking: Internally tracks bullish, bearish, or neutral conditions to guide trend entries.
BTC-Focused On-Chain Analysis: Tailored specifically for Bitcoin using Market Cap and Realized Cap inputs.
🔍 How It Works
NUPL Calculation: Derived as the percentage of net unrealized profit relative to market cap: (MC - RMC) / MC * 100.
Z-Scoring: NUPL is normalized using a rolling mean and standard deviation over a long window (default 1300 days) to create a smoothed trend signal.
Directional Loop: A custom loop iterates from the start_loop to the end_loop, comparing the current Z-score to past values.
Each instance where NUPL_Z > NUPL_Z adds +1 to the score; otherwise, it subtracts -1.
This cumulative score reflects how consistently NUPL-Z has been trending.
Signal Logic:
Long signal when loop score exceeds long_threshold.
Short signal when score falls below short_threshold.
CD State Engine: Maintains the current trend regime (1 for long, -1 for short), which drives plot coloring and overlays.
🔁 Use Cases & Applications
Momentum Trend Filter: Detects and confirms sustained directional strength in BTC’s profit/loss positioning.
Noise Suppression: Avoids reactive signals from one-off spikes or dips in NUPL by requiring a consistent trend before confirming bias.
Best Suited for BTC: Designed specifically for Bitcoin’s price and on-chain structure, using its unique NUPL dynamics.
✅ Conclusion
NUPL-Z For Loop transforms a traditionally mean-reverting indicator into a trend-following signal engine. By scoring the consistency of movement in normalized NUPL, this tool identifies trend strength rather than reversal potential — providing more reliable context for momentum-aligned trades on Bitcoin.
⚠️ Disclaimer
The content provided by this indicator is for educational and informational purposes only. Nothing herein constitutes financial or investment advice. Trading and investing involve risk, including the potential loss of capital. Always backtest and apply risk management suited to your strategy.
MVRV-Z For Loop🧠 Overview
MVRV-Z For Loop is a trend-following indicator that applies a custom directional for-loop logic to the MVRV Z-score. By evaluating the number of consecutive Z-score improvements or deteriorations over time, it identifies sustained directional pressure in Bitcoin’s on-chain trend — helping traders align with prevailing market strength rather than reacting to single-point extremes.
🧩 Key Features
Loop-Based Trend Filter: Applies a running comparison loop to assess whether MVRV-Z has been consistently strengthening or weakening.
Directional Scoring System: Each upward movement contributes positively, and each downward movement negatively, producing a cumulative trend score.
Z-Scored MVRV: Leverages on-chain valuation via the Market Cap to Realized Cap ratio, normalized using a long-term rolling average and standard deviation.
Custom Thresholds: User-defined thresholds for long and short signals based on trend score magnitude.
Dynamic Candle Coloring: Visually reinforces trend state with aqua for bullish and red for bearish environments.
🔍 How It Works
Z-score Transformation: The MVRV ratio is normalized over a long lookback (default 1050 days), creating a standardized valuation signal.
For-Loop Engine: A directional loop compares the current MVRV-Z value to previous values within a defined range (start to end).
If today’s value is higher than ma , it adds +1 to the score; otherwise, it subtracts -1.
This loop effectively measures momentum consistency rather than magnitude alone.
Signal Logic:
A Long signal is triggered when the cumulative trend score exceeds the long_threshold.
A Short signal is triggered when the score drops below the short_threshold.
State Variable (CD): Tracks the market regime (1 = long, -1 = short), updating only when a valid condition is met.
🔁 Use Cases & Applications
Trend Confirmation Tool: Helps traders assess whether a directional move has been sustained over time before committing.
Momentum Alignment: Filters out short-term noise by scoring consistency in MVRV-Z movement rather than relying on single-bar reversals.
Best Suited for BTC: This indicator is specifically built using Bitcoin’s Market Cap and Realized Cap metrics, making it ideal for BTC trend tracking.
✅ Conclusion
MVRV-Z For Loop transforms the traditional MVRV Z-score into a trend-following signal using a cumulative scoring approach. It excels in highlighting sustained directional strength and avoids premature entries during valuation whipsaws. This makes it a strong tool for traders looking to stay on the right side of the trend without overreacting to short-term fluctuations.
⚠️ Disclaimer
The content provided by this indicator is for educational and informational purposes only. Nothing herein constitutes financial or investment advice. Trading and investing involve risk, including the potential loss of capital. Always backtest and apply risk management suited to your strategy.
SD Median MVRV-Z🧠 Overview
SD Median MVRV-Z is a trend-following indicator that uses on-chain valuation signals as a supportive filter. It blends the momentum of the MVRV Z-score with a dynamic median-based price structure to provide cleaner, more reliable directional signals. This tool is designed to identify when price and trend align with favorable broader context — not to pinpoint overbought or oversold extremes.
🧩 Key Features
Trend-Following Core: Signals are built around directional strength, not reversion.
MVRV Z-Score Momentum: Utilizes the statistical momentum of Market Cap vs Realized Cap as a macro trend driver.
Rolling Median Filter: Applies a price-based condition to ensure trend signals are not triggered during short-term counter-moves or noise.
Threshold Customization: Input controls allow traders to define the strength required to trigger long or short signals.
Dynamic Visualization: Candle coloring and filled zones provide instant feedback on current market regime.
🔍 How It Works
Trend Signal: The MVRV ratio is normalized via Z-scoring to produce a momentum-like signal based on how far current valuation deviates from its rolling average.
Price Filter: A rolling median and standard deviation of price define an upper and lower band. These serve to filter out MVRV-Z signals that occur when price is moving against the perceived direction.
Signal Logic:
Long signal = MVRV-Z above threshold and price is not in the lower volatility band.
Short signal = MVRV-Z below threshold, regardless of price band (more aggressive condition).
Directional Engine (CD): Encodes the market regime state (1 for long, -1 for short, 0 for neutral), and drives all visual outputs.
🔁 Use Cases & Applications
Momentum Confirmation: Identify when on-chain momentum and price structure both confirm a trend direction.
Reduced Whipsawing: Filter out weak or conflicting trend signals that would otherwise lead to false entries.
Best Suited for BTC: This indicator is specifically tailored for Bitcoin, using BTC’s Market Cap and Realized Cap data from on-chain sources.
✅ Conclusion
SD Median MVRV-Z is a trend-centric tool that ensures directional conviction by requiring agreement between price structure and underlying market momentum. It is not meant to detect tops or bottoms, but instead to help traders participate in sustainable moves with greater confidence.
⚠️ Disclaimer
The content provided by this indicator is for educational and informational purposes only. Nothing herein constitutes financial or investment advice. Trading and investing involve risk, including the potential loss of capital. Always backtest and apply risk management suited to your strategy.
RSI Buy Sell Signals[RanaAlgo]Overview
This Premium RSI with Enhanced Signals builds upon the classic Relative Strength Index by incorporating multiple confirmation filters and visual enhancements to improve signal reliability. The indicator goes beyond basic overbought/oversold levels by adding volume confirmation, trend alignment, and peak detection logic.
Key Features
Enhanced Signal Detection
Peak Strength Filter: Requires RSI movements to meet minimum strength criteria (configurable from 1-5 bars)
Volume Confirmation: Optional volume filter to ensure signals occur with above-average trading activity
Trend Alignment: Optional trend confirmation that checks price position relative to 20-period EMA
Visual Improvements
Dynamic coloring of RSI line (green in oversold, red in overbought)
Customizable reference lines and zones
Clear buy/sell signals with triangle markers
Comprehensive info panel showing current RSI status
Alert Capabilities
Ready-to-use alert conditions for both buy and sell signals
Visual and audible alerts when signals trigger
How It Works
Core RSI Calculation: Uses standard RSI formula with configurable length (default 14)
Signal Generation:
Buy signals require either:
RSI rising from oversold with volume/trend confirmation (when enabled)
Simple crossover above oversold level (when filters disabled)
Sell signals require either:
RSI falling from overbought with volume/trend confirmation
Simple crossunder below overbought level
Additional Filters:
Minimum peak strength prevents weak, insignificant movements from generating signals
Volume filter helps confirm institutional participation
Trend filter aligns signals with broader price direction
Usage Instructions
Apply to any chart timeframe (works best on 1H or higher)
Configure settings in the input panel:
Adjust RSI length if needed
Set overbought/oversold levels (default 70/30)
Enable/disable volume and trend filters
Customize visual elements
Signals appear as triangles below/above the RSI line
Use alerts to get notified of new signals
Differentiation from Standard RSI
This indicator adds several layers of confirmation that aren't present in the basic RSI:
Multi-bar momentum requirement for peaks/troughs
Volume validation option
Trend confirmation option
Smoothed RSI line for cleaner visualization
Comprehensive info panel with current status
The combination of these features helps filter out false signals that commonly occur with traditional RSI implementations.
Correlation Coefficient📊 Correlation Coefficient (CC)
This indicator measures the statistical correlation between two selected securities over a defined period, scaled from -100 to +100.
It helps you quickly assess whether assets are moving:
Together (positive correlation)
Opposite (negative correlation)
Independently (zero correlation)
🔧 Features:
Select any two symbols (default: NIFTY & BANKNIFTY)
Adjustable length parameter for short-term or long-term correlation analysis
Clean, color-coded plot with horizontal levels to easily identify key correlation zones
📈 Useful For:
Pair trading setups
Hedging strategies
Detecting market regime shifts or intermarket divergences
⚠️ Disclaimer: This is not trading or investment advice.
This indicator is intended for informational purposes only and is not recommended for making
direct trading decisions.
$ADD LevelsThis Pine Script is designed to track and visualize the NYSE Advance-Decline Line (ADD). The Advance-Decline Line is a popular market breadth indicator, showing the difference between advancing and declining stocks on the NYSE. It’s often used to gauge overall market sentiment and strength.
1. //@version=5
This line tells TradingView to use Pine Script v5, the latest and most powerful version of Pine.
2. indicator(" USI:ADD Levels", overlay=false)
• This creates a new indicator called ” USI:ADD Levels”.
• overlay=false means it will appear in a separate pane, not on the main price chart.
3. add = request.security(...)
This fetches real-time data from the symbol USI:ADD (Advance-Decline Line) using a 1-minute timeframe. You can change the timeframe if needed.
add_symbol = input.symbol(" USI:ADD ", "Market Breadth Symbol")
add = request.security(add_symbol, "1", close)
4. Key Thresholds
These define the market sentiment zones:
Zone. Value. Meaning
Overbought +1500 Extremely bullish
Bullish +1000 Generally bullish trend
Neutral ±500 Choppy, unclear market
Bearish -1000 Generally bearish trend
Oversold -1500 Extremely bearish
5. Plot the ADD Line hline(...)
Draws static lines at +1500, +1000, +500, -500, -1000, -1500 for reference so you can visually assess where ADD stands.
6. Horizontal Threshold Lines bgcolor(...)
• Green background if ADD > +1500 → extremely bullish.
• Red background if ADD < -1500 → extremely bearish.
7. Background Highlights alertcondition(...)
• Green background if ADD > +1500 → extremely bullish.
• Red background if ADD < -1500 → extremely bearish.
8. Alert Conditions. alertcondition(...)
Lets you create automatic alerts for:
• USI:ADD being very high or low.
• Crosses above +1000 (bullish trigger).
• Crosses below -1000 (bearish trigger).
You can use these to trigger trades or monitor sentiment shifts.
Summary: When to Use It
• Use this script in a market breadth dashboard.
• Combine it with price action and volume analysis.
• Monitor for ADD crosses to signal potential market reversals or momentum.
TICK Extreme Levels & AlertsAutomatically draws horizontal lines at +1000 and -1000 TICK levels
Sends alerts when TICK crosses those levels (for potential scalping/reversal setups)
Strategy: How to Use TICK in Real-Time Trading
1. Confirm Market Breadth
Use TICK to confirm broad participation in the move:
• Long S&P futures or SPY? Only buy breakouts if TICK is above +600 to +1000
• Shorting? Confirm with TICK below –600 to –1000
2. Fade Extremes for Scalps
Look for reversals at extreme levels:
• Fade +1200+: market likely overbought short term → scalp short
• Fade –1200–: market likely oversold → scalp long
Use in combo with other signals (like price exhaustion, candlestick reversal, or VWAP touches)
3. Avoid Trading in the Choppy Zone
If TICK remains between –400 and +400, institutions are not committed. This is where fakeouts are common.
4. Time Entries with TICK Swings
For example:
• TICK moves from –800 to +600 = momentum shift → look for long entries
• TICK stalling around +1000 = momentum climax → partial profit or fade play
EMA 200 Price Deviation Alerts (1H Only)This script monitors the price deviation from the 200-period Exponential Moving Average (EMA) exclusively on the 1-hour chart. It generates alerts when the absolute difference between the current price and the EMA 200 exceeds a user-defined threshold (default: 65).
Features:
Works only on 1-hour (60-minute) charts to avoid false signals on other timeframes.
Customizable deviation threshold via script input.
Visual display of the 200 EMA on the chart.
Alert system to notify when price deviates significantly above or below the EMA.
Buy/Sell arrows shown when conditions are met:
Sell arrow appears when price is above the EMA and deviation exceeds threshold.
Buy arrow appears when price is below the EMA and deviation exceeds threshold.
Use this tool to identify potential overextended price moves relative to long-term trend support or resistance on the 1H timeframe.
Enhanced Stock Ticker with 50MA vs 200MADescription
The Enhanced Stock Ticker with 50MA vs 200MA is a versatile Pine Script indicator designed to visualize the relative position of a stock's price within its short-term and long-term price ranges, providing actionable bullish and bearish signals. By calculating normalized indices based on user-defined lookback periods (defaulting to 50 and 200 bars), this indicator helps traders identify potential reversals or trend continuations. It offers the flexibility to plot signals either on the main price chart or in a separate lower pane, leveraging Pine Script v6's force_overlay functionality for seamless integration. The indicator also includes a customizable ticker table, visual fills, and alert conditions for automated trading setups.
Key Features
Dual Lookback Indices: Computes short-term (default: 50 bars) and long-term (default: 200 bars) indices, normalizing the closing price relative to the high/low range over the specified periods.
Flexible Signal Plotting: Users can toggle between plotting crossover signals (triangles) on the main price chart (location.abovebar/belowbar) or in the lower pane (location.top/bottom) using the Plot Signals on Main Chart option.
Crossover Signals: Generates bullish (Golden Cross) and bearish (Death Cross) signals when the short or long index crosses above 5 or below 95, respectively.
Visual Enhancements:
Plots short-term (blue) and long-term (white) indices in a separate pane with customizable lookback periods.
Includes horizontal reference lines at 0, 20, 50, 80, and 100, with green and red fills to highlight overbought/oversold zones.
Dynamic fill between indices (green when short > long, red when long > short) for quick trend visualization.
Displays a ticker and legend table in the top-right corner, showing the symbol and lookback periods.
Alert Conditions: Supports alerts for bullish and bearish crossovers on both short and long indices, enabling integration with TradingView's alert system.
Technical Innovation: Utilizes Pine Script v6's force_overlay parameter to plot signals on the main chart from a non-overlay indicator, combining the benefits of a separate pane and chart-based signals in a single script.
Technical Details
Calculation Logic:
Uses confirmed bars (barstate.isconfirmed) to calculate indices, ensuring reliability by avoiding real-time bar fluctuations.
Short-term index: (close - lowest(low, lookback_short)) / (highest(high, lookback_short) - lowest(low, lookback_short)) * 100
Long-term index: (close - lowest(low, lookback_long)) / (highest(high, lookback_long) - lowest(low, lookback_long)) * 100
Signals are triggered using ta.crossover() and ta.crossunder() for indices crossing 5 (bullish) and 95 (bearish).
Signal Plotting:
Main chart signals use force_overlay=true with location.abovebar/belowbar for precise alignment with price bars.
Lower pane signals use location.top/bottom for visibility within the indicator pane.
Plotting is controlled by boolean conditions (e.g., bullishLong and plot_on_chart) to ensure compliance with Pine Script's global scope requirements.
Performance Considerations: Optimized for efficiency by calculating indices only on confirmed bars and using lightweight plotting functions.
How to Use
Add to Chart:
Copy the script into TradingView's Pine Editor and add it to your chart.
Configure Settings:
Short Lookback Period: Adjust the short-term lookback (default: 50 bars) to match your trading style (e.g., 20 for shorter-term analysis).
Long Lookback Period: Adjust the long-term lookback (default: 200 bars) for broader market context.
Plot Signals on Main Chart: Check this box to display signals on the price chart; uncheck to show signals in the lower pane.
Interpret Signals:
Golden Cross (Bullish): Green (long) or blue (short) triangles indicate the index crossing above 5, suggesting a potential buying opportunity.
Death Cross (Bearish): Red (long) or white (short) triangles indicate the index crossing below 95, signaling a potential selling opportunity.
Set Alerts:
Use TradingView's alert system to create notifications for the four alert conditions: Long Index Valley, Long Index Peak, Short Index Valley, and Short Index Peak.
Customize Visuals:
The ticker table displays the symbol and lookback periods in the top-right corner.
Adjust colors and styles via TradingView's settings if desired.
Example Use Cases
Swing Trading: Use the short-term index (e.g., 50 bars) to identify short-term reversals within a broader trend defined by the long-term index.
Trend Confirmation: Monitor the fill between indices to confirm whether the short-term trend aligns with the long-term trend.
Automated Trading: Leverage alert conditions to integrate with bots or manual trading strategies.
Notes
Testing: Always backtest the indicator on your chosen market and timeframe to validate its effectiveness.
Optional Histogram: The script includes a commented-out histogram for the index difference (index_short - index_long). Uncomment the plot(index_diff, ...) line to enable it.
Compatibility: Built for Pine Script v6 and tested on TradingView as of May 27, 2025.
Acknowledgments
This indicator was inspired by the need for a flexible tool that combines lower-pane analysis with main chart signals, made possible by Pine Script's force_overlay feature. Share your feedback or suggestions in the comments below, and happy trading!
S&P 500 & Normalized CAPE Z-Score AnalyzerThis macro-focused indicator visualizes the historical valuation of the U.S. equity market using the CAPE ratio (Shiller P/E), normalized over its long-term average and standard deviations. It helps traders and investors identify overvaluation and undervaluation zones over time, combining both statistical signals and historical context.
💡 Why It’s Useful
This indicator is ideal for macro traders and long-term investors looking to contextualize equity valuations across decades. It helps identify statistical extremes in valuation by referencing the standard deviation of the CAPE ratio relative to its long-term mean. The overlay of S&P 500 price with valuation zones provides a visual confirmation tool for macro decisions or timing insights.
It includes:
✅ Three display modes:
-S&P 500 (color-coded by CAPE valuation zone)
-Normalized CAPE (vs. long-term mean)
-CAPE Z-Score (standardized measure)
🎯 How to Interpret
Dynamic coloring of the S&P 500 price based on CAPE valuation:
🔴 Z > +2σ → Highly Overvalued
🟠 Z > +1σ → Overvalued
⚪ -1σ < Z < +1σ → Neutral
🟢 Z < -1σ → Undervalued
✅ Z < -2σ → Strong Buy Zone
-Live valuation label showing the current CAPE, Z-score, and zone.
-Macro event shading: major historical events (e.g. Great Depression, Oil Crisis, Dot-com Bubble, COVID Crash) are shaded on the chart for context.
✅ Built-in alerts:
CAPE > +2σ → Potential risk zone
CAPE < -2σ → Potential opportunity zone
📊 Use Cases
This indicator is ideal for:
🧠 Macro traders seeking long-term valuation extremes.
📈 Portfolio managers monitoring systemic valuation risk.
🏛️ Long-term investors timing strategic allocation shifts.
🧪 How It Works
CAPE ratio (Shiller PE) is retrieved from Quandl (MULTPL/SHILLER_PE_RATIO_MONTH).
The script calculates the long-term average and standard deviation of CAPE.
The Z-score is computed as:
(CAPE - Mean) / Standard Deviation
Users can switch between:
S&P 500 chart, color-coded by CAPE valuation zones.
Normalized CAPE, centered around zero (historic mean).
CAPE Z-score, showing statistical positioning directly.
Visual bands represent +1σ, +2σ, -1σ, -2σ thresholds.
You can switch between modes using the “Display” dropdown in the settings panel.
📊 Data Sources
CAPE: MULTPL/SHILLER_PE_RATIO_MONTH via Quandl
S&P 500: Monthly close prices of SPX (TradingView data)
All data updated on monthly resolution
This is not a repackaged built-in or autogenerated script. It’s a custom-built and interactive indicator designed for educational and analytical use in macroeconomic valuation studies.
TP/SL Overlay with Volume/ATR TableThis is a Take Profit and Stop Loss indicator that plots the TP/SL levels, along with the Risk/Reward ratios on the chart similar to an auto fib overlay. These levels are ATR based and are dynamic, based on the current price. It also includes heads-up display that shows the Relative Volume, ATR and several TP levels. All settings and configurations are editable from the settings menu, as well. I created this to make it easier to estimate TP levels without having to pull up a calculator or the "Long" tool that TradingView provides. Hope you like it!
EMD Trend [InvestorUnknown]EMD Trend is a dynamic trend-following indicator that utilizes Exponential Moving Deviation (EMD) to build adaptive channels around a selected moving average. Designed for traders who value responsive trend signals with built-in volatility sensitivity, this tool highlights directional bias, market regime shifts, and potential breakout opportunities.
How It Works
Instead of using standard deviation, EMD Trend employs the exponential moving average of the absolute deviation from a moving average—producing smoother, faster-reacting upper and lower bounds:
Bullish (Risk-ON Long): Price crosses above the upper EMD band
Bearish (Risk-ON Short): Price crosses below the lower EMD band
Neutral: Price stays within the channel, indicating potential mean reversion or low momentum
Trend direction is defined by price interaction with these bands, and visual cues (color-coded bars and fills) help quickly identify market conditions.
Features
7 Moving Average Types: SMA, EMA, HMA, DEMA, TEMA, RMA, FRAMA
Custom Price Source: Choose close, hl2, ohlc4, or others
EMD Multiplier: Controls the width of the deviation envelope
Bar Coloring: Candles change color based on current trend
Intra-bar Signal Option: Enables faster updates (with optional repainting)
Speculative Zones: Fills highlight aggressive momentum moves beyond EMD bounds
Backtest Mode
Switch to Backtest Mode for performance evaluation over historical data:
Equity Curve Plot: Compare EMD Trend strategy vs. Buy & Hold
Trade Metrics Table: View number of trades, win/loss stats, profits
Performance Metrics Table: Includes CAGR, Sharpe, max drawdown, and more
Custom Start Date: Select from which date the backtest should begin
Trade Sizing: Configure capital and trade percentage per entry
Signal Filters: Choose from Long Only, Short Only, or Both
Alerts
Built-in alerts let you automate entries, exits, and trend transitions:
LONG (EMD Trend) - Trend flips to Long
SHORT (EMD Trend) - Trend flips to Short
RISK-ON LONG - Price crosses above upper EMD band
RISK-OFF LONG - Price crosses back below upper EMD band
RISK-ON SHORT - Price crosses below lower EMD band
RISK-OFF SHORT - Price crosses back above lower EMD band
Use Cases
Trend Confirmation with volatility-sensitive boundaries
Momentum Entry Filtering via breakout zones
Mean Reversion Avoidance in sideways markets
Backtesting & Strategy Building with real-time metrics
Disclaimer
This indicator is intended for informational and educational purposes only. It does not constitute investment advice. Historical performance does not guarantee future results. Always backtest and use in simulation before live trading.
RMSD Trend [InvestorUnknown]RMSD Trend is a trend-following indicator that utilizes Root Mean Square Deviation (RMSD) to dynamically construct a volatility-weighted trend channel around a selected moving average. This indicator is designed to enhance signal clarity, minimize noise, and offer quantitative insights into market momentum, ideal for both discretionary and systematic traders.
How It Works
At its core, RMSD Trend calculates a deviation band around a selected moving average using the Root Mean Square Deviation (similar to standard deviation but with squared errors), capturing the magnitude of price dispersion over a user-defined period. The logic is simple:
When price crosses above the upper deviation band, the market is considered bullish (Risk-ON Long).
When price crosses below the lower deviation band, the market is considered bearish (Risk-ON Short).
If price stays within the band, the market is interpreted as neutral or ranging, offering low-risk decision zones.
The indicator also generates trend flips (Long/Short) based on crossovers and crossunders of the price and the RMSD bands, and colors candles accordingly for enhanced visual feedback.
Features
7 Moving Average Types: Choose between SMA, EMA, HMA, DEMA, TEMA, RMA, and FRAMA for flexibility.
Customizable Source Input: Use price types like close, hl2, ohlc4, etc.
Volatility-Aware Channel: Adjustable RMSD multiplier determines band width based on volatility.
Smart Coloring: Candles and bands adapt their colors to reflect trend direction (green for bullish, red for bearish).
Intra-bar Repainting Toggle: Option to allow more responsive but repaintable signals.
Speculation Fill Zones: When price exceeds the deviation channel, a semi-transparent fill highlights potential momentum surges.
Backtest Mode
Switching to Backtest Mode unlocks a robust suite of simulation features:
Built-in Equity Curve: Visualizes both strategy equity and Buy & Hold performance.
Trade Metrics Table: Displays the number of trades, win rates, gross profits/losses, and long/short breakdowns.
Performance Metrics Table: Includes key stats like CAGR, drawdown, Sharpe ratio, and more.
Custom Date Range: Set a custom start date for your backtest.
Trade Sizing: Simulate results using position sizing and initial capital settings.
Signal Filters: Choose between Long & Short, Long Only, or Short Only strategies.
Alerts
The RMSD Trend includes six built-in alert conditions:
LONG (RMSD Trend) - Trend flips from Short to Long
SHORT (RMSD Trend) - Trend flips from Long to Short
RISK-ON LONG (RMSD Trend) - Price crosses above upper RMSD band
RISK-OFF LONG (RMSD Trend) - Price falls back below upper RMSD band
RISK-ON SHORT (RMSD Trend) - Price crosses below lower RMSD band
RISK-OFF SHORT (RMSD Trend) - Price rises back above lower RMSD band
Use Cases
Trend Confirmation: Confirms directional bias with RMSD-weighted confidence zones.
Breakout Detection: Highlights moments when price breaks free from historical volatility norms.
Mean Reversion Filtering: Avoids false signals by incorporating RMSD’s volatility sensitivity.
Strategy Development: Backtest your signals or integrate with a broader system for alpha generation.
Settings Summary
Display Mode: Overlay (default) or Backtest Mode
Average Type: Choose from SMA, EMA, HMA, DEMA, etc.
Average Length: Lookback window for moving average
RMSD Multiplier: Band width control based on RMS deviation
Source: Input price source (close, hl2, ohlc4, etc.)
Intra-bar Updating: Real-time updates (may repaint)
Color Bars: Toggle bar coloring by trend direction
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Past performance, including backtest results, is not indicative of future results. Use with caution and always test thoroughly before live deployment.
Trailing Stop Loss [TradingFinder] 4 Machine Learning Methods🔵 Introduction
The trailing stop indicator dynamically adjusts stop-loss (SL) levels to lock in profits as price moves favorably. It uses pivot levels and ATR to set optimal SL points, balancing risk and reward.
Trade confirmation filters, a key feature, ensure entries align with market conditions, reducing false signals. In 2023 a study showed filtered entries improve win rates by 15% in forex. This enhances trade precision.
SL settings, ranging from very tight to very wide, adapt to volatility via ATR calculations. These settings anchor SL to previous pivot levels, ensuring alignment with market structure. This caters to diverse trading styles, from scalping to swing trading.
The indicator colors the profit zone between the entry point (EP) and SL, using light green for buy trades and light red for sell trades. This visual cue highlights profit potential. It’s ideal for traders seeking dynamic risk management.
A table displays real-time trade details, including EP, SL, and profit/loss (PNL). Backtests show trailing stops cut losses by 20% in trending markets. This transparency aids decision-making.
🔵 How to Use
🟣 SL Levels
The trailing stop indicator sets SL based on pivot levels and ATR, offering four options: very tight, tight, wide, or very wide. Very tight SLs suit scalpers, while wide SLs fit swing traders. Select the base level to match your strategy.
If price hits the SL, the trade closes, and the indicator evaluates the next trade using the selected filter. This ensures disciplined trade management. The cycle restarts with a new confirmed entry.
Very tight SLs, set near recent pivots, trigger exits early to minimize risk but limit profits in volatile markets. Wide SLs, shown as farther lines, allow more price movement but increase exposure to losses. Adjust based on ATR and conditions, noting SL breaches open new positions.
🟣 Visualization
The indicator’s visual cues, like colored profit zones, simplify monitoring, with light green showing the profit area from EP to trailed SL. Dashed lines mark entry points, while solid lines track the trailed SL, triggering new positions when breached.
When price moves into profit, the area between EP and SL is colored—light green for longs, light red for shorts. This highlights the profit zone visually. The SL trails price, locking in gains as the trade progresses.
🟣 Filters
Upon trade entry, the indicator requires confirmation via filters like SMA 2x or ADX to validate momentum. Filters reduce false entries, though no guarantee exists for improved outcomes. Monitor price action post-entry for trade validity.
Filters like Momentum or ADX assess trend strength before entry. For example, ADX above 25 confirms strong trends. Choose “none” for unfiltered entries.
🟣 Bullish Alert
For a bullish trade, the indicator opens a long position with a green SL Line (after optional filters), trailing the SL below price. Set alerts to On in the settings for notifications, or Off to monitor manually.
🟣 Bearish Alert
In a bearish trade, the indicator opens a short position with a red SL Line post-confirmation, trailing the SL above price. With alerts On in the settings, it notifies the potential reversal.
🟣 Panel
A table displays all trades’ details, including Win Rates, PNL, and trade status. This real-time data aids in tracking performance. Check the table to assess trade outcomes instantly.
Review the table regularly to evaluate trade performance and adjust settings. Consistent monitoring ensures alignment with market dynamics. This maximizes the indicator’s effectiveness.
🔵 Settings
Length (Default: 10) : Sets the pivot period for calculating SL levels, balancing sensitivity and reliability.
Base Level : Options (“Very tight,” “Tight,” “Wide,” “Very wide”) adjust SL distance via ATR.
Show EP Checkbox : Toggles visibility of the entry point on the chart.
Show PNL : Displays profit/loss data for active and closed trades.
Filter : Options (“none,” “SMA 2x,” “Momentum,” “ADX”) validate trade entries.
🔵 Conclusion
The trailing stop indicator, a dynamic risk management tool, adjusts SLs using pivot levels and ATR. Its confirmation filters reduce false entries, boosting precision. Backtests show 20% loss reduction in trending markets.
Customizable SL settings and visual profit zones enhance usability across trading styles. The real-time table provides clear trade insights, streamlining analysis. It’s ideal for forex, stocks, or crypto.
While filters like ADX improve entry accuracy, no setup guarantees success in all conditions. Contextual analysis, like trend strength, is key. This indicator empowers disciplined, data-driven trading.
Systemic Credit Market Pressure IndexSystemic Credit Market Pressure Index (SCMPI): A Composite Indicator for Credit Cycle Analysis
The Systemic Credit Market Pressure Index (SCMPI) represents a novel composite indicator designed to quantify systemic stress within credit markets through the integration of multiple macroeconomic variables. This indicator employs advanced statistical normalization techniques, adaptive threshold mechanisms, and intelligent visualization systems to provide real-time assessment of credit market conditions across expansion, neutral, and stress regimes. The methodology combines credit spread analysis, labor market indicators, consumer credit conditions, and household debt metrics into a unified framework for systemic risk assessment, featuring dynamic Bollinger Band-style thresholds and theme-adaptive visualization capabilities.
## 1. Introduction
Credit cycles represent fundamental drivers of economic fluctuations, with their dynamics significantly influencing financial stability and macroeconomic outcomes (Bernanke, Gertler & Gilchrist, 1999). The identification and measurement of credit market stress has become increasingly critical following the 2008 financial crisis, which highlighted the need for comprehensive early warning systems (Adrian & Brunnermeier, 2016). Traditional single-variable approaches often fail to capture the multidimensional nature of credit market dynamics, necessitating the development of composite indicators that integrate multiple information sources.
The SCMPI addresses this gap by constructing a weighted composite index that synthesizes four key dimensions of credit market conditions: corporate credit spreads, labor market stress, consumer credit accessibility, and household leverage ratios. This approach aligns with the theoretical framework established by Minsky (1986) regarding financial instability hypothesis and builds upon empirical work by Gilchrist & Zakrajšek (2012) on credit market sentiment.
## 2. Theoretical Framework
### 2.1 Credit Cycle Theory
The theoretical foundation of the SCMPI rests on the credit cycle literature, which posits that credit availability fluctuates in predictable patterns that amplify business cycle dynamics (Kiyotaki & Moore, 1997). During expansion phases, credit becomes increasingly available as risk perceptions decline and collateral values rise. Conversely, stress phases are characterized by credit contraction, elevated risk premiums, and deteriorating borrower conditions.
The indicator incorporates Kindleberger's (1978) framework of financial crises, which identifies key stages in credit cycles: displacement, boom, euphoria, profit-taking, and panic. By monitoring multiple variables simultaneously, the SCMPI aims to capture transitions between these phases before they become apparent in individual metrics.
### 2.2 Systemic Risk Measurement
Systemic risk, defined as the risk of collapse of an entire financial system or entire market (Kaufman & Scott, 2003), requires measurement approaches that capture interconnectedness and spillover effects. The SCMPI follows the methodology established by Bisias et al. (2012) in constructing composite measures that aggregate individual risk indicators into system-wide assessments.
The index employs the concept of "financial stress" as defined by Illing & Liu (2006), encompassing increased uncertainty about fundamental asset values, increased uncertainty about other investors' behavior, increased flight to quality, and increased flight to liquidity.
## 3. Methodology
### 3.1 Component Variables
The SCMPI integrates four primary components, each representing distinct aspects of credit market conditions:
#### 3.1.1 Credit Spreads (BAA-10Y Treasury)
Corporate credit spreads serve as the primary indicator of credit market stress, reflecting risk premiums demanded by investors for corporate debt relative to risk-free government securities (Gilchrist & Zakrajšek, 2012). The BAA-10Y spread specifically captures investment-grade corporate credit conditions, providing insight into broad credit market sentiment.
#### 3.1.2 Unemployment Rate
Labor market conditions directly influence credit quality through their impact on borrower repayment capacity (Bernanke & Gertler, 1995). Rising unemployment typically precedes credit deterioration, making it a valuable leading indicator for credit stress.
#### 3.1.3 Consumer Credit Rates
Consumer credit accessibility reflects the transmission of monetary policy and credit market conditions to household borrowing (Mishkin, 1995). Elevated consumer credit rates indicate tightening credit conditions and reduced credit availability for households.
#### 3.1.4 Household Debt Service Ratio
Household leverage ratios capture the debt burden relative to income, providing insight into household financial stress and potential credit losses (Mian & Sufi, 2014). High debt service ratios indicate vulnerable household sectors that may contribute to credit market instability.
### 3.2 Statistical Methodology
#### 3.2.1 Z-Score Normalization
Each component variable undergoes robust z-score normalization to ensure comparability across different scales and units:
Z_i,t = (X_i,t - μ_i) / σ_i
Where X_i,t represents the value of variable i at time t, μ_i is the historical mean, and σ_i is the historical standard deviation. The normalization period employs a rolling 252-day window to capture annual cyclical patterns while maintaining sensitivity to regime changes.
#### 3.2.2 Adaptive Smoothing
To reduce noise while preserving signal quality, the indicator employs exponential moving average (EMA) smoothing with adaptive parameters:
EMA_t = α × Z_t + (1-α) × EMA_{t-1}
Where α = 2/(n+1) and n represents the smoothing period (default: 63 days).
#### 3.2.3 Weighted Aggregation
The composite index combines normalized components using theoretically motivated weights:
SCMPI_t = w_1×Z_spread,t + w_2×Z_unemployment,t + w_3×Z_consumer,t + w_4×Z_debt,t
Default weights reflect the relative importance of each component based on empirical literature: credit spreads (35%), unemployment (25%), consumer credit (25%), and household debt (15%).
### 3.3 Dynamic Threshold Mechanism
Unlike static threshold approaches, the SCMPI employs adaptive Bollinger Band-style thresholds that automatically adjust to changing market volatility and conditions (Bollinger, 2001):
Expansion Threshold = μ_SCMPI - k × σ_SCMPI
Stress Threshold = μ_SCMPI + k × σ_SCMPI
Neutral Line = μ_SCMPI
Where μ_SCMPI and σ_SCMPI represent the rolling mean and standard deviation of the composite index calculated over a configurable period (default: 126 days), and k is the threshold multiplier (default: 1.0). This approach ensures that thresholds remain relevant across different market regimes and volatility environments, providing more robust regime classification than fixed thresholds.
### 3.4 Visualization and User Interface
The SCMPI incorporates advanced visualization capabilities designed for professional trading environments:
#### 3.4.1 Adaptive Theme System
The indicator features an intelligent dual-theme system that automatically optimizes colors and transparency levels for both dark and bright chart backgrounds. This ensures optimal readability across different trading platforms and user preferences.
#### 3.4.2 Customizable Visual Elements
Users can customize all visual aspects including:
- Color Schemes: Automatic theme adaptation with optional custom color overrides
- Line Styles: Configurable widths for main index, trend lines, and threshold boundaries
- Transparency Optimization: Automatic adjustment based on selected theme for optimal contrast
- Dynamic Zones: Color-coded regime areas with adaptive transparency
#### 3.4.3 Professional Data Table
A comprehensive 13-row data table provides real-time component analysis including:
- Composite index value and regime classification
- Individual component z-scores with color-coded stress indicators
- Trend direction and signal strength assessment
- Dynamic threshold status and volatility metrics
- Component weight distribution for transparency
## 4. Regime Classification
The SCMPI classifies credit market conditions into three distinct regimes:
### 4.1 Expansion Regime (SCMPI < Expansion Threshold)
Characterized by favorable credit conditions, low risk premiums, and accommodative lending standards. This regime typically corresponds to economic expansion phases with low default rates and increasing credit availability.
### 4.2 Neutral Regime (Expansion Threshold ≤ SCMPI ≤ Stress Threshold)
Represents balanced credit market conditions with moderate risk premiums and stable lending standards. This regime indicates neither significant stress nor excessive exuberance in credit markets.
### 4.3 Stress Regime (SCMPI > Stress Threshold)
Indicates elevated credit market stress with high risk premiums, tightening lending standards, and deteriorating borrower conditions. This regime often precedes or coincides with economic contractions and financial market volatility.
## 5. Technical Implementation and Features
### 5.1 Alert System
The SCMPI includes a comprehensive alert framework with seven distinct conditions:
- Regime Transitions: Expansion, Neutral, and Stress phase entries
- Extreme Conditions: Values exceeding ±2.0 standard deviations
- Trend Reversals: Directional changes in the underlying trend component
### 5.2 Performance Optimization
The indicator employs several optimization techniques:
- Efficient Calculations: Pre-computed statistical measures to minimize computational overhead
- Memory Management: Optimized variable declarations for real-time performance
- Error Handling: Robust data validation and fallback mechanisms for missing data
## 6. Empirical Validation
### 6.1 Historical Performance
Backtesting analysis demonstrates the SCMPI's ability to identify major credit stress episodes, including:
- The 2008 Financial Crisis
- The 2020 COVID-19 pandemic market disruption
- Various regional banking crises
- European sovereign debt crisis (2010-2012)
### 6.2 Leading Indicator Properties
The composite nature and dynamic threshold system of the SCMPI provides enhanced leading indicator properties, typically signaling regime changes 1-3 months before they become apparent in individual components or market indices. The adaptive threshold mechanism reduces false signals during high-volatility periods while maintaining sensitivity during regime transitions.
## 7. Applications and Limitations
### 7.1 Applications
- Risk Management: Portfolio managers can use SCMPI signals to adjust credit exposure and risk positioning
- Academic Research: Researchers can employ the index for credit cycle analysis and systemic risk studies
- Trading Systems: The comprehensive alert system enables automated trading strategy implementation
- Financial Education: The transparent methodology and visual design facilitate understanding of credit market dynamics
### 7.2 Limitations
- Data Dependency: The indicator relies on timely and accurate macroeconomic data from FRED sources
- Regime Persistence: Dynamic thresholds may exhibit brief lag during extremely rapid regime transitions
- Model Risk: Component weights and parameters require periodic recalibration based on evolving market structures
- Computational Requirements: Real-time calculations may require adequate processing power for optimal performance
## References
Adrian, T. & Brunnermeier, M.K. (2016). CoVaR. *American Economic Review*, 106(7), 1705-1741.
Bernanke, B. & Gertler, M. (1995). Inside the black box: the credit channel of monetary policy transmission. *Journal of Economic Perspectives*, 9(4), 27-48.
Bernanke, B., Gertler, M. & Gilchrist, S. (1999). The financial accelerator in a quantitative business cycle framework. *Handbook of Macroeconomics*, 1, 1341-1393.
Bisias, D., Flood, M., Lo, A.W. & Valavanis, S. (2012). A survey of systemic risk analytics. *Annual Review of Financial Economics*, 4(1), 255-296.
Bollinger, J. (2001). *Bollinger on Bollinger Bands*. McGraw-Hill Education.
Gilchrist, S. & Zakrajšek, E. (2012). Credit spreads and business cycle fluctuations. *American Economic Review*, 102(4), 1692-1720.
Illing, M. & Liu, Y. (2006). Measuring financial stress in a developed country: An application to Canada. *Journal of Financial Stability*, 2(3), 243-265.
Kaufman, G.G. & Scott, K.E. (2003). What is systemic risk, and do bank regulators retard or contribute to it? *The Independent Review*, 7(3), 371-391.
Kindleberger, C.P. (1978). *Manias, Panics and Crashes: A History of Financial Crises*. Basic Books.
Kiyotaki, N. & Moore, J. (1997). Credit cycles. *Journal of Political Economy*, 105(2), 211-248.
Mian, A. & Sufi, A. (2014). What explains the 2007–2009 drop in employment? *Econometrica*, 82(6), 2197-2223.
Minsky, H.P. (1986). *Stabilizing an Unstable Economy*. Yale University Press.
Mishkin, F.S. (1995). Symposium on the monetary transmission mechanism. *Journal of Economic Perspectives*, 9(4), 3-10.
Inside 4+ Candles Box (Entry + Target + SMA Stop Logic)🔍 What This Script Does
This indicator detects price compression areas using 4 or more consecutive inside candles, then draws a breakout box to visually highlight the range.
Once price closes above the box, a long entry marker is plotted, along with:
🎯 Target line at 1x box size above the breakout.
❌ Stop-loss at the box low or at a dynamic SMA-based level if the box is too large.
🧠 Why It’s Unique
This script combines inside bar compression, breakout logic, risk control, and visual clarity — all in one tool.
It also cancels the setup entirely if price closes below the box low before breakout, avoiding late or false entries.
⚙️ Customizable Settings
Minimum inside candles (default = 4)
SMA length (used as stop if box is large)
Box size % threshold to activate smart stop
Entry, Target, and Stop marker colors
📌 Notes
For long setups only (no short signals).
Use on any asset or timeframe (ideal on 4H/1D).
This is not financial advice. Use with proper risk management.
Backtest thoroughly before live use.
Built with ❤️ by using Pine Script v6.
🇸🇦 وصف مختصر باللغة العربية:
هذا المؤشر يكتشف مناطق تماسك السعر من خلال 4 شموع داخلية أو أكثر، ثم يرسم مربعًا يحدد منطقة الاختراق المحتملة.
عند الإغلاق أعلى المربع، يتم عرض إشارة دخول وسطر هدف بنسبة 100% من حجم المربع.
كما يتم احتساب وقف الخسارة تلقائيًا إما عند قاع المربع أو عند متوسط متحرك ذكي (SMA) إذا كان حجم المربع كبيرًا.
الميزة الإضافية: إذا تم كسر قاع المربع قبل الاختراق، يتم إلغاء الصفقة تلقائيًا لتجنب الدخول المتأخر.
🧪 للاستفادة التعليمية والتحليل فقط. لا يُعتبر توصية مالية.
Math by Thomas Swing RangeMath by Thomas Swing Range is a simple yet powerful tool designed to visually highlight key swing levels in the market based on a user-defined lookback period. It identifies the highest high, lowest low, and calculates the midpoint between them — creating a clear range for swing trading strategies.
These levels can help traders:
Spot potential support and resistance zones
Analyze price rejection near range boundaries
Frame mean-reversion or breakout setups
The indicator continuously updates and extends these lines into the future, making it easier to plan and manage trades with visual clarity.
🛠️ How to Use
Add to Chart:
Apply the indicator on any timeframe and asset (works best on higher timeframes like 1H, 4H, or Daily).
Configure Parameters:
Lookback Period: Number of candles used to detect the highest high and lowest low. Default is 20.
Extend Lines by N Bars: Number of future bars the levels should be projected to the right.
Interpret Lines:
🔴 Red Line: Swing High (Resistance)
🟢 Green Line: Swing Low (Support)
🔵 Blue Line: Midpoint (Mean level — useful for equilibrium-based strategies)
Trade Ideas:
Bounce trades from swing high/low zones.
Breakout confirmation if price closes strongly outside the range.
Reversion trades if price moves toward the midpoint after extreme moves.
Bear Market Probability Model# Bear Market Probability Model: A Multi-Factor Risk Assessment Framework
The Bear Market Probability Model represents a comprehensive quantitative framework for assessing systemic market risk through the integration of 13 distinct risk factors across four analytical categories: macroeconomic indicators, technical analysis factors, market sentiment measures, and market breadth metrics. This indicator synthesizes established financial research methodologies to provide real-time probabilistic assessments of impending bear market conditions, offering institutional-grade risk management capabilities to retail and professional traders alike.
## Theoretical Foundation
### Historical Context of Bear Market Prediction
Bear market prediction has been a central focus of financial research since the seminal work of Dow (1901) and the subsequent development of technical analysis theory. The challenge of predicting market downturns gained renewed academic attention following the market crashes of 1929, 1987, 2000, and 2008, leading to the development of sophisticated multi-factor models.
Fama and French (1989) demonstrated that certain financial variables possess predictive power for stock returns, particularly during market stress periods. Their three-factor model laid the groundwork for multi-dimensional risk assessment, which this indicator extends through the incorporation of real-time market microstructure data.
### Methodological Framework
The model employs a weighted composite scoring methodology based on the theoretical framework established by Campbell and Shiller (1998) for market valuation assessment, extended through the incorporation of high-frequency sentiment and technical indicators as proposed by Baker and Wurgler (2006) in their seminal work on investor sentiment.
The mathematical foundation follows the general form:
Bear Market Probability = Σ(Wi × Ci) / ΣWi × 100
Where:
- Wi = Category weight (i = 1,2,3,4)
- Ci = Normalized category score
- Categories: Macroeconomic, Technical, Sentiment, Breadth
## Component Analysis
### 1. Macroeconomic Risk Factors
#### Yield Curve Analysis
The inclusion of yield curve inversion as a primary predictor follows extensive research by Estrella and Mishkin (1998), who demonstrated that the term spread between 3-month and 10-year Treasury securities has historically preceded all major recessions since 1969. The model incorporates both the 2Y-10Y and 3M-10Y spreads to capture different aspects of monetary policy expectations.
Implementation:
- 2Y-10Y Spread: Captures market expectations of monetary policy trajectory
- 3M-10Y Spread: Traditional recession predictor with 12-18 month lead time
Scientific Basis: Harvey (1988) and subsequent research by Ang, Piazzesi, and Wei (2006) established the theoretical foundation linking yield curve inversions to economic contractions through the expectations hypothesis of the term structure.
#### Credit Risk Premium Assessment
High-yield credit spreads serve as a real-time gauge of systemic risk, following the methodology established by Gilchrist and Zakrajšek (2012) in their excess bond premium research. The model incorporates the ICE BofA High Yield Master II Option-Adjusted Spread as a proxy for credit market stress.
Threshold Calibration:
- Normal conditions: < 350 basis points
- Elevated risk: 350-500 basis points
- Severe stress: > 500 basis points
#### Currency and Commodity Stress Indicators
The US Dollar Index (DXY) momentum serves as a risk-off indicator, while the Gold-to-Oil ratio captures commodity market stress dynamics. This approach follows the methodology of Akram (2009) and Beckmann, Berger, and Czudaj (2015) in analyzing commodity-currency relationships during market stress.
### 2. Technical Analysis Factors
#### Multi-Timeframe Moving Average Analysis
The technical component incorporates the well-established moving average convergence methodology, drawing from the work of Brock, Lakonishok, and LeBaron (1992), who provided empirical evidence for the profitability of technical trading rules.
Implementation:
- Price relative to 50-day and 200-day simple moving averages
- Moving average convergence/divergence analysis
- Multi-timeframe MACD assessment (daily and weekly)
#### Momentum and Volatility Analysis
The model integrates Relative Strength Index (RSI) analysis following Wilder's (1978) original methodology, combined with maximum drawdown analysis based on the work of Magdon-Ismail and Atiya (2004) on optimal drawdown measurement.
### 3. Market Sentiment Factors
#### Volatility Index Analysis
The VIX component follows the established research of Whaley (2009) and subsequent work by Bekaert and Hoerova (2014) on VIX as a predictor of market stress. The model incorporates both absolute VIX levels and relative VIX spikes compared to the 20-day moving average.
Calibration:
- Low volatility: VIX < 20
- Elevated concern: VIX 20-25
- High fear: VIX > 25
- Panic conditions: VIX > 30
#### Put-Call Ratio Analysis
Options flow analysis through put-call ratios provides insight into sophisticated investor positioning, following the methodology established by Pan and Poteshman (2006) in their analysis of informed trading in options markets.
### 4. Market Breadth Factors
#### Advance-Decline Analysis
Market breadth assessment follows the classic work of Fosback (1976) and subsequent research by Brown and Cliff (2004) on market breadth as a predictor of future returns.
Components:
- Daily advance-decline ratio
- Advance-decline line momentum
- McClellan Oscillator (Ema19 - Ema39 of A-D difference)
#### New Highs-New Lows Analysis
The new highs-new lows ratio serves as a market leadership indicator, based on the research of Zweig (1986) and validated in academic literature by Zarowin (1990).
## Dynamic Threshold Methodology
The model incorporates adaptive thresholds based on rolling volatility and trend analysis, following the methodology established by Pagan and Sossounov (2003) for business cycle dating. This approach allows the model to adjust sensitivity based on prevailing market conditions.
Dynamic Threshold Calculation:
- Warning Level: Base threshold ± (Volatility × 1.0)
- Danger Level: Base threshold ± (Volatility × 1.5)
- Bounds: ±10-20 points from base threshold
## Professional Implementation
### Institutional Usage Patterns
Professional risk managers typically employ multi-factor bear market models in several contexts:
#### 1. Portfolio Risk Management
- Tactical Asset Allocation: Reducing equity exposure when probability exceeds 60-70%
- Hedging Strategies: Implementing protective puts or VIX calls when warning thresholds are breached
- Sector Rotation: Shifting from growth to defensive sectors during elevated risk periods
#### 2. Risk Budgeting
- Value-at-Risk Adjustment: Incorporating bear market probability into VaR calculations
- Stress Testing: Using probability levels to calibrate stress test scenarios
- Capital Requirements: Adjusting regulatory capital based on systemic risk assessment
#### 3. Client Communication
- Risk Reporting: Quantifying market risk for client presentations
- Investment Committee Decisions: Providing objective risk metrics for strategic decisions
- Performance Attribution: Explaining defensive positioning during market stress
### Implementation Framework
Professional traders typically implement such models through:
#### Signal Hierarchy:
1. Probability < 30%: Normal risk positioning
2. Probability 30-50%: Increased hedging, reduced leverage
3. Probability 50-70%: Defensive positioning, cash building
4. Probability > 70%: Maximum defensive posture, short exposure consideration
#### Risk Management Integration:
- Position Sizing: Inverse relationship between probability and position size
- Stop-Loss Adjustment: Tighter stops during elevated risk periods
- Correlation Monitoring: Increased attention to cross-asset correlations
## Strengths and Advantages
### 1. Comprehensive Coverage
The model's primary strength lies in its multi-dimensional approach, avoiding the single-factor bias that has historically plagued market timing models. By incorporating macroeconomic, technical, sentiment, and breadth factors, the model provides robust risk assessment across different market regimes.
### 2. Dynamic Adaptability
The adaptive threshold mechanism allows the model to adjust sensitivity based on prevailing volatility conditions, reducing false signals during low-volatility periods and maintaining sensitivity during high-volatility regimes.
### 3. Real-Time Processing
Unlike traditional academic models that rely on monthly or quarterly data, this indicator processes daily market data, providing timely risk assessment for active portfolio management.
### 4. Transparency and Interpretability
The component-based structure allows users to understand which factors are driving risk assessment, enabling informed decision-making about model signals.
### 5. Historical Validation
Each component has been validated in academic literature, providing theoretical foundation for the model's predictive power.
## Limitations and Weaknesses
### 1. Data Dependencies
The model's effectiveness depends heavily on the availability and quality of real-time economic data. Federal Reserve Economic Data (FRED) updates may have lags that could impact model responsiveness during rapidly evolving market conditions.
### 2. Regime Change Sensitivity
Like most quantitative models, the indicator may struggle during unprecedented market conditions or structural regime changes where historical relationships break down (Taleb, 2007).
### 3. False Signal Risk
Multi-factor models inherently face the challenge of balancing sensitivity with specificity. The model may generate false positive signals during normal market volatility periods.
### 4. Currency and Geographic Bias
The model focuses primarily on US market indicators, potentially limiting its effectiveness for global portfolio management or non-USD denominated assets.
### 5. Correlation Breakdown
During extreme market stress, correlations between risk factors may increase dramatically, reducing the model's diversification benefits (Forbes and Rigobon, 2002).
## References
Akram, Q. F. (2009). Commodity prices, interest rates and the dollar. Energy Economics, 31(6), 838-851.
Ang, A., Piazzesi, M., & Wei, M. (2006). What does the yield curve tell us about GDP growth? Journal of Econometrics, 131(1-2), 359-403.
Baker, M., & Wurgler, J. (2006). Investor sentiment and the cross‐section of stock returns. The Journal of Finance, 61(4), 1645-1680.
Baker, S. R., Bloom, N., & Davis, S. J. (2016). Measuring economic policy uncertainty. The Quarterly Journal of Economics, 131(4), 1593-1636.
Barber, B. M., & Odean, T. (2001). Boys will be boys: Gender, overconfidence, and common stock investment. The Quarterly Journal of Economics, 116(1), 261-292.
Beckmann, J., Berger, T., & Czudaj, R. (2015). Does gold act as a hedge or a safe haven for stocks? A smooth transition approach. Economic Modelling, 48, 16-24.
Bekaert, G., & Hoerova, M. (2014). The VIX, the variance premium and stock market volatility. Journal of Econometrics, 183(2), 181-192.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5), 1731-1764.
Brown, G. W., & Cliff, M. T. (2004). Investor sentiment and the near-term stock market. Journal of Empirical Finance, 11(1), 1-27.
Campbell, J. Y., & Shiller, R. J. (1998). Valuation ratios and the long-run stock market outlook. The Journal of Portfolio Management, 24(2), 11-26.
Dow, C. H. (1901). Scientific stock speculation. The Magazine of Wall Street.
Estrella, A., & Mishkin, F. S. (1998). Predicting US recessions: Financial variables as leading indicators. Review of Economics and Statistics, 80(1), 45-61.
Fama, E. F., & French, K. R. (1989). Business conditions and expected returns on stocks and bonds. Journal of Financial Economics, 25(1), 23-49.
Forbes, K. J., & Rigobon, R. (2002). No contagion, only interdependence: measuring stock market comovements. The Journal of Finance, 57(5), 2223-2261.
Fosback, N. G. (1976). Stock market logic: A sophisticated approach to profits on Wall Street. The Institute for Econometric Research.
Gilchrist, S., & Zakrajšek, E. (2012). Credit spreads and business cycle fluctuations. American Economic Review, 102(4), 1692-1720.
Harvey, C. R. (1988). The real term structure and consumption growth. Journal of Financial Economics, 22(2), 305-333.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. Econometrica, 47(2), 263-291.
Magdon-Ismail, M., & Atiya, A. F. (2004). Maximum drawdown. Risk, 17(10), 99-102.
Nickerson, R. S. (1998). Confirmation bias: A ubiquitous phenomenon in many guises. Review of General Psychology, 2(2), 175-220.
Pagan, A. R., & Sossounov, K. A. (2003). A simple framework for analysing bull and bear markets. Journal of Applied Econometrics, 18(1), 23-46.
Pan, J., & Poteshman, A. M. (2006). The information in option volume for future stock prices. The Review of Financial Studies, 19(3), 871-908.
Taleb, N. N. (2007). The black swan: The impact of the highly improbable. Random House.
Whaley, R. E. (2009). Understanding the VIX. The Journal of Portfolio Management, 35(3), 98-105.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.
Zarowin, P. (1990). Size, seasonality, and stock market overreaction. Journal of Financial and Quantitative Analysis, 25(1), 113-125.
Zweig, M. E. (1986). Winning on Wall Street. Warner Books.