First EMA Touch (Last N Bars)Okay, here's a description of the "First EMA Touch (Last N Bars)" TradingView indicator:
Indicator Name: First EMA Touch (Last N Bars)
Core Purpose:
This indicator is designed to visually highlight on the chart the exact moment when the price (specifically, the high/low range of a price bar) makes contact with a specified Exponential Moving Average (EMA) for the first time within a defined recent lookback period (e.g., the last 20 bars).
How it Works:
EMA Calculation: It first calculates a standard Exponential Moving Average (EMA) based on the user-defined EMA Length and EMA Source (e.g., close price). This EMA line is plotted on the chart, often serving as a dynamic level of potential support or resistance.
"Touch" Detection: For every price bar, the indicator checks if the bar's range (from its low to its high) overlaps with or crosses the calculated EMA value for that bar. If low <= EMA <= high, it's considered a "touch".
"First Touch" Logic: This is the key feature. The indicator looks back over a specified number of preceding bars (defined by the Lookback Period). If a "touch" occurs on the current bar, and no "touch" occurred on any of the bars within that preceding lookback window, then the current touch is marked as the "first touch".
Visual Signal: When a "first touch" condition is met, the indicator plots a distinct shape (by default, a small green triangle) below the corresponding price bar. This makes it easy to spot these specific events.
Key Components & Settings:
EMA Line: The calculated EMA itself is plotted (typically as an orange line) for visual reference.
First Touch Signal: A shape (e.g., green triangle) appears below bars meeting the "first touch" criteria.
EMA Length (Input): Determines the period used for the EMA calculation. Shorter lengths make the EMA more reactive to recent price changes; longer lengths make it smoother and slower.
Lookback Period (Input): Defines how many bars (including the current one) the indicator checks backwards to determine if the current touch is the first one. A lookback of 20 means it checks if there was a touch in the previous 19 bars before signalling the current one as the first.
EMA Source (Input): Specifies which price point (close, open, high, low, hl2, etc.) is used to calculate the EMA.
Interpretation & Potential Uses:
Identifying Re-tests: The signal highlights when price returns to test the EMA after having stayed away from it for the duration of the lookback period. This can be significant as the market re-evaluates the EMA level.
Potential Reversal/Continuation Points: A first touch might indicate:
A potential area where a trend might resume after a pullback (if price bounces off the EMA).
A potential area where a reversal might begin (if price strongly rejects the EMA).
A point of interest if price consolidates around the EMA after the first touch.
Filtering Noise: By focusing only on the first touch within a period, it can help filter out repeated touches that might occur during choppy or consolidating price action around the EMA.
Confluence: Traders might use this signal in conjunction with other forms of analysis (e.g., horizontal support/resistance, trendlines, candlestick patterns, other indicators) to strengthen trade setups.
Limitations:
Lagging: Like all moving averages, the EMA is a lagging indicator.
Not Predictive: The signal indicates a specific past event (the first touch) occurred; it doesn't guarantee a future price movement.
Parameter Dependent: The effectiveness and frequency of signals heavily depend on the chosen EMA Length and Lookback Period. These may need tuning for different assets and timeframes.
Requires Confirmation: It's generally recommended to use this indicator as part of a broader trading strategy and not rely solely on its signals for trade decisions.
In essence, the "First EMA Touch (Last N Bars)" indicator provides a specific, refined signal related to price interaction with a moving average, helping traders focus on potentially significant initial tests of the EMA after a period of separation.
Moving Averages
CRT with Trend FilterExplanation of Functionality
The CRT RED DOG with Trend Filter indicator is a tool used to identify buy and sell signals on a price chart. It filters signals based on the market trend to ensure higher accuracy.
Main Components of the Indicator
Moving Average (EMA) Settings
Users can set the moving average (EMA) length as desired, with a default value of 50 days.
This moving average is used to determine the market trend.
Determining Market Trend
Uptrend: Occurs when the closing price is above the moving average.
Downtrend: Occurs when the closing price is below the moving average.
Identifying Buy and Sell Signals
Buy Signal: Occurs when the current bar's low is lower than the previous bar's low, and the closing price is higher than the previous bar's close, during an uptrend.
Sell Signal: Occurs when the current bar's high is higher than the previous bar's high, and the closing price is lower than the previous bar's close, during a downtrend.
Displaying Signals on the Chart
Buy signals are displayed with a green arrow below the candlestick.
Sell signals are displayed with a red arrow above the candlestick.
Time frame Day >> 15M
Triangular Hull Moving Average [BigBeluga X PineIndicators]This strategy is based on the original Triangular Hull Moving Average (THMA) + Volatility indicator by BigBeluga. Full credit for the concept and design goes to BigBeluga.
The strategy blends smoothed trend-following logic using a Triangular Hull Moving Average with dynamic volatility overlays, providing actionable trade signals with responsive visual feedback. It's designed for traders who want a non-lagging trend filter while also monitoring market volatility in real time.
How the Strategy Works
1. Triangular Hull Moving Average (THMA) Core
At its core, the strategy uses a Triangular Hull Moving Average (THMA) — a variation of the traditional Hull Moving Average with triple-smoothing logic:
It combines multiple weighted moving averages (WMAs) to create a faster and smoother trend line.
This reduces lag without compromising trend accuracy.
The THMA reacts more responsively to price movements than classic MAs.
THMA Formula:
thma(_src, _length) =>
ta.wma(ta.wma(_src,_length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length)
This logic filters out short-term noise while still being sensitive to genuine trend shifts.
2. Volatility-Enhanced Candle Plotting
An optional volatility mode overlays the chart with custom candles that incorporate volatility bands:
Wicks expand and contract dynamically based on market volatility.
The volatility value is computed using a HMA of high-low range over a user-defined length.
The candle bodies reflect THMA values, while the wicks reflect the current volatility spread.
This feature allows traders to visually gauge the strength of price moves and anticipate possible breakouts or slowdowns.
3. Trend Reversal Signal Detection
The strategy identifies trend reversals when the THMA line crosses over/under its own past value:
A bullish signal is triggered when THMA crosses above its value from two bars ago.
A bearish signal is triggered when THMA crosses below its value from two bars ago.
These shifts are marked on the chart with triangle-shaped signals for clear visibility.
This logic helps detect momentum shifts early and enables reactive trade entries.
Trade Entry & Exit Logic
Trade Modes Supported
Users can choose between:
Only Long – Enters long trades only.
Only Short – Enters short trades only.
Long & Short – Enables both directions.
Entry Conditions
Long Entry:
Triggered when a bullish crossover is detected.
Active only if the strategy mode allows long trades.
Short Entry:
Triggered when a bearish crossover is detected.
Active only if the strategy mode allows short trades.
Exit Conditions
In Only Long mode, the strategy closes long positions when a bearish signal appears.
In Only Short mode, the strategy closes short positions when a bullish signal appears.
In Long & Short mode, the strategy does not auto-close positions — instead, it opens new positions on each confirmed signal.
Dashboard Visualization
In the bottom-right corner of the chart, a live dashboard displays:
The current trend direction (🢁 for bullish, 🢃 for bearish).
The current volatility level as a percentage.
This helps traders quickly assess market status and adjust their decisions accordingly.
Customization Options
THMA Length: Adjust how smooth or reactive the trend detection should be.
Volatility Toggle & Length: Enable or disable volatility visualization and set sensitivity.
Color Settings: Choose colors for up/down trend visualization.
Trade Direction Mode: Limit the strategy to long, short, or both types of trades.
Use Cases & Strategy Strengths
1. Trend Following
Use the THMA-based candles and triangle signals to enter with momentum. The indicator adapts quickly, reducing lag and improving trade timing.
2. Volatility Monitoring
Visualize the strength of the trend with volatility wicks. Use expanding bands to confirm breakouts and contracting ones to detect weakening moves.
3. Signal Confirmation
Combine this tool with other indicators or use the trend shift triangles as confirmations for manual entries.
Conclusion
The THMA + Volatility Strategy is a non-repainting trend-following system that integrates:
Triangular Hull MA for advanced trend detection.
Real-time volatility visualization.
Clear entry signals based on trend reversals.
Configurable trade direction settings.
It is ideal for traders who:
Prefer smoothed price analysis.
Want to follow trends with precision.
Value visual volatility feedback for breakout detection.
Full credit for the original concept and indicator goes to BigBeluga.
MACD Crossover Breakout Rays with VWAP & Breakout ConfirmationOverview
This script is designed to highlight potential strong breakout moves by combining MACD crossovers, VWAP confirmation, and price action breakouts. It helps traders identify momentum shifts and filter high-probability trade setups.
How It Works
1. MACD Crossover Detection
- The script detects bullish crossovers (MACD line crossing above the signal line) and bearish crossovers (MACD line crossing below the signal line).
- A horizontal ray is drawn at the high (bullish) or low (bearish) of the crossover candle.
2. Multi-Timeframe MACD Confirmation
- A secondary MACD crossover is checked on a lower timeframe (default: 5 minutes) to confirm the strength of the move.
- The script ensures alignment between the primary and lower timeframe MACD crossovers before signaling a strong move.
3. VWAP Confirmation
- A bullish breakout is valid only if the price is above the VWAP.
- A bearish breakout is valid only if the price is below the VWAP.
4. Breakout Validation
- The script waits for price action confirmation—a breakout is only valid when a candle closes above (bullish) or below (bearish) the horizontal ray.
- Once confirmed, the ray color changes to blue to signal a strong move.
5. Label Alerts for Strong Moves
- When all conditions align, the script prints "STRONG 💪 MOVE" above or below the breakout candle.
- The previous label is automatically removed to keep the chart clean.
Customization Options
- MACD Settings: Adjust fast/slow lengths and signal smoothing.
- Lower Timeframe Confirmation: Choose a different timeframe for multi-timeframe MACD validation.
- VWAP Filtering: Ensure breakouts align with volume-weighted trends.
- Ray Length & Colors: Customize the horizontal ray length, width, and colors.
- Breakout Confirmation Window: Adjust how many bars to check for MACD alignment.
Best Use Cases
✅ Identifying high-probability breakouts with trend confirmation.
✅ Filtering out false signals by requiring multi-timeframe agreement.
✅ Helping traders stay in momentum-driven moves with strong confirmation.
⚠ Note: This script is for educational purposes only and does not constitute financial advice. Always conduct your own analysis before making trading decisions.
Litecoin Trailing-Stop StrategyAltcoins Trailing-Stop Strategy
This strategy is based on a momentum breakout approach using PKAMA (Powered Kaufman Adaptive Moving Average) as a trend filter, and a delayed trailing stop mechanism to manage risk effectively.
It has been designed and fine-tuned Altcoins, which historically shows consistent volatility patterns and clean trend structures, especially on intraday timeframes like 15m and 30m.
Strategy Logic:
Entry Conditions:
Long when PKAMA indicates an upward move
Short when PKAMA detects a downward trend
Minimum spacing of 30 bars between trades to avoid overtrading
Trailing Stop:
Activated only after a customizable delay (delayBars)
User can set trailing stop % and delay independently
Helps avoid premature exits due to short-term volatility
Customizable Parameters:
This strategy uses a custom implementation of PKAMA (Powered Kaufman Adaptive Moving Average), inspired by the work of alexgrover
PKAMA is a volatility-aware moving average that adjusts dynamically to market conditions, making it ideal for altcoins where trend strength and direction change frequently.
This script is for educational and experimental purposes only. It is not financial advice. Please test thoroughly before using it in live conditions, and always adapt parameters to your specific asset and time frame.
Feedback is welcome! Feel free to clone and adapt it for your own trading style.
EMA Bias + Persistent RSI Cross (2min Table)EMA + RSI CROSS per 2min Strat
IYKYK
Tells us when EMA + RSI align to provide higher confidence trades. A+ = Both EMA + RSI are aligning
Quick Analysis [ProjeAdam]OVERVIEW:
The Quick Analysis indicator is a multi-symbol technical screener that aggregates key indicator values—RSI, TSI, ADX, and Supertrend—for up to 30 different symbols. It displays the data on a customizable dashboard table overlaid on the chart, enabling traders to quickly compare market conditions across multiple assets.
ALGORITHM:
1. Initialization and Input Setup
The script sets the indicator’s title, short title, and overlay option.
It configures the dashboard table by allowing users to toggle its display, set its position (e.g., Bottom Right), and choose its size.
Input parameters for the technical indicators (RSI, TSI, ADX, Supertrend) are defined.
Up to 30 symbols are provided with toggle options so that users can select which ones to include in the analysis.
2. Technical Indicator Calculations
Custom functions are defined to smooth data for TSI (using double EMA smoothing) and to calculate ADX based on directional movements.
The main function, which runs on each symbol via request.security, computes:
RSI based on the close price.
TSI using the change in price and smoothing techniques.
ADX by comparing positive and negative directional movements.
Supertrend to signal market direction changes.
3. Data Aggregation and Matrix Formation
A matrix is created to store the aggregated values (price, RSI, TSI, ADX, Supertrend) for each symbol.
For each enabled symbol, a custom function retrieves the current indicator values and adds them as a row to the matrix.
4. Table Visualization and Dynamic Updates
A dashboard table is initialized with user-defined location and size settings.
The table headers include “SYMBOL”, “PRICE”, “RSI”, “TSI”, “ADX”, and “Supertrend”.
For every row in the matrix, the table is updated with the corresponding data:
The symbol code is extracted and displayed.
The current price and computed indicator values are shown.
Conditional formatting is applied (RSI and TSI cells change color based on threshold levels, Supertrend is marked with “Down 📛” or “Up 🚀”).
5. Real-Time Data Updates
The table refreshes on every new bar, ensuring that the displayed data remains current and reflects the latest market conditions across the selected symbols.
INDICATOR SUMMARY: RSI, TSI, ADX, and Supertrend
RSI (Relative Strength Index): Measures the speed and change of price movements, oscillating between 0 and 100. Typically, values above 70 indicate overbought conditions, while values below 35 indicate oversold conditions.
TSI (True Strength Index): Uses double EMA smoothing to measure price momentum and helps identify trend strength and potential reversal points.
ADX (Average Directional Index): Measures the strength of a trend, regardless of its direction. Higher values suggest a strong trend, while lower values indicate a weak trend.
Supertrend: A trend-following indicator based on the Average True Range (ATR) that identifies the market direction and potential support/resistance levels. It typically displays visual signals such as “Up 🚀” or “Down 📛.”
HOW DOES THE INDICATOR WORK?
Data Gathering: Uses TradingView’s security function to request real-time data for multiple symbols simultaneously.
Indicator Computation: For each symbol, the script calculates RSI, TSI, ADX, and Supertrend using a blend of built-in Pine Script functions and custom smoothing algorithms.
Visualization: A dynamically updated table displays the results with conditional colors and symbols for immediate visual cues on market trends and potential trade signals.
SETTINGS PANEL
Dashboard Configuration: Options to toggle the Trend Table, select its position, and determine the table size.
Indicator Parameters: Customizable settings for RSI (length, overbought/oversold levels), TSI (smoothing lengths and thresholds), ADX (smoothing and DI length), and Supertrend (ATR length and factor).
Symbol Management: Enable/disable switches for each of the 30 symbols along with symbol input fields, allowing users to choose which assets to analyze.
BENEFITS OF THE QUICK ANALYSIS INDICATOR
Comprehensive Market Overview:
Aggregates key technical metrics for multiple symbols on a single chart.
Customizability and Flexibility:
Fully configurable dashboard and indicator settings allow tailoring to various trading strategies.
Time Efficiency:
Automates the process of monitoring multiple assets, saving traders time and effort.
Visual Clarity:
Conditional color coding and clear table formatting provide immediate insights into market conditions.
Enhanced Multi-Market Analysis:
The ability to toggle and compare up to 30 different symbols supports diversified market evaluation.
CUSTOMIZATION
Users can modify indicator periods, thresholds, and table aesthetics through the input panel.
The symbol selection mechanism enables dynamic analysis across various markets, facilitating comparative insights and strategic decision-making.
CONCLUSION
The Quick Analysis indicator serves as a powerful, multi-symbol screener for traders by consolidating crucial technical indicators into a single, easy-to-read dashboard. Its dynamic updates, extensive customization options, and clear visual representation make it an essential tool for real-time market analysis.
If you have any ideas to further enhance this tool—whether by integrating additional sources, refining calculations, or adding new features—please feel free to suggest them in DM.
MA Distance (% and ATR) + Threshold CountMA Distance (% & ATR) + Threshold Count
This script visualizes how far price is extended from key moving averages using both percentage and ATR-based distance. It includes a dynamic threshold system that tracks how unusually extended price is, based on historical volatility.
🔍 Features:
Calculates distance from:
10 EMA, 20 SMA, 50 SMA, 100 SMA, 200 SMA
Measures both:
% distance from each MA
ATR-multiple distance from each MA
Automatically calculates dynamic upper/lower thresholds using a rolling standard deviation
Plots a colored dot when distance exceeds these thresholds
Dots appear above or below the bar depending on direction
Color-coded summary table displays:
% distance
ATR distance
Threshold extremes
Total number of threshold hits
🎯 Customization:
Toggle which MAs to display in the table
Set your own lookback window and threshold sensitivity (via stdev multiplier)
Show/hide dots based on how many thresholds are hit
Use this tool to identify when price is overextended from its moving averages and approaching historically significant levels of deviation. Great for spotting mean reversion setups, parabolic runs, or deep pullbacks.
DAMA OSC - Directional Adaptive MA OscillatorOverview:
The DAMA OSC (Directional Adaptive MA Oscillator) is a highly customizable and versatile oscillator that analyzes the delta between two moving averages of your choice. It detects trend progression, regressions, rebound signals, MA cross and critical zone crossovers to provide highly contextual trading information.
Designed for trend-following, reversal timing, and volatility filtering, DAMA OSC adapts to market conditions and highlights actionable signals in real-time.
Features:
Support for 11 custom moving average types (EMA, DEMA, TEMA, ALMA, KAMA, etc.)
Customizable fast & slow MA periods and types
Histogram based on percentage delta between fast and slow MA
Trend direction coloring with “Green”, “Blue”, and “Red” zones
Rebound detection using close or shadow logic
Configurable thresholds: Overbought, Oversold, Underbought, Undersold
Optional filters: rebound validation by candle color or flat-zone filter
Full visual overlay: MA lines, crossover markers, rebound icons
Complete alert system with 16 preconfigured conditions
How It Works:
Histogram Logic:
The histogram measures the percentage difference between the fast and slow MA:
hist_value = ((FastMA - SlowMA) / SlowMA) * 100
Trend State Logic (Green / Blue / Red):
Green_Up = Bullish acceleration
Blue_Up (or Red_Up, depending the display settings) = Bullish deceleration
Blue_Down (or Green_Down, depending the display settings) = Bearish deceleration
Red_Down = Bearish acceleration
Rebound Logic:
A rebound is detected when price:
Crosses back over a selected MA (fast or slow)
After being away for X candles (rebound_backstep)
Optional: filtered by histogram zones or candle color
Inputs:
Display Options:
Show/hide MA lines
Show/hide MA crosses
Show/hide price rebounds
Enable/disable blue deceleration zones
DAMA Settings:
Fast/Slow MA type and length
Source input (close by default)
Overbought/Oversold levels
Underbought/Undersold levels
Rebound Settings:
Use Close and/or Shadow
Rebound MA (Fast/Slow)
Candle color validation
Flat zone filter rebounds (between UnderSold and UnderBought)
Available MA type:
SMA (Simple MA)
EMA (Exponential MA)
DEMA (Double EMA)
TEMA (Triple EMA)
WMA (Weighted MA)
HMA (Hull MA)
VWMA (Volume Weighted MA)
Kijun (Ichimoku Baseline)
ALMA (Arnaud Legoux MA)
KAMA (Kaufman Adaptive MA)
HULLMOD (Modified Hull MA, Same as HMA, tweaked for Pine v6 constraints)
Notes:
**DEMA/TEMA** reduce lag compared to EMA, useful for faster reaction in trending markets.
**KAMA/ALMA** are better suited to noisy or volatile environments (e.g., BTC).
**VWMA** reacts strongly to volume spikes.
**HMA/HULLMOD** are great for visual clarity in fast moves.
Alerts Included (Fully Configurable):
Golden Cross:
Fast MA crosses above Slow MA
Death Cross:
Fast MA crosses below Slow MA
Bullish Rebound:
Rebound from below MA in uptrend
Bearish Rebound:
Rebound from above MA in downtrend
Bull Progression:
Transition into Green_Up with positive delta
Bear Progression:
Transition into Red_Down with negative delta
Bull Regression:
Exit from Red_Down into Blue/Green with negative delta
Bear Regression:
Exit from Green_Up into Blue/Red with positive delta
Crossover Overbought:
Histogram crosses above Overbought
Crossunder Overbought:
Histogram crosses below Overbought
Crossover Oversold:
Histogram crosses above Oversold
Crossunder Oversold:
Histogram crosses below Oversold
Crossover Underbought:
Histogram crosses above Underbought
Crossunder Underbought:
Histogram crosses below Underbought
Crossover Undersold:
Histogram crosses above Undersold
Crossunder Undersold:
Histogram crosses below Undersold
Credits:
Created by Eff_Hash. This code is shared with the TradingView community and full free. do not hesitate to share your best settings and usage.
Trend Strength MeterThe Trend Strength Meter (TSM) is a powerful and versatile indicator designed to help traders identify market trends, measure their strength, and detect potential reversals with ease. This indicator combines the power of moving averages, divergence detection, and a clean, customizable dashboard to provide actionable insights for traders of all levels.
How It Works
Trend Strength Calculation:
1. The TSM calculates the trend strength using the difference between two Exponential Moving Averages (EMAs): a fast EMA (default: 20) and a slow EMA (default: 50).
2. The difference is expressed as a percentage of the slow EMA, providing a clear measure of the trend's strength and direction.
Histogram Visualization:
1. A color-coded histogram visually represents the trend strength:
Green: Bullish trend
Red: Bearish trend
Gray: Neutral or no significant trend
2. A smoothed trend strength line (SMA of the trend strength) is also plotted for better clarity.
Divergence Detection:
1. The indicator detects bullish and bearish divergences using the RSI (Relative Strength Index) and price action.
2. Bullish Divergence: Price makes a lower low, but RSI makes a higher low, signaling potential upward momentum.
3. Bearish Divergence: Price makes a higher high, but RSI makes a lower high, signaling potential downward momentum.
=> Divergences are marked with arrows on the chart:
Green Arrow: Bullish divergence
Red Arrow: Bearish divergence
Dashboard:
1. A clean and informative dashboard displays key information:
Trend Strength Value: The current strength of the trend
Trend Direction: Bullish, Bearish, or Neutral
Last Signal: Buy, Sell, or None (based on divergence signals)
The dashboard is fully customizable and can be positioned anywhere on the chart (e.g., top-right, bottom-left, center, etc.).
Key Features
1. Trend Strength Measurement: Quickly identify the strength and direction of the trend.
2. Divergence Detection: Spot potential reversals before they occur with bullish and bearish divergence signals.
3. Customizable Dashboard: Move the dashboard to your preferred location on the chart for better visibility.
4. User-Friendly Design: Clean visuals and intuitive color coding make it easy to interpret market conditions.
5. Actionable Signals: Provides clear Buy/Sell signals based on divergence, helping traders make informed decisions.
How to Use
1. Trend Confirmation:
Use the histogram and trend strength value to confirm the current market trend.
Green bars indicate a bullish trend, while red bars indicate a bearish trend.
2. Divergence Signals:
Look for divergence arrows (green for bullish, red for bearish) to anticipate potential reversals.
Combine divergence signals with other technical analysis tools for higher accuracy.
3. Dashboard Insights:
Monitor the dashboard for real-time updates on trend strength, direction, and the latest signal.
Use the "Last Signal" (Buy/Sell) to validate your trading decisions.
4. Custom Settings:
Adjust the EMA lengths and divergence lookback period to suit your trading style and timeframe.
Position the dashboard anywhere on the chart for convenience.
Best Practices
1. Use the TSM in conjunction with other indicators or price action analysis for confirmation.
2. Test the indicator on different timeframes to find the one that works best for your strategy.
3. Always practice proper risk management when trading.
Disclaimer
This indicator is a tool to assist in technical analysis and should not be used as a standalone trading strategy. Past performance is not indicative of future results. Always conduct your own research and consult with a financial advisor before making trading decisions.
Adv EMA Cloud v6 (ADX, Alerts)Summary:
This indicator provides a multi-faceted view of market trends using Exponential Moving Averages (EMAs) arranged in visually intuitive clouds, enhanced with an optional ADX-based range filter and configurable alerts for key market conditions. It aims to help traders quickly gauge trend alignment across short, medium, and long timeframes while filtering signals during potentially choppy market conditions.
Key Features:
Multiple EMAs: Displays 10-period (Fast), 20-period (Mid), and 50-period (Slow) EMAs.
Long-Term Trend Filter: Includes a 200-period EMA to provide context for the overall dominant trend direction.
Dual EMA Clouds:
Fast/Mid Cloud (10/20 EMA): Fills the area between the 10 and 20 EMAs. Defaults to Green when 10 > 20 (bullish short-term momentum) and Red when 10 < 20 (bearish short-term momentum).
Mid/Slow Cloud (20/50 EMA): Fills the area between the 20 and 50 EMAs. Defaults to Aqua when 20 > 50 (bullish mid-term trend) and Fuchsia when 20 < 50 (bearish mid-term trend).
Optional ADX Range Filter: Uses the Average Directional Index (ADX) to identify potentially non-trending or choppy markets. When enabled and ADX falls below a user-defined threshold, the EMA clouds will turn grey, visually warning that trend-following signals may be less reliable.
Configurable Alerts: Provides several built-in alert conditions using Pine Script's alertcondition function:
Confluence Condition: Triggers when a 10/20 EMA crossover occurs while both EMA clouds show alignment (both bullish/green/aqua or both bearish/red/fuchsia) and price respects the 200 EMA filter and the ADX filter indicates a trend (if filters are enabled).
MA Filter Cross: Triggers when price crosses above or below the 200 EMA filter line.
Full Alignment Start: Triggers on the first bar where full bullish or bearish alignment occurs (both clouds aligned + MA filter respected + ADX trending, if filters are enabled).
How It Works:
EMA Calculation: Standard Exponential Moving Averages are calculated for the 10, 20, 50, and 200 periods based on the closing price.
Cloud Creation: The fill() function visually shades the area between the 10 & 20 EMAs and the 20 & 50 EMAs.
Cloud Coloring: The color of each cloud is determined by the relationship between the two EMAs that define it (e.g., if EMA 10 is above EMA 20, the first cloud is bullish-colored).
ADX Filter Logic: The script calculates the ADX value. If the "Use ADX Trend Filter?" input is checked and the calculated ADX is below the specified "ADX Trend Threshold", the script considers the market potentially ranging.
ADX Visual Effect: During detected ranging periods (if the ADX filter is active), the plotCloud12Color and plotCloud23Color variables are assigned a neutral grey color instead of their normal bullish/bearish colors before being passed to the fill() function.
Alert Logic: Boolean variables track the specific conditions (crossovers, cloud alignment, filter positions, ADX state). The alertcondition() function creates triggerable alerts based on these pre-defined conditions.
Potential Interpretation (Not Financial Advice):
Trend Alignment: When both clouds share the same directional color (e.g., both bullish - Green & Aqua) and price is on the corresponding side of the 200 EMA filter, it may suggest a stronger, more aligned trend. Conversely, conflicting cloud colors may indicate indecision or transition.
Dynamic Support/Resistance: The EMA lines themselves (especially the 20, 50, and 200) can sometimes act as dynamic levels where price might react.
Range Warning: Greyed-out clouds (when ADX filter is enabled) serve as a visual warning that trend-based strategies might face increased difficulty or whipsaws.
Confluence Alerts: The specific confluence alerts signal moments where multiple conditions align (crossover + cloud agreement + filters), which some traders might view as higher-probability setups.
Customization:
All EMA lengths (10, 20, 50, 200) are adjustable via the Inputs menu.
The ADX length and threshold are configurable.
The MA Trend Filter and ADX Trend Filter can be independently enabled or disabled.
Disclaimer:
This indicator is provided for informational and educational purposes only. Trading financial markets involves significant risk. Past performance is not indicative of future results. Always conduct your own thorough analysis and consider your risk tolerance before making any trading decisions. This indicator should be used in conjunction with other analysis methods and tools. Do not trade based solely on the signals or visuals provided by this indicator.
PARKER Currency Strength with RESETS v 3.00PARKER Currency Strength v3.00 is a comprehensive multi-currency strength indicator designed for Forex traders who want detailed insights into major currency performance. Here are some of its key features:
Customizable Session Resets:
The indicator supports automatic resets of currency strength calculations at the start of each major market session (Sydney, Tokyo, London, and New York). You can also enable a custom reset with a user-defined reset time and name.
User-Defined Market Hours:
With the new "Market Settings" section, you can set the open and close times for each market (Sydney, Tokyo, London, and New York) using hour and minute inputs. This allows you to tailor the session times to your local time zone or trading preferences.
Session Shading and Labels:
The background color of the indicator pane changes based on the active market session. Labels are generated at the start of each session to provide clear visual cues. Market session labels and times are also displayed on the chart for quick reference.
Dual Mode Display:
In addition to the reset-based currency strength calculations, the indicator can plot "normal" (continuous) currency strength lines at 50% transparency, allowing you to compare different calculation methods side by side.
Fully Customizable Appearance:
Customize line colors, widths, and offsets for each currency pair via user inputs, enabling a personalized and clear display that fits your trading style.
This indicator is ideal for Forex traders who require a dynamic and highly customizable tool to monitor currency strength, adapt to different market sessions, and make informed trading decisions based on real-time performance data.
Ichimoku Cloud Auto TF🧠 Timeframe Breakdown for Ichimoku Cloud Auto TF
Each timeframe in this indicator is carefully calibrated to reflect meaningful Ichimoku behavior relative to its scale. Here's how each one is structured and what it's best used for:
⏱️ 1 Minute (1m)
Tenkan / Kijun / Span B: 5 / 15 / 45
Use: Scalping fast price action.
Logic: Quick reaction to short-term momentum. Best for highly active traders or bots.
⏱️ 2 Minutes (2m)
Tenkan / Kijun / Span B: 6 / 18 / 54
Use: Slightly smoother than 1m, still ideal for scalping with a little more stability.
⏱️ 5 Minutes (5m)
Tenkan / Kijun / Span B: 8 / 24 / 72
Use: Intraday setups, quick trend capture.
Logic: Balanced between reactivity and noise reduction.
⏱️ 15 Minutes (15m)
Tenkan / Kijun / Span B: 9 / 27 / 81
Use: Short-term swing and intraday entries with higher reliability.
⏱️ 30 Minutes (30m)
Tenkan / Kijun / Span B: 10 / 30 / 90
Use: Intra-swing entries or confirmation of 5m/15m signals.
🕐 1 Hour (1H)
Tenkan / Kijun / Span B: 12 / 36 / 108
Use: Ideal for swing trading setups.
Logic: Anchored to Daily reference (1H × 24 ≈ 1D).
🕐 2 Hours (2H)
Tenkan / Kijun / Span B: 14 / 42 / 126
Use: High-precision swing setups with better context.
🕒 3 Hours (3H)
Tenkan / Kijun / Span B: 15 / 45 / 135
Use: Great compromise between short and mid-term vision.
🕓 4 Hours (4H)
Tenkan / Kijun / Span B: 18 / 52 / 156
Use: Position traders & intraday swing confirmation.
Logic: Designed to echo the structure of 1D Ichimoku but on smaller scale.
📅 1 Day (1D)
Tenkan / Kijun / Span B: 9 / 26 / 52
Use: Classic Ichimoku settings.
Logic: Standard used globally for technical analysis. Suitable for swing and position trading.
📆 1 Week (1W)
Tenkan / Kijun / Span B: 12 / 24 / 120
Use: Long-term position trading & institutional swing confirmation.
Logic: Expanded ratios for broader perspective and noise filtering.
🗓️ 1 Month (1M)
Tenkan / Kijun / Span B: 6 / 12 / 24
Use: Macro-level trend visualization and investment planning.
Logic: Condensed but stable structure to handle longer data cycles.
📌 Summary
This indicator adapts Ichimoku settings dynamically to your chart's timeframe, maintaining logical ratios between Tenkan, Kijun, and Span B. This ensures each timeframe remains responsive yet meaningful for its respective market context.
STH Unrealized Profit/Loss Ratio (STH-NUPL) | [DeV]STH-NUPL
The Short-Term Holder Net Unrealized Profit/Loss Ratio (STH-NUPL) is an analytical tool designed to approximate the unrealized profit or loss of Bitcoin’s short-term holders (STHs)—typically those holding coins for less than 155 days—within the constraints of TradingView’s price-based environment. Drawing inspiration from the canonical STH-NUPL metric, which assesses the difference between the market value and realized value of STH-held coins, this indicator adapts the concept into a normalized ratio using Bitcoin’s price data as a proxy. It offers a window into the sentiment and behavior of short-term market participants, who are often more sensitive to price fluctuations than long-term holders.
In its raw form, STH-NUPL oscillates around a break-even threshold of 0, where positive values indicate aggregate unrealized profits for STHs (market value exceeds realized value), and negative values suggest losses. This inflection point frequently acts as a key level: in bear markets, it can signal capitulation as STHs sell at break-even or below, while in bull markets, it may reflect reluctance to realize losses, providing support. The indicator enhances this metric with smoothing, a moving average overlay, and sophisticated visualization options, delivering a statistically informed perspective on short-term holder dynamics tailored for institutional-grade analysis.
STH-NUPL Settings -
Lookback Length (Default: 150 days): Defines the SMA period for estimating realized value. This 150-day window aligns with traditional STH definitions (e.g., <155 days), capturing a broad yet relevant historical cost basis for short-term holders, ideal for assessing cyclical behavior.
Smoothing Period (Default: 5 days): Applies an EMA to the raw STH-NUPL ratio, with a short default period to maintain responsiveness to recent price shifts while filtering out daily volatility. This setting is particularly suited for tactical analysis.
Moving Average Settings -
MA Lookback Length (Default: 90 days): Sets the period for the STH-NUPL’s moving average, offering a medium-term trend signal that contrasts with the 150-day lookback, enabling detection of momentum shifts within broader market phases.
MA Type (Default: EMA): Provides six moving average types, from the straightforward SMA to the volume-sensitive VWMA. The default EMA balances smoothness and reactivity, while options like HMA or VWMA cater to specialized needs, such as emphasizing recent action or volume trends.
Display Settings -
Show Moving Average (Default: True): Toggles the visibility of the STH-NUPL MA plot, allowing users to focus solely on the smoothed ratio when desired.
Show Background Colors (Default: True): Activates dynamic background shading to visually reinforce market regimes.
Background Color Source (Default: STH-NUPL): Enables users to tie the background to either the STH-NUPL’s midline (reflecting sthNupl > 0) or the MA’s trend direction (maNupl > maNupl ), aligning the visual context with the chosen analytical focus.
Analytical Applications -
Bear Market Capitulation: When the smoothed STH-NUPL approaches or falls below zero, it often signals loss realization among STHs, a precursor to capitulation in downtrends. A declining MA crossing zero can confirm this selling pressure.
Bull Market Support: Positive STH-NUPL values with a rising MA indicate STHs are in profit and reluctant to sell at a loss, forming support zones in uptrends as sell pressure wanes.
Sentiment Extremes: Significant deviations above or below zero highlight over-optimism or despair among STHs, offering contrarian opportunities when paired with price action or other on-chain metrics.
**Limitations**
As a TradingView-based approximation, this indicator uses price data (close) rather than true on-chain STH supply and realized price, which are available through providers like Glassnode. The 150-day SMA for realized value simplifies the cost basis, potentially underrepresenting the diversity of STH transactions. Despite this, the smoothed ratio and moving average overlay provide a practical proxy for tracking STH sentiment within TradingView’s ecosystem.
Multi-Timeframe EMAsMulti Timeframe EMA's
The 'Multi-Timeframe EMA Band Comparison' indicator is a tool designed to analyze trend direction across multiple timeframes using Exponential Moving Averages. it calculates the 50, 100, and 200 period EMAs for fiver user defined timeframes and compares their relationships to provide a visual snapshot of bullish or bearish momentum.
How it Works:
EMA Calculations: For each selected timeframe, the indicator computes the 50, 100, and 200 period EMAs based on the closing price.
Band Comparisons: Three key relationships are evaluated:
50 EMA vs 100 EMA
100 EMA vs 200 EMA
50 EMA vs 200 EMA
Scoring System: Each comparison is assigned a score:
🟢 (Green Circle): The shorter EMA is above the longer EMA, signaling bullish momentum.
🔴 (Red Circle): The shorter EMA is below the longer EMA, signaling bearish momentum.
⚪️ (White Circle): The EMAs are equal or data is unavailable (rare).
Average Score:
An overall average score is calculated across all 15 comparisons ranging from 1 to -1, displayed with two decimal places and color coded.
Customization:
This indicator is fully customizable from the timeframe setting to the color of the table. The only specific part that is not changeable is the EMA bands.
Scalping Strategy Signal v2 by [INFINITYTRADER]Overview
This Pine Script (v6) implements a scalping strategy that uses higher timeframe data (default: 4H) to generate entry and exit signals, originally designed for the 15-minute timeframe with an option for 30-minute charts. The "Scalping Strategy Signal v2 by " integrates moving averages, RSI, volume, ATR, and candlestick patterns to identify trading opportunities. It features adjustable risk management with ATR-based stop-loss, take-profit, and trailing stops, plus dynamic position sizing based on user-set capital. Trades trigger only on the higher timeframe candle close (e.g., 4H) to limit activity within the same period. This closed-source script offers a structured scalping approach, blending multiple entry methods and risk controls for adaptability across market conditions.
What Makes It Unique
Unlike typical scalping scripts relying on single-indicator triggers (e.g., RSI alone or basic MA crossovers), this strategy combines four distinct entry methods—standard MA crossovers, RSI-based momentum shifts, trend-following shorts, and candlestick pattern logic—evaluated on a 4H timeframe for confirmation. This multi-layered design, paired with re-entry logic after losses and a mix of manual, ATR-based, and trailing exits, aims to balance trade frequency and reliability. The higher timeframe filter adds precision not commonly found in simpler scalping tools, while the 30-minute option enhances consistency by reducing noise.
How It Works
Timeframe Logic
Runs on a base timeframe (designed for 15-minute charts, with a 30-minute option) while pulling data from a user-chosen higher timeframe (default: 4H) for signal accuracy.
Limits entries to the close of each 4H candle, ensuring one trade per period to avoid over-trading in volatile conditions.
Indicators and Data
Moving Averages : Employs 21-period and 50-period simple moving averages on the higher timeframe to detect trends and signal entries/exits.
Volume : Requires volume to exceed 70% of its 20-period average on the higher timeframe for momentum confirmation.
RSI : Uses a 14-period RSI for overbought/oversold filtering and a 6-period RSI for precise entry timing.
ATR : Applies a 14-period Average True Range on the higher timeframe to set adaptive stop-loss and take-profit levels.
Candlestick Patterns : Analyzes consecutive green or red 4H bars for trend continuation signals.
Why These Indicators
The blend of moving averages, RSI, volume, ATR, and candlestick patterns forms a robust scalping framework. Moving averages establish trend context, RSI filters momentum and avoids extremes, volume confirms market activity, ATR adjusts risk to volatility, and candlestick patterns enhance entry timing with price action insights. Together, they target small, frequent moves in flat or trending markets, with the 4H filter reducing false signals common in lower-timeframe scalping.
Entry Conditions
Four entry methods are evaluated at the 4H candle close:
Standard Long Entry: Price crosses above the 21-period moving average, volume exceeds 70% of its 20-period average, and the 1H 14-period RSI is below 70—confirms uptrend momentum.
Special Long Entry: The 6-period RSI crosses above 23, price is more than 1.5 times the ATR from the 21-period moving average, and price exceeds its prior close—targets oversold bounces with a stop-loss at the 4H candle’s low.
Short Entries:
- RSI-Based: The 6-period RSI crosses below 68 with volume support—catches overbought pullbacks.
- Trend-Based: Price crosses below the 21-period moving average, volume is above 70% of its average, and the 1H 14-period RSI is above 30—confirms downtrends.
Red/Green Bar Logic: Two consecutive green 4H bars for longs or red 4H bars for shorts—uses candlestick patterns for continuation, with a tight stop-loss from the base timeframe candle.
Re-Entry Logic
Long : After a losing special long, triggers when the 6-period RSI crosses 27 and price crosses the 21-period moving average.
Short : After a losing short, triggers when the 6-period RSI crosses 50 and price crosses below the 21-period moving average.
Purpose: Offers recovery opportunities with stricter conditions.
Exit Conditions
Manual Exits: Longs close if the 21-period MA crosses below the 50-period MA or the 1H 14-period RSI exceeds 68; shorts close if the 21-period MA crosses above the 50-period MA or RSI drops below 25.
ATR-Based TP/SL: Stop-loss is entry price ± ATR × 1.5 (default); take-profit is ± ATR × 4 (default), checked at 4H close.
Trailing Stop: Adjusts ±6x ATR from peak/trough, closing if price retraces within 1x ATR.
Special/Tight SL: Special longs exit if price opens below the 4H candle’s low; 4th method entries use the base timeframe candle’s low/high, checked every bar.
Position Sizing
Bases trade value on user-set capital (default: 100 USDT), dividing by the higher timeframe close price for dynamic sizing.
Visualization
Displays a table at the bottom-right with current/previous signals, TP/SL levels, equity, trading pair, and trade size—color-coded for clarity (green for buy, red for sell).
Inputs
Initial Capital (USDT): Sets trade value (default: 100, min: 1).
ATR Stop-Loss Multiplier: Adjusts SL distance (default: 1.5, min: 1).
ATR Take-Profit Multiplier: Adjusts TP distance (default: 4, min: 1).
Higher Timeframe: Selects analysis timeframe (options: 1m, 5m, 15m, 30m, 1H, 4H, D, W; default: 4H).
Usage Notes
Intended Timeframe: Designed for 15-minute charts with 4H confirmation for precision and frequency; 30-minute charts improve consistency by reducing noise.
Backtesting: Adjust ATR multipliers and capital to match your asset’s volatility and risk tolerance.
Risk Management: Combines manual, ATR, and trailing exits—monitor to avoid overexposure.
Limitations: 4H candle-close dependency may delay entries in fast markets; RSI/volume filters can reduce trades in low-momentum periods.
Backtest Observations
Tested on BTC/USDT (4H higher timeframe, default settings: Initial Capital: 100 USDT, ATR SL: 1.5x, ATR TP: 4x) across market conditions, comparing 15-minute and 30-minute charts:
Bull Market (Jul 2023 - Dec 2023):
15-Minute: 277 long, 219 short; Win Rate: 42.74%; P&L: 108%; Drawdown: 1.99%; Profit Factor: 3.074.
30-Minute: 257 long, 215 short; Win Rate: 49.58%; P&L: 116.85%; Drawdown: 2.34%; Profit Factor: 3.14.
Notes: Moving average crossovers and green bar patterns suited this bullish phase; 30-minute improved win rate and P&L by filtering weaker signals.
Bear Market (Jan 2022 - Jun 2022):
15-Minute: 262 long, 211 short; Win Rate: 44.4%; P&L: 239.80%; Drawdown: 3.74%; Profit Factor: 3.419.
30-Minute: 250 long, 200 short; Win Rate: 52.22%; P&L: 258.77%; Drawdown: 5.34%; Profit Factor: 3.461.
Notes: Red bar patterns and RSI shorts thrived in the downtrend; 30-minute cut choppy reversals for better consistency.
Flat Market (Jan 2021 - Jun 2021):
15-Minute: 280 long, 208 short; Win Rate: 51.84%; P&L: 340.33%; Drawdown: 9.59%; Profit Factor: 2.924.
30-Minute: 270 long, 209 short; Win Rate: 55.11%; P&L: 315.42%; Drawdown: 7.21%; Profit Factor: 2.598.
Notes: High trade frequency and P&L showed strength in ranges; 30-minute lowered drawdown for better risk control.
Results reflect historical performance on BTC/USDT with default settings—users should test on their assets and timeframes. Past performance does not guarantee future results and is shared only to illustrate the strategy’s behavior.
Why It Works Well in Flat Markets
A "flat market" lacks strong directional trends, with price oscillating around moving averages, as in Jan 2021 - Jun 2021 for BTC/USDT. This strategy excels here because its crossover-based entries trigger frequently in tight ranges. In trending markets, an exit might not be followed by a new entry without a pullback, but flat markets produce multiple crossovers, enabling more trades. ATR-based TP/SL and trailing stops capture these small swings, while RSI and volume filters ensure momentum, driving high P&L and win rates.
Technical Details
Built in Pine Script v6 for TradingView compatibility.
Prevents overlapping trades with long/short checks.
Handles edge cases like zero division and auto-detects the trading pair’s base currency (e.g., BTC from BTCUSDT).
This strategy suits scalpers seeking structured entries and risk management. Test on 15-minute or 30-minute charts to match your style and market conditions.
Spent Output Profit Ratio (SOPR) Z-Score | [DeV]SOPR Z-Score
The Spent Output Profit Ratio (SOPR) is an advanced on-chain metric designed to provide deep insights into Bitcoin market dynamics by measuring the ratio between the combined USD value of all Bitcoin outputs spent on a given day and their combined USD value at the time of creation (typically, their purchase price). As a member of the Realized Profit/Loss family of metrics, SOPR offers a window into aggregate seller behavior, effectively representing the USD amount received by sellers divided by the USD amount they originally paid. This indicator enhances this metric by normalizing it into a Z-Score, enabling a statistically robust analysis of market sentiment relative to historical trends, augmented by a suite of customizable features for precision and visualization.
SOPR Settings -
Lookback Length (Default: 150 days): Determines the historical window for calculating the Z-Score’s mean and standard deviation. A longer lookback captures broader market cycles, providing a stable baseline for identifying extreme deviations, which is particularly valuable for long-term strategic analysis.
Smoothing Period (Default: 100 days): Applies an EMA to the raw SOPR, balancing responsiveness to recent changes with noise reduction. This extended smoothing period ensures the indicator focuses on sustained shifts in seller behavior, ideal for institutional-grade trend analysis.
Moving Average Settings -
MA Lookback Length (Default: 90 days): Sets the period for the Z-Score’s moving average, offering a shorter-term trend signal relative to the 150-day Z-Score lookback. This contrast enhances the ability to detect momentum shifts within the broader context.
MA Type (Default: EMA): Provides six moving average types, from the simple SMA to the volume-weighted VWMA. The default EMA strikes an optimal balance between smoothness and responsiveness, while alternatives like HMA (Hull) or VWMA (volume-weighted) allow for specialized applications, such as emphasizing recent price action or incorporating volume dynamics.
Display Settings -
Show Moving Average (Default: True): Toggles the visibility of the Z-Score MA plot, enabling users to focus solely on the raw Z-Score when preferred.
Show Background Colors (Default: True): Activates dynamic background shading, enhancing visual interpretation of market regimes.
Background Color Source (Default: SOPR): Allows users to tie the background color to either the SOPR Z-Score’s midline (reflecting adjustedZScore > 0) or the MA’s trend direction (zScoreMA > zScoreMA ). This dual-source option provides flexibility to align the visual context with the primary analytical focus.
Analytical Applications -
Bear Market Resistance: When the Z-Score approaches or exceeds zero (raw SOPR near 1), it often signals resistance as sellers rush to exit at break-even, a pattern historically observed during downtrends. A rising Z-Score MA crossing zero can confirm this pressure.
Bull Market Support: Conversely, a Z-Score dropping below zero in uptrends indicates reluctance to sell at a loss, forming support as sell pressure diminishes. The MA’s bullish coloring reinforces confirmation of renewed buying interest.
Extreme Deviations: Values significantly above or below zero highlight overbought or oversold conditions, respectively, offering opportunities for contrarian positioning when paired with other on-chain or price-based metrics.
111D SMA / (350D SMA * 2)Indicator: Pi Cycle Ratio
This custom technical indicator calculates a ratio between two moving averages that are used for the PI Cycle Top indicator. The PI Cycle Top indicator triggers when the 111-day simple moving average (111D SMA) crosses up with the 350-day simple moving average (350D SMA *2).
The line value is ratio is calculated as:
Line Value = 111DSMA / (350D SMA × 2)
When the 111D SMA crosses with the 350D SMA triggering the PI Cycle Top, the value of the ratio between the two lines is 1.
This visualizes the ratio between the two moving averages into a single line. This indicator can be used for technical analysis for historical and future moves.
Combined SMA Cross & RSI Multi-Timeframe Indicator K2Combined SMA Cross & RSI Multi-Timeframe Indicator
This Pine Script v6 indicator combines two popular technical analysis tools—Simple Moving Average (SMA) crossover and Relative Strength Index (RSI) crossover—across multiple timeframes to generate bullish and bearish trading signals. It overlays SMA lines on the chart, displays signals with shapes, and provides a table summarizing SMA crossover states across 11 timeframes.
Features:
SMA Crossover:
Compares a short SMA (default: 20 periods) with a long SMA (default: 50 periods).
Bullish signal: Short SMA crosses above Long SMA.
Bearish signal: Short SMA crosses below Long SMA.
Plotted as green (short) and red (long) lines on the chart.
RSI Crossover:
Calculates RSI (default: 14 periods) and its SMA (default: 14 periods).
Bullish signal: RSI crosses above its SMA.
Bearish signal: RSI crosses below its SMA.
Multi-Timeframe Analysis:
Evaluates SMA and RSI conditions across 11 timeframes: 1M, 5M, 15M, 30M, 1H, 2H, 4H, 8H, 12H, 1D, 1W.
User can toggle which timeframes to include via input settings.
Combined Logic:
Generates a signal only when both SMA and RSI conditions (if enabled) are met across all selected timeframes.
Bullish: All selected timeframes show bullish SMA and RSI crossovers.
Bearish: All selected timeframes show bearish SMA and RSI crossovers.
Logic toggles allow enabling/disabling SMA or RSI components.
Visuals:
Triangles: Green triangle below bar for bullish signals, red triangle above bar for bearish signals.
Arrows: Green upward arrow for "Long" signals, red downward arrow for "Short" signals, ensuring no overlap with previous signals.
Table: Displays SMA crossover states for all 11 timeframes at the bottom center of the chart (green for bullish, red for bearish).
Alerts:
Triggers alerts for combined bullish ("SMA Cross and RSI timeframes are bullish!") and bearish ("SMA Cross and RSI timeframes are bearish!") signals.
Inputs:
SMA Settings: Short SMA length (20), Long SMA length (50).
RSI Settings: RSI length (14), RSI SMA length (14).
Logic Toggles: Enable/disable SMA Cross and RSI logic.
Timeframe Toggles: Enable/disable each of the 11 timeframes.
Usage:
Add the indicator to your chart and adjust inputs as needed.
Use the signals for trend confirmation or entry/exit points, combining multi-timeframe SMA and RSI analysis.
Monitor the table to assess alignment across timeframes.
Notes:
Designed for TradingView with Pine Script v6.
Signals are confirmed on closed bars (barstate.isconfirmed) to avoid repainting.
Ideal for traders seeking a multi-timeframe confirmation tool.
Этот индикатор Pine Script v6 объединяет два популярных инструмента технического анализа — кроссовер Simple Moving Average (SMA) и кроссовер Relative Strength Index (RSI) — на нескольких таймфреймах для генерации бычьих и медвежьих торговых сигналов. Он накладывает линии SMA на график, отображает сигналы с помощью фигур и предоставляет таблицу, обобщающую состояния пересечения SMA на 11 таймфреймах.
Функции:
Кроссовер SMA :
Сравнивает короткую SMA (по умолчанию: 20 периодов) с длинной SMA (по умолчанию: 50 периодов).
Бычий сигнал: короткая SMA пересекает длинную SMA сверху вниз.
Медвежий сигнал: короткая SMA пересекает длинную SMA снизу вверх.
На графике это обозначено зеленой (короткой) и красной (длинной) линиями.
Кроссовер RSI :
Рассчитывает RSI (по умолчанию: 14 периодов) и его SMA (по умолчанию: 14 периодов).
Бычий сигнал: RSI пересекает SMA выше.
Медвежий сигнал: RSI пересекает SMA ниже.
Анализ нескольких таймфреймов :
Оценивает состояния SMA и RSI на 11 таймфреймах: 1M, 5M, 15M, 30M, 1H, 2H, 4H, 8H, 12H, 1D, 1W.
Пользователь может переключать включаемые временные интервалы с помощью настроек ввода.
Комбинированная логика :
Генерирует сигнал только тогда, когда выполняются оба условия SMA и RSI (если они включены) на всех выбранных таймфреймах.
Бычий: все выбранные таймфреймы показывают бычьи пересечения SMA и RSI.
Медвежий: все выбранные таймфреймы показывают медвежьи пересечения SMA и RSI.
Логические переключатели позволяют включать/отключать компоненты SMA или RSI.
Визуальные эффекты :
Треугольники : зеленый треугольник под полосой — бычьи сигналы, красный треугольник над полосой — медвежьи сигналы.
Стрелки : зеленая стрелка вверх для «длинных» сигналов, красная стрелка вниз для «коротких» сигналов, что гарантирует отсутствие наложения с предыдущими сигналами.
Таблица : отображает состояния пересечения SMA для всех 11 таймфреймов в нижней центральной части графика (зеленый для бычьего тренда, красный для медвежьего).
Оповещения :
Запускает оповещения для комбинированных бычьих («Таймфреймы SMA Cross и RSI являются бычьими!») и медвежьих («Таймфреймы SMA Cross и RSI являются медвежьими!») сигналов.
Входные данные:
Настройки SMA : короткая длина SMA (20), длинная длина SMA (50).
Настройки RSI : длина RSI (14), длина RSI SMA (14).
Переключатели логики : включение/выключение логики SMA Cross и RSI.
Переключение таймфреймов : включение/отключение каждого из 11 таймфреймов.
Использование:
Добавьте индикатор на свой график и при необходимости скорректируйте входные данные.
Используйте сигналы для подтверждения тренда или точек входа/выхода, комбинируя многовременной анализ SMA и RSI.
Следите за таблицей, чтобы оценить согласованность по всем временным интервалам.
Примечания:
Разработано для TradingView с использованием Pine Script v6.
Сигналы подтверждаются на закрытых барах ( barstate.isconfirmed ), чтобы избежать перерисовки.
Идеально подходит для трейдеров, которым нужен инструмент подтверждения с несколькими таймфреймами.
HabibiTrades Pro System Strategy Overview
This strategy uses the following conditions:
WMA Crossover: To determine the direction of the market trend.
ADX: To confirm whether the trend is strong enough for trade.
Volume Spike: To validate the trade signal with increased market participation.
Let's break down each component and its role in the strategy.
1. WMA (Weighted Moving Average) Crossover:
The WMA is a type of moving average that gives more weight to recent prices. In this strategy, we use two WMAs:
Fast WMA (short period): Reacts quicker to price changes.
Slow WMA (long period): Reacts slower to price changes.
How it works:
Bullish Entry (Long): The Fast WMA crosses above the Slow WMA, indicating a potential upward price movement (bullish trend).
Bearish Entry (Short): The Fast WMA crosses below the Slow WMA, indicating a potential downward price movement (bearish trend).
2. ADX (Average Directional Index):
The ADX measures the strength of a trend, regardless of whether the trend is up or down.
How it works:
ADX > 20: Indicates a strong trend (either bullish or bearish). This is the threshold for considering a trade.
ADX > 30: Indicates an even stronger trend and is used to indicate high confidence in the trend direction.
3. Volume Spike:
Volume is an important indicator that tells you how much trading activity is happening in the market. A volume spike occurs when the current volume is significantly higher than the average volume over a specified period.
How it works:
Volume Spike Condition: The current volume is compared to the average volume (SMA). If the current volume is greater than the Volume SMA multiplied by the Volume Multiplier, a volume spike is detected.
Volume spikes are used to validate the strength of the trend and increase the likelihood that the trade signal is meaningful.
Strategy Logic
Long Entry Conditions (Buy Signal):
WMA Crossover: The Fast WMA crosses above the Slow WMA (bullish signal).
ADX: The ADX is above 20 (indicating a strong trend).
Volume Spike: The current volume is higher than the Volume SMA multiplied by the Volume Multiplier, confirming market participation.
Short Entry Conditions (Sell Signal):
WMA Crossover: The Fast WMA crosses below the Slow WMA (bearish signal).
ADX: The ADX is above 20 (indicating a strong trend).
Volume Spike: The current volume is higher than the Volume SMA multiplied by the Volume Multiplier, confirming market participation.
Exit Conditions:
Trailing Stop: A trailing stop is used based on the highest price for long trades or the lowest price for short trades since the entry. The position is exited when the price moves against the trade by a set amount (in ticks).
RSI Multi-Timeframe K2Indicator Name: RSI Multi-Timeframe Cross Indicator
Overview:
"RSI Multi-Timeframe Cross Indicator" is a versatile Pine Script (v5) tool developed for TradingView, designed for traders using multi-time frame analysis. It monitors the Relative Strength Index (RSI) cross its Simple Moving Average (SMA) on multiple time frames (1-minute, 5-minute, 15-minute, 30-minute, 1-hour, 4-hour and daily) to identify bullish and bearish conditions. The indicator overlays the signals on the chart and provides a customizable table to visualize the time frame conditions.
Key Features:
RSI Crossover Detection:
Monitors when the RSI crosses above (bullish trend) or below (bearish trend) its SMA on each selected time frame.
Uses constant state tracking to maintain a bullish/bearish state until an opposite crossover occurs.
Configurable Parameters:
RSI Length: Configurable period for calculating RSI (default: 14).
MA Length: Configurable period for SMA applied to RSI (default: 20).
Time Frame Controls:
Logical Switches: Independent switches ( use1m , use5m , etc.) to include/exclude each time frame in the signal logic.
Visualization Switches: Separate switches ( show1m , show5m , etc.) to show/hide each time frame in the table without affecting the logic.
Visuals:
Triangles: Green ascending triangles below the bars indicate bullish signals, red descending triangles above the bars indicate bearish signals.
Labels : Long (green) or Short (red) labels on the last confirmed bar when all enabled timeframes match.
Dynamic Table : A centered table at the bottom of the chart displaying the status of each timeframe with colored boxes (green for bullish, red for bearish). The table size is adjustable based on the visible timeframes.
Alerts :
Trigger alerts when all enabled timeframes are bullish ("All RSI timeframes are bullish (green)!") or bearish ("All RSI timeframes are bearish (red)!").
Input Parameters:
RSI Settings :
RSI Length : Integer (min: 1, default: 14) — Period for RSI calculation.
MA Length : Integer (min: 1, default: 20) — Period for SMA RSI.
Timeframe Logic Settings:
Use 1M in Logic, Use 5M in Logic, etc.: Boolean (default: true) - Enable/Disable each timeframe in signal calculation.
Timeframe Visualization Settings:
Show 1M in Table, Show 5M in Table, etc.: Boolean (default: true) - Show/Hide each timeframe in the table display.
Logic:
Bullish Condition: RSI crosses above SMA on a given timeframe, setting a bullish condition until a bearish crossover occurs.
Bearish Condition: RSI crosses below SMA on a given timeframe, setting a bearish condition until a bullish crossover occurs.
Combination signal: A Long or Short signal is generated only when all enabled timeframes (use the * switches) line up in the same direction (bullish or bearish).
Visualization: The table displays the status of each timeframe, but only shows the fields for the timeframes with the Show* switch enabled.
Visual output:
Chart signals:
A green ascending triangle and a Long label when all enabled timeframes are bullish.
A red downward-pointing triangle and a Short label when all enabled timeframes are bearish.
Table:
Located in the lower center of the chart.
The bars dynamically adjust to the number of visible timeframes (1 to 7).
Each cell displays the time frame name (e.g. "1M", "5M") with a background color indicating its status (green for bullish, red for bearish).
Use:
Trend Confirmation: Used to confirm trends across multiple time frames based on RSI behavior.
Configure: Customize RSI and MA lengths to suit your trading strategy, and turn time frames on/off for both logic and visualization to focus on the relevant periods.
Alerts: Set up alerts to be notified when all selected time frames match, useful for automated trading systems or manual monitoring.
Notes:
The indicator does not display RSI or SMA lines directly on the chart, focusing instead on crossover events and signals.
If all visualization toggles are disabled, the table disappears, but signals and alerts continue to function based on the logic toggles.
Compatible with any chart timeframe, data from later timeframes is retrieved using request.security() .
Stoch RSI Multi-Timeframe Cross Indicator
Stoch RSI Multi-Timeframe Cross Indicator
Overview
This Pine Script v6 indicator is designed to monitor Stochastic RSI crossovers across multiple timeframes (1-minute, 5-minute, 15-minute, 30-minute, 1-hour, 4-hour, and daily) and provide visual and alert-based signals for trading decisions. It overlays on the chart, displaying:
A table showing the bullish (green) or bearish (red) state of each timeframe.
Triangles and labels ("Long" or "Short") to indicate entry points when all enabled timeframes align in a bullish or bearish direction.
Alerts for when all enabled timeframes turn bullish or bearish.
The indicator tracks crossovers between the Stochastic RSI %K and %D lines, persisting the state (bullish or bearish) until the next crossover occurs, mimicking the behavior of the original RSI-based script but adapted for Stochastic RSI.
Inputs
RSI Length (rsiLength): Length of the RSI calculation (default: 14).
Stochastic Length (stochLength): Lookback period for the Stochastic RSI calculation (default: 14).
Smooth K (smoothK): Smoothing period for the %K line (default: 3).
Smooth D (smoothD): Smoothing period for the %D line (default: 3).
Use in Logic (use1m, use5m, etc.): Boolean toggles to include or exclude each timeframe (1M, 5M, 15M, 30M, 1H, 4H, 1D) in the entry signal logic (default: all true).
Timeframes
The indicator monitors the following timeframes, defined as strings compatible with Pine Script v6:
1-minute ("1")
5-minute ("5")
15-minute ("15")
30-minute ("30")
1-hour ("60")
4-hour ("240")
Daily ("D")
Core Logic
Stochastic RSI Calculation:
For each timeframe, the indicator:
Computes RSI using ta.rsi(close, rsiLength).
Applies the stochastic formula to RSI with ta.stoch(rsi, rsi, rsi, stochLength) to get the raw Stochastic RSI.
Smooths the result with ta.sma() to calculate %K (using smoothK) and %D (using smoothD).
This is done within a stochRsiState function, which is called via request.security() to ensure calculations align with each timeframe’s data.
Crossover Detection:
Detects crossovers using ta.crossover(k, d) (bullish) and ta.crossunder(k, d) (bearish).
Maintains a persistent state (var bool isBullish) for each timeframe, updated only when a crossover occurs:
true (bullish) when %K crosses above %D.
false (bearish) when %K crosses below %D.
Multi-Timeframe States:
Each timeframe’s %K, %D, and isBullish state is fetched independently using request.security(), ensuring accurate crossover detection regardless of the chart’s timeframe.
Visual Outputs
Table:
A static table in the bottom-left corner displays the state of each timeframe:
Columns: "1M", "5M", "15M", "30M", "1H", "4H", "1D".
Background color: Green (color.green) for bullish, Red (color.red) for bearish.
Updates on the last confirmed bar (barstate.islast).
Triangles:
Green upward triangle below the bar when all enabled timeframes are bullish (allBullish).
Red downward triangle above the bar when all enabled timeframes are bearish (allBearish).
Labels:
"Long" label (green) below the bar when allBullish is true.
"Short" label (red) below the bar when allBearish is true.
Displayed only on the last confirmed historical bar (barstate.islastconfirmedhistory).
Alerts
All Timeframes Bullish: Triggers when all enabled timeframes are bullish, with the message: "All Stoch RSI timeframes are bullish (green)!"
All Timeframes Bearish: Triggers when all enabled timeframes are bearish, with the message: "All Stoch RSI timeframes are bearish (red)!"
Conditions for Signals
Bullish Condition (allBullish):
True when all enabled timeframes (use1m ? isBullish1m : true, etc.) are bullish, and at least one timeframe is enabled.
Bearish Condition (allBearish):
True when all enabled timeframes are bearish, and at least one timeframe is enabled.
Disabled timeframes are treated as neutral (always true) in the logic, ensuring they don’t block signals.
Usage
Add the indicator to your TradingView chart.
Adjust input parameters (e.g., rsiLength, stochLength, smoothK, smoothD) to match your trading strategy.
Enable/disable timeframes via the input settings to focus on specific ones.
Watch the table for individual timeframe states and the chart for entry signals ("Long"/"Short") when all enabled timeframes align.
Set up alerts to be notified of full alignment.
Notes
The indicator is designed to persist the crossover state until the next crossover, similar to the original RSI-based script, ensuring stability across chart timeframe switches.
It uses request.security() to fetch data, making it robust for multi-timeframe analysis, though performance may depend on the chart’s data availability.
Stoch RSI Multi-Timeframe Cross Индикатор
Обзор
Этот индикатор Pine Script v6 предназначен для мониторинга пересечений Stochastic RSI на нескольких таймфреймах (1-минутный, 5-минутный, 15-минутный, 30-минутный, 1-часовой, 4-часовой и дневной) и предоставления визуальных и основанных на оповещениях сигналов для принятия торговых решений. Он накладывается на график, отображая:
Таблица, показывающая бычье (зеленый) или медвежье (красный) состояние каждого таймфрейма.
Треугольники и метки («Длинный» или «Короткий») для обозначения точек входа, когда все включенные таймфреймы совпадают в бычьем или медвежьем направлении.
Оповещения о том, когда все включенные таймфреймы становятся бычьими или медвежьими.
Индикатор отслеживает пересечения линий %K и %D стохастического RSI , сохраняя состояние (бычье или медвежье) до тех пор, пока не произойдет следующее пересечение, имитируя поведение исходного скрипта на основе RSI, но адаптированного для стохастического RSI.
Входы
Длина RSI ( rsiLength ): длина расчета RSI (по умолчанию: 14).
Длина стохастика ( stochLength ): период ретроспективного анализа для расчета стохастического RSI (по умолчанию: 14).
Сглаживание K ( smoothK ): период сглаживания для линии %K (по умолчанию: 3).
Smooth D ( smoothD ): период сглаживания для линии %D (по умолчанию: 3).
Использовать в логике ( use1m , use5m и т. д.): логические переключатели для включения или исключения каждого таймфрейма (1M, 5M, 15M, 30M, 1H, 4H, 1D) в логику входного сигнала (по умолчанию: все true).
Временные рамки
Индикатор отслеживает следующие таймфреймы, определенные как строки, совместимые с Pine Script v6:
1 минута ( "1" )
5-минутный ( "5" )
15-минутный ( "15" )
30-минутный ( "30" )
1 час ( "60" )
4-часовой ( "240" )
Ежедневно ( "Д" )
Основная логика
Расчет стохастического RSI :
Для каждого таймфрейма индикатор:
Вычисляет RSI с помощью ta.rsi(close, rsiLength) .
Применяет стохастическую формулу к RSI с ta.stoch(rsi, rsi, rsi, stochLength) для получения необработанного стохастического RSI.
Сглаживает результат с помощью ta.sma() для вычисления %K (используя smoothK ) и %D (используя smoothD ).
Это делается в функции stochRsiState , которая вызывается через request.security(), чтобы гарантировать соответствие расчетов данным каждого таймфрейма.
Обнаружение кроссовера :
Обнаруживает пересечения с помощью ta.crossover(k, d) (бычий) и ta.crossunder(k, d) (медвежий).
Поддерживает постоянное состояние ( var bool isBullish ) для каждого таймфрейма, обновляется только при возникновении пересечения:
истина (бычий тренд), когда %K пересекает %D снизу вверх .
ложно (медвежье), когда %K пересекает %D снизу .
Состояния с несколькими таймфреймами :
Состояние %K , %D и isBullish каждого таймфрейма извлекается независимо с помощью request.security() , что обеспечивает точное обнаружение пересечений независимо от таймфрейма графика.
Визуальные результаты
Стол :
Статическая таблица в нижнем левом углу отображает состояние каждого таймфрейма:
Столбцы: «1M», «5M», «15M», «30M», «1H», «4H», «1D».
Цвет фона: зеленый ( color.green ) для бычьего тренда, красный ( color.red ) для медвежьего тренда.
Обновления по последнему подтвержденному бару ( barstate.islast ).
Треугольники :
Зеленый восходящий треугольник под полосой, когда все включенные таймфреймы являются бычьими ( allBullish ).
Красный нисходящий треугольник над баром, когда все включенные таймфреймы медвежьи ( allBearish ).
Метки :
Метка «Длинная» (зеленая) под полосой, когда allBullish имеет значение true.
Метка «Короткая» (красная) под полосой, когда allBearish имеет значение true.
Отображается только на последнем подтвержденном историческом баре ( barstate.islastconfirmedhistory ).
Оповещения
Все таймфреймы бычьи : срабатывает, когда все включенные таймфреймы бычьи, с сообщением: «Все таймфреймы Stoch RSI бычьи (зеленые)!»
Все таймфреймы медвежьи : срабатывает, когда все включенные таймфреймы медвежьи, с сообщением: «Все таймфреймы Stoch RSI медвежьи (красные)!»
Условия для сигналов
Бычье состояние ( всеБычье ) :
Истинно, когда все включенные таймфреймы ( use1m ? isBullish1m : true и т. д.) являются бычьими и включен хотя бы один таймфрейм.
Медвежьи условия ( всемедвежьи ) :
Истинно, когда все включенные таймфреймы являются медвежьими и включен хотя бы один таймфрейм.
Отключенные таймфреймы рассматриваются в логике как нейтральные (всегда истинные ), что гарантирует, что они не блокируют сигналы.
Использование
Добавьте индикатор на свой график TradingView.
Отрегулируйте входные параметры (например, rsiLength , stochLength , smoothK , smoothD ) в соответствии с вашей торговой стратегией.
Включите/отключите таймфреймы с помощью настроек ввода, чтобы сосредоточиться на определенных из них.
Следите за таблицей для определения состояний отдельных таймфреймов и графиком для определения сигналов на вход («Длинный»/«Короткий»), когда все включенные таймфреймы совпадают.
Настройте оповещения, чтобы получать уведомления о полном выравнивании.
Примечания
Индикатор разработан таким образом, чтобы сохранять состояние пересечения до следующего пересечения, аналогично оригинальному скрипту на основе RSI, обеспечивая стабильность при переключении таймфреймов графика.
Для извлечения данных используется request.security() , что делает его надежным для многовременного анализа, хотя производительность может зависеть от доступности данных графика.
SMA Multi-Timeframe Trend Indicator (Enhanced)Here is the description of the "SMA Multi-Timeframe Trend Indicator (Enhanced)" in English, based on the latest version of the code:
Description of the Indicator: SMA Multi-Timeframe Trend Indicator (Enhanced)
Purpose:
The indicator is designed to identify trends based on the price crossing a Simple Moving Average (SMA) on the current timeframe, with additional confirmation of the trend direction across multiple timeframes. It assists traders in finding entry points (Long or Short), displaying signals only at the moment of the first crossing of the candle body through the SMA, avoiding repeated signals until the next opposite crossing.
Indicator Type: Overlay — displayed on top of the price chart.
Key Features:
Entry Signals:
Long (green triangle and "Long" label): Appears when the candle body fully crosses the SMA upward (the candle's low low becomes higher than the SMA) and it is the first crossing after a previous bearish signal or from the chart's start.
Short (red triangle and "Short" label): Appears when the candle body fully crosses the SMA downward (the candle's high high becomes lower than the SMA) and it is the first crossing after a previous bullish signal or from the chart's start.
Signals are shown only once until the next opposite crossing, preventing redundant notifications.
Multi-Timeframe Confirmation:
The indicator analyzes the trend state across 9 timeframes: 1M, 5M, 15M, 30M, 1H, 4H, 8H, 1D, 1W.
For each timeframe, it checks the price position relative to the SMA:
Bullish state (low > SMA) — green color.
Bearish state (high < SMA) — red color.
An entry signal is generated only if all enabled timeframes confirm the trend direction (all bullish for Long, all bearish for Short).
Visualization:
SMA Line: Displayed on the current timeframe chart (green color, RGB: 9, 247, 108, linewidth 1).
Triangles: Green below the candle for Long, red above the candle for Short.
Labels: "Long" (green) or "Short" (red) appear on the last confirmed candle below the chart.
Table: Positioned at the bottom center of the chart, containing 9 cells (one for each timeframe), showing the current state (green or red background).
Customizability:
SMA Length: Users can set the SMA period (default is 20).
Timeframe Selection: Each of the 9 timeframes can be enabled or disabled in the logic settings (default: only 1H enabled).
Alerts:
Two types of notifications are generated:
"Bullish Cross": When the price crosses above the SMA on all enabled timeframes.
"Bearish Cross": When the price crosses below the SMA on all enabled timeframes.
How the Indicator Works:
SMA Calculation:
A Simple Moving Average (SMA) is calculated on the current timeframe with the specified period.
The trend state is determined on each of the 9 timeframes based on the price's position relative to the SMA.
Signal Conditions:
For Long: The low of the current candle (low) crosses the SMA upward (ta.crossover(low, smaCurrent)), and all enabled timeframes show a bullish state.
For Short: The high of the current candle (high) crosses the SMA downward (ta.crossunder(high, smaCurrent)), and all enabled timeframes show a bearish state.
A signal triggers only if the previous signal was in the opposite direction or absent, controlled by the lastSignalWasBullish variable.
Display:
When conditions are met, a triangle and label of the corresponding direction appear on the chart.
The table updates on each candle, reflecting the current state of all timeframes.
Usage:
Timeframe: Suitable for any timeframe, but tested on 1H with all other timeframes disabled.
Default Settings:
smaLength = 20
Only 1H enabled (use1h = true), others disabled (false).
Recommendations:
For more frequent signals, reduce smaLength (e.g., to 10).
To filter noise, enable additional timeframes (e.g., 4H, 1D).
Use alerts for automatic entry point notifications.
Example of Operation:
Scenario on 1H:
The price on the previous bar was below the SMA (high < smaCurrent), and on the current bar, low > smaCurrent. If 1H is the only enabled timeframe, a green triangle and "Long" label appear immediately.
Then the price drops, and high < smaCurrent after crossing downward — a red triangle and "Short" label appear.
Signals do not repeat until the price crosses the SMA in the opposite direction.
Limitations:
If all timeframes are disabled, the indicator will not generate signals (at least one timeframe must be enabled).
On highly volatile markets or with a large smaLength, crossings may be infrequent.
The table always displays the state of all 9 timeframes, even if they are not used in the logic.
Описание индикатора: SMA Multi-Timeframe Trend Indicator (Enhanced)
Назначение:
Индикатор предназначен для определения трендов на основе пересечения цены с простой скользящей средней (SMA) на текущем таймфрейме с дополнительным подтверждением состояния тренда на нескольких таймфреймах. Он помогает трейдерам находить точки входа в позицию (Long или Short), отображая сигналы только в момент первого пересечения тела свечи через SMA, избегая повторных сигналов до следующего противоположного пересечения.
Тип индикатора: Наложение (Overlay) — отображается поверх графика цены.
Основные особенности:
Сигналы входа:
Long (зелёный треугольник и метка "Long"): Появляется, когда тело свечи полностью пересекает SMA вверх (минимум свечи low становится выше SMA) и это первое пересечение после предыдущего медвежьего сигнала или с начала графика.
Short (красный треугольник и метка "Short"): Появляется, когда тело свечи полностью пересекает SMA вниз (максимум свечи high становится ниже SMA) и это первое пересечение после предыдущего бычьего сигнала или с начала графика.
Сигналы отображаются только один раз до следующего противоположного пересечения, что предотвращает избыточные уведомления.
Мультитаймфреймовое подтверждение:
Индикатор анализирует состояние тренда на 9 таймфреймах: 1M, 5M, 15M, 30M, 1H, 4H, 8H, 1D, 1W.
Для каждого таймфрейма проверяется положение цены относительно SMA:
Бычье состояние (low > SMA) — зелёный цвет.
Медвежье состояние (high < SMA) — красный цвет.
Сигнал на вход появляется только если все включённые таймфреймы подтверждают направление тренда (все бычьи для Long, все медвежьи для Short).
Визуализация:
Линия SMA: Отображается на графике текущего таймфрейма (зелёный цвет, RGB: 9, 247, 108, толщина 1).
Треугольники: Зелёные под свечой для Long, красные над свечой для Short.
Метки: "Long" (зелёная) или "Short" (красная) появляются на последней подтверждённой свече внизу графика.
Таблица: Расположена по центру внизу графика, содержит 9 ячеек (по одной для каждого таймфрейма), показывающих текущее состояние (зелёный или красный фон).
Настраиваемость:
Длина SMA: Пользователь может задать период скользящей средней (по умолчанию 20).
Выбор таймфреймов: Каждый из 9 таймфреймов можно включить или выключить в настройках логики (по умолчанию включён только 1H).
Алерты:
Генерируются два типа уведомлений:
"Bullish Cross": Когда цена пересекает SMA вверх на всех включённых таймфреймах.
"Bearish Cross": Когда цена пересекает SMA вниз на всех включённых таймфреймах.
Как работает индикатор:
Расчёт SMA:
На текущем таймфрейме рассчитывается простая скользящая средняя (SMA) с заданным периодом.
На каждом из 9 таймфреймов определяется состояние тренда на основе положения цены относительно SMA.
Условия сигнала:
Для Long: Минимум текущей свечи (low) пересекает SMA вверх (ta.crossover(low, smaCurrent)), и все включённые таймфреймы показывают бычье состояние.
Для Short: Максимум текущей свечи (high) пересекает SMA вниз (ta.crossunder(high, smaCurrent)), и все включённые таймфреймы показывают медвежье состояние.
Сигнал срабатывает только если предыдущий сигнал был противоположным или отсутствовал, что контролируется переменной lastSignalWasBullish.
Отображение:
При выполнении условий на графике появляются треугольник и метка соответствующего направления.
Таблица обновляется на каждой свече, показывая текущее состояние всех таймфреймов.
Использование:
Таймфрейм: Подходит для любого таймфрейма, но протестирован на 1H с отключёнными остальными таймфреймами.
Настройки по умолчанию:
smaLength = 20
Только 1H включён (use1h = true), остальные выключены (false).
Рекомендации:
Для более частых сигналов уменьшите smaLength (например, до 10).
Для фильтрации шума включите дополнительные таймфреймы (например, 4H, 1D).
Используйте алерты для автоматического уведомления о точках входа.
Пример работы:
Сценарий на 1H:
Цена на предыдущем баре была ниже SMA (high < smaCurrent), а на текущем баре low > smaCurrent. Если 1H — единственный включённый таймфрейм, сразу появляется зелёный треугольник и метка "Long".
Затем цена падает, и high < smaCurrent после пересечения вниз — появляется красный треугольник и метка "Short".
Сигналы не повторяются, пока цена не пересечёт SMA в противоположном направлении.
Ограничения:
Если все таймфреймы отключены, индикатор не будет генерировать сигналы (требуется хотя бы один включённый таймфрейм).
На очень волатильных рынках или при большом значении smaLength пересечения могут быть редкими.
Таблица всегда показывает состояние всех 9 таймфреймов, даже если они не используются в логике.
Multi-MA Strategy Analyzer with BacktestMulti-MA Strategy Analyzer with Backtest
This TradingView Pine Script indicator is designed to analyze multiple moving averages (SMA or EMA) dynamically and identify the most profitable one based on historical performance.
Features
Dynamic MA Range:
Specify a minLength, maxLength, and step size.
Automatically calculates up to 20 MAs.
Custom MA Calculation:
Uses custom SMA and EMA implementations to support dynamic length values.
Buy/Sell Logic:
Buy when price crosses above a MA.
Sell when price crosses below.
Supports both long and short trades.
Performance Tracking:
Tracks PnL, number of trades, win rate, average profit, and drawdown.
Maintains individual stats for each MA.
Best MA Detection:
Automatically highlights the best-performing MA.
Optional showBestOnly toggle to focus only on the best line and its stats.
Visualization:
Up to 20 plot() calls (static) for MAs.
Green highlight for the best MA.
Color-coded result table and chart.
Table View
When showBestOnly = false, the table displays all MAs with stats.
When showBestOnly = true, the table displays only the best MA with a summary row.
Includes:
Best MA length
Total PnL
Number of trades
Win rate
Avg PnL per trade
Max Drawdown
Configuration
minLength (default: 10)
maxLength (default: 200)
step (default: 10)
useEMA: Toggle between EMA and SMA
showBestOnly: Focus on best-performing MA only
Notes
MA plotting is static, limited to 20 total.
Table supports highlighting and is optimized for performance.
Script is structured to run efficiently using arrays and simple int where required.
Potential Extensions
Add visual buy/sell arrows
Export stats to CSV
Strategy tester conversion
Custom date range filtering for backtesting
Author: Muhammad Wasim
Version: 1.0