OPEN-SOURCE SCRIPT
saodisengxiaoyu-lianghua-2.1

- This indicator is a modular, signal-building framework designed to generate long and short signals by combining a chosen leading indicator with selectable confirmation filters. It runs on Pine Script version 5, overlays directly on price, and is built to be highly configurable so traders can tailor the signal logic to their market, timeframe, and trading style. It includes a dashboard to visualize which conditions are active and whether they validate a signal, and it outputs clear buy/sell labels and alert conditions so you can automate or monitor trades with confidence.
Core Design
- Leading Indicator: You choose one primary signal generator from a broad list (for example, Range Filter, Supertrend, MACD, RSI, Ichimoku, and many others). This serves as the anchor of the system and determines when a preliminary long or short setup exists.
- Confirmation Filters: You can enable additional filters that validate the leading signal before it becomes actionable. Each “respect…” input toggles a filter on or off. These filters include popular tools like EMA, 2/3 EMA crosses, RQK (Nadaraya Watson), ADX/DMI, Bollinger-based oscillators, MACD variations, QQE, Hull, VWAP, Choppiness Index, Damiani Volatility, and more.
- Signal Expiry: To avoid waiting indefinitely for confirmations, the indicator counts how many consecutive bars the leading condition holds. If confirmations do not align within a defined number of bars, the setup expires. This controls latency and helps reduce late or stale entries.
- Alternating Signals: An optional mode enforces alternation (long must follow short and vice versa), helping avoid repeated entries in the same direction without a meaningful reset.
- Aggregation Logic: The final long/short conditions are formed by combining the leading condition with all selected confirmation filters through logical conjunction. Only if all enabled filters validate the signal (within expiry constraints) does the indicator consider it a confirmed long or short.
- Visualization and Alerts: The script plots buy/sell labels at signal points, provides alert conditions for automation, and displays a compact dashboard summarizing the leading indicator’s status and each confirmation’s pass/fail result using checkmarks.
Leading Indicator Options
- The indicator includes a very large menu of leading tools, each with its own logic to determine uptrend or downtrend impulses. Highlights include:
- Range Filter: Uses a dynamic centerline and bands computed via conditional EMA/SMA and range sizing to define directional movement. It can operate in a default mode or an alternative “DW” mode.
- Rational Quadratic Kernel (RQK): Applies a kernel smoothing model (Nadaraya Watson) to detect uptrends and downtrends with a focus on noise reduction.
- Supertrend, Half Trend, SSL Channel: Classic trend-following tools that derive direction from ATR-based bands or moving average channels.
- Ichimoku Cloud and SuperIchi: Multi-component systems validating trend via cloud position, conversion/base line relationships, projected cloud, and lagging span.
- TSI (True Strength Index), DPO (Detrended Price Oscillator), AO (Awesome Oscillator), MACD, STC (Schaff Trend Cycle), QQE Mod: Momentum and cycle tools that parse direction from crossovers, zero-line behavior, and momentum shifts.
- Donchian Trend Ribbon, Chandelier Exit: Trend and exit tools that can validate breakouts or sustained trend strength.
- ADX/DMI: Measures trend strength and directional movement via +DI/-DI relationships and minimum ADX thresholds.
- RSI and Stochastic: Use crossovers, level exits, or threshold filters to gate entries based on overbought/oversold dynamics or relative strength trends.
- Vortex, Chaikin Money Flow, VWAP, Bull Bear Power, ROC, Wolfpack Id, Hull Suite: A diverse set of directional, momentum, and volume-based indicators to suit different markets and styles.
- Trendline Breakout and Range Detector: Price-behavior filters that confirm signals during breakouts or within defined ranges.
Confirmation Filters
- Each filter is optional. When enabled, it must validate the leading condition for a signal to pass. Examples:
- EMA Filter: Requires price to be above a specified EMA for longs and below for shorts, filtering signals that contradict broader trend or baseline levels.
- 2 EMA Cross and 3 EMA Cross: Enforce moving average cross conditions (fast above slow for long, the reverse for short) or a three-line stacking logic for more stringent trend alignment.
- RQK, Supertrend, Half Trend, Donchian, QQE, Hull, MACD (crossover vs. zero-line), AO (zero line or AC momentum variants), SSL: Each adds its characteristic validation pattern.
- RSI family (MA cross, exits OB/OS zones, threshold levels) plus RSI MA direction and RSI/RSI MA limits: Multiple ways to constrain signals via relative strength behavior and trajectories.
- Choppiness Index and Damiani Volatility: Prevent entries during ranging conditions or insufficient volatility; choppiness thresholds and volatility states gate the trade.
- VWAP, Volume modes (above MA, simple up/down, delta), Chaikin Money Flow: Volume and flow conditions that ensure signals happen in supportive liquidity or accumulation/distribution contexts.
- ADX/DMI thresholds: Demand a minimum trend strength and directional DI alignment to reduce whipsaw trades.
- Trendline Breakout and Range Detector: Confirm that the price is breaking structure or remains within active range consistent with the leading setup.
- By combining several filters you can create strict, conservative entries or looser setups depending on your goals.
Range Filter Engine
- A core building block, the Range Filter uses conditional EMA and SMA functions to compute adaptive bands around a dynamic centerline. It supports two types:
- Type 1: The centerline updates when price exceeds the band thresholds; bands define acceptable drift ranges.
- Type 2: Uses quantized steps (via floor operations) relative to the previous centerline to handle larger moves in discrete increments.
- The engine offers smoothing for range values using a secondary EMA and can switch between raw and averaged outputs. Its hi/lo bands and centerline compose a corridor that defines directional movement and potential breakout confirmation.
Signal Construction
- The script computes:
- leadinglongcond and leadingshortcond : The primary directional signals from the chosen leading indicator.
- longCond and shortCond : Final signals formed by combining the leading conditions with all enabled confirmations. Each confirmation contributes a boolean gate. If a filter is disabled, it contributes a neutral pass-through, keeping the logic intact without enforcing that condition.
- Expiry Logic: The code counts consecutive bars where the leading condition remains true. If confirmations do not line up within the user-defined “Signal Expiry Candle Count,” the setup is abandoned and the signal does not trigger.
- Alternation: An optional state ensures that long and short signals alternate. This can reduce repeated entries in the same direction without a clear reset.
- Finally, longCondition and shortCondition represent the actionable signals after expiry and alternation logic. These drive the label plotting and alert conditions.
Visualization
- Buy and Sell Labels: When longCondition or shortCondition confirm, the script plots annotated labels directly on the chart, making entries easy to see at a glance. The labels use color coding and clear text tags (“long” vs. “short”).
- Dashboard: A table summarizes the status of the leading indicator and all confirmations. Each row shows the indicator label and whether it passed (✔️) or failed (❌) on the current bar. This intensely practical UI helps you diagnose why a signal did or did not trigger, empowering faster strategy iteration and parameter tuning.
- Failed Confirmation Markers: If a setup expires (count exceeds the limit) and confirmations failed to align, the script can mark the chart with a small label and provide a tooltip listing which confirmations did not pass. It’s a helpful audit trail to understand missed trades or prevent “chasing” invalid signals.
- Data Window Values: The script outputs signal states to the data window, which can be useful for debugging or building composite conditions in multi-indicator templates.
Inputs and Parameters
- You control the indicator from a comprehensive input panel:
- Setup: Signal expiry count, whether to enforce alternating signals, and whether to display labels and the dashboard (including position and size).
- Leading Indicator: Choose the primary signal generator from the large list.
- Per-Filter Toggles: For each confirmation, a respect... toggle enables or disables it. Many include sub-options (like MACD type, Stochastic mode, RSI mode, ADX variants, thresholds for choppiness/volatility, etc.) to fine-tune behavior.
- Range Filter Settings: Choose type and behavior; select default vs. DW mode and smoothing. The underlying functions adjust band sizes using ATR, average change, standard deviation, or user-defined scales.
- Because everything is customizable, you can adapt the indicator to different assets, volatility regimes, and timeframes.
Alerts and Automation
- The script defines alert conditions tied to longCondition and shortCondition . You can set these alerts in your chart to trigger notifications or webhook calls for automated execution in external bots. The alert text is simple, and you can configure your own message template when creating alerts in the chart, including JSON payloads for algorithmic integration.
Typical Workflow
- Select a Leading Indicator aligned with your style. For trend following, Supertrend or SSL may be appropriate; for momentum, MACD or TSI; for range/trend-change detection, Range Filter, RQK, or Donchian.
- Add a few key Confirmation Filters that complement the leading signal. For example:
- Pair Supertrend with EMA Filter and RSI MA Direction to ensure trend alignment and positive momentum.
- Combine MACD Crossover with ADX/DMI and Volume Above MA to avoid signals in low-trend or low-liquidity conditions.
- Use RQK with Choppiness Index and Damiani Volatility to only act when the market is trending and volatile enough.
- Set a sensible Signal Expiry Candle Count. Shorter expiry keeps entries timely and reduces lag; longer expiry captures setups that mature slowly.
- Observe the Dashboard during live markets to see which filters pass or fail, then iterate. Tighten or loosen thresholds and filter combinations as needed.
- For automation, turn on alerts for the final conditions and use webhook payloads to notify your trading robot.
Strengths and Practical Notes
- Flexibility: The indicator is a toolkit rather than a single rigid model. It lets you test different combinations rapidly and visualize outcomes immediately.
- Clarity: Labels, dashboard, and failed-confirmation markers make it easy to audit behavior and refine settings without digging into code.
- Robustness: The expiry and alternation options add discipline, avoiding the temptation to enter late or repeatedly in one direction without a reset.
- Modular Design: The logical gates (“respect…”) make the behavior transparent: if a filter is on, it must pass; if it’s off, the signal ignores it. This keeps reasoning clean.
- Avoiding Overfitting: Because you can stack many filters, it’s tempting to over-constrain signals. Start simple (one leading indicator and one or two confirmations). Add complexity only if it demonstrably improves your edge across varied market regimes.
Limitations and Recommendations
- No single configuration is universally optimal. Markets change; tune filters for the instrument and timeframe you trade and revisit settings periodically.
- Trend filters can underperform in choppy markets; likewise, momentum filters can false-trigger in quiet periods. Consider using Choppiness Index or Damiani to gate signals by regime.
- Use expiry wisely. Too short may miss good setups that need a few bars to confirm; too long may cause late entries. Balance responsiveness and accuracy.
- Always consider risk management externally (position sizing, stops, profit targets). The indicator focuses on signal quality; combining it with robust trade management methods will improve results.
Example Configurations
- Trend-Following Setup:
- Leading: Supertrend uptrend for longs and downtrend for shorts.
- Confirmations: EMA Filter (price above 200 EMA for long, below for short), ADX/DMI (trend strength above threshold with +DI/-DI alignment), Volume Above MA.
- Expiry: 3–4 bars to keep entries timely.
- Result: Strong bias toward sustained moves while avoiding weak trends and thin liquidity.
- Mean-Reversion to Momentum Crossover:
- Leading: RSI exits from OB/OS zones (e.g., RSI leaves oversold for long and leaves overbought for short).
- Confirmations: 2 EMA Cross (fast crossing slow in the same direction), MACD zero-line behavior for added momentum validation.
- Expiry: 2–3 bars for responsive re-entry.
- Result: Captures momentum transitions after short-term extremes, with extra confirmation to reduce head-fakes.
- Range Breakout Focus:
- Leading: Range Filter Type 2 or Donchian Trend Ribbon to detect breakouts.
- Confirmations: Damiani Volatility (avoid low-volatility false breaks), Choppiness Index (prefer trend-ready states), ROC positive/negative threshold.
- Expiry: 1–3 bars to act on breakout windows.
- Result: Better alignment to breakout dynamics, gating trades by volatility and regime.
Conclusion
- This indicator is a comprehensive, configurable framework that merges a chosen leading signal with an array of corroborating filters, disciplined expiry handling, and intuitive visualization. It’s designed to help you build high-quality entry signals tailored to your approach, whether that’s trend-following, breakout trading, momentum capturing, or a hybrid. By surfacing pass/fail states in a dashboard and allowing alert-based automation, it bridges the gap between discretionary analysis and systematic execution. With sensible parameter tuning and thoughtful filter selection, it can serve as a robust backbone for signal generation across diverse instruments and timeframes.
Core Design
- Leading Indicator: You choose one primary signal generator from a broad list (for example, Range Filter, Supertrend, MACD, RSI, Ichimoku, and many others). This serves as the anchor of the system and determines when a preliminary long or short setup exists.
- Confirmation Filters: You can enable additional filters that validate the leading signal before it becomes actionable. Each “respect…” input toggles a filter on or off. These filters include popular tools like EMA, 2/3 EMA crosses, RQK (Nadaraya Watson), ADX/DMI, Bollinger-based oscillators, MACD variations, QQE, Hull, VWAP, Choppiness Index, Damiani Volatility, and more.
- Signal Expiry: To avoid waiting indefinitely for confirmations, the indicator counts how many consecutive bars the leading condition holds. If confirmations do not align within a defined number of bars, the setup expires. This controls latency and helps reduce late or stale entries.
- Alternating Signals: An optional mode enforces alternation (long must follow short and vice versa), helping avoid repeated entries in the same direction without a meaningful reset.
- Aggregation Logic: The final long/short conditions are formed by combining the leading condition with all selected confirmation filters through logical conjunction. Only if all enabled filters validate the signal (within expiry constraints) does the indicator consider it a confirmed long or short.
- Visualization and Alerts: The script plots buy/sell labels at signal points, provides alert conditions for automation, and displays a compact dashboard summarizing the leading indicator’s status and each confirmation’s pass/fail result using checkmarks.
Leading Indicator Options
- The indicator includes a very large menu of leading tools, each with its own logic to determine uptrend or downtrend impulses. Highlights include:
- Range Filter: Uses a dynamic centerline and bands computed via conditional EMA/SMA and range sizing to define directional movement. It can operate in a default mode or an alternative “DW” mode.
- Rational Quadratic Kernel (RQK): Applies a kernel smoothing model (Nadaraya Watson) to detect uptrends and downtrends with a focus on noise reduction.
- Supertrend, Half Trend, SSL Channel: Classic trend-following tools that derive direction from ATR-based bands or moving average channels.
- Ichimoku Cloud and SuperIchi: Multi-component systems validating trend via cloud position, conversion/base line relationships, projected cloud, and lagging span.
- TSI (True Strength Index), DPO (Detrended Price Oscillator), AO (Awesome Oscillator), MACD, STC (Schaff Trend Cycle), QQE Mod: Momentum and cycle tools that parse direction from crossovers, zero-line behavior, and momentum shifts.
- Donchian Trend Ribbon, Chandelier Exit: Trend and exit tools that can validate breakouts or sustained trend strength.
- ADX/DMI: Measures trend strength and directional movement via +DI/-DI relationships and minimum ADX thresholds.
- RSI and Stochastic: Use crossovers, level exits, or threshold filters to gate entries based on overbought/oversold dynamics or relative strength trends.
- Vortex, Chaikin Money Flow, VWAP, Bull Bear Power, ROC, Wolfpack Id, Hull Suite: A diverse set of directional, momentum, and volume-based indicators to suit different markets and styles.
- Trendline Breakout and Range Detector: Price-behavior filters that confirm signals during breakouts or within defined ranges.
Confirmation Filters
- Each filter is optional. When enabled, it must validate the leading condition for a signal to pass. Examples:
- EMA Filter: Requires price to be above a specified EMA for longs and below for shorts, filtering signals that contradict broader trend or baseline levels.
- 2 EMA Cross and 3 EMA Cross: Enforce moving average cross conditions (fast above slow for long, the reverse for short) or a three-line stacking logic for more stringent trend alignment.
- RQK, Supertrend, Half Trend, Donchian, QQE, Hull, MACD (crossover vs. zero-line), AO (zero line or AC momentum variants), SSL: Each adds its characteristic validation pattern.
- RSI family (MA cross, exits OB/OS zones, threshold levels) plus RSI MA direction and RSI/RSI MA limits: Multiple ways to constrain signals via relative strength behavior and trajectories.
- Choppiness Index and Damiani Volatility: Prevent entries during ranging conditions or insufficient volatility; choppiness thresholds and volatility states gate the trade.
- VWAP, Volume modes (above MA, simple up/down, delta), Chaikin Money Flow: Volume and flow conditions that ensure signals happen in supportive liquidity or accumulation/distribution contexts.
- ADX/DMI thresholds: Demand a minimum trend strength and directional DI alignment to reduce whipsaw trades.
- Trendline Breakout and Range Detector: Confirm that the price is breaking structure or remains within active range consistent with the leading setup.
- By combining several filters you can create strict, conservative entries or looser setups depending on your goals.
Range Filter Engine
- A core building block, the Range Filter uses conditional EMA and SMA functions to compute adaptive bands around a dynamic centerline. It supports two types:
- Type 1: The centerline updates when price exceeds the band thresholds; bands define acceptable drift ranges.
- Type 2: Uses quantized steps (via floor operations) relative to the previous centerline to handle larger moves in discrete increments.
- The engine offers smoothing for range values using a secondary EMA and can switch between raw and averaged outputs. Its hi/lo bands and centerline compose a corridor that defines directional movement and potential breakout confirmation.
Signal Construction
- The script computes:
- leadinglongcond and leadingshortcond : The primary directional signals from the chosen leading indicator.
- longCond and shortCond : Final signals formed by combining the leading conditions with all enabled confirmations. Each confirmation contributes a boolean gate. If a filter is disabled, it contributes a neutral pass-through, keeping the logic intact without enforcing that condition.
- Expiry Logic: The code counts consecutive bars where the leading condition remains true. If confirmations do not line up within the user-defined “Signal Expiry Candle Count,” the setup is abandoned and the signal does not trigger.
- Alternation: An optional state ensures that long and short signals alternate. This can reduce repeated entries in the same direction without a clear reset.
- Finally, longCondition and shortCondition represent the actionable signals after expiry and alternation logic. These drive the label plotting and alert conditions.
Visualization
- Buy and Sell Labels: When longCondition or shortCondition confirm, the script plots annotated labels directly on the chart, making entries easy to see at a glance. The labels use color coding and clear text tags (“long” vs. “short”).
- Dashboard: A table summarizes the status of the leading indicator and all confirmations. Each row shows the indicator label and whether it passed (✔️) or failed (❌) on the current bar. This intensely practical UI helps you diagnose why a signal did or did not trigger, empowering faster strategy iteration and parameter tuning.
- Failed Confirmation Markers: If a setup expires (count exceeds the limit) and confirmations failed to align, the script can mark the chart with a small label and provide a tooltip listing which confirmations did not pass. It’s a helpful audit trail to understand missed trades or prevent “chasing” invalid signals.
- Data Window Values: The script outputs signal states to the data window, which can be useful for debugging or building composite conditions in multi-indicator templates.
Inputs and Parameters
- You control the indicator from a comprehensive input panel:
- Setup: Signal expiry count, whether to enforce alternating signals, and whether to display labels and the dashboard (including position and size).
- Leading Indicator: Choose the primary signal generator from the large list.
- Per-Filter Toggles: For each confirmation, a respect... toggle enables or disables it. Many include sub-options (like MACD type, Stochastic mode, RSI mode, ADX variants, thresholds for choppiness/volatility, etc.) to fine-tune behavior.
- Range Filter Settings: Choose type and behavior; select default vs. DW mode and smoothing. The underlying functions adjust band sizes using ATR, average change, standard deviation, or user-defined scales.
- Because everything is customizable, you can adapt the indicator to different assets, volatility regimes, and timeframes.
Alerts and Automation
- The script defines alert conditions tied to longCondition and shortCondition . You can set these alerts in your chart to trigger notifications or webhook calls for automated execution in external bots. The alert text is simple, and you can configure your own message template when creating alerts in the chart, including JSON payloads for algorithmic integration.
Typical Workflow
- Select a Leading Indicator aligned with your style. For trend following, Supertrend or SSL may be appropriate; for momentum, MACD or TSI; for range/trend-change detection, Range Filter, RQK, or Donchian.
- Add a few key Confirmation Filters that complement the leading signal. For example:
- Pair Supertrend with EMA Filter and RSI MA Direction to ensure trend alignment and positive momentum.
- Combine MACD Crossover with ADX/DMI and Volume Above MA to avoid signals in low-trend or low-liquidity conditions.
- Use RQK with Choppiness Index and Damiani Volatility to only act when the market is trending and volatile enough.
- Set a sensible Signal Expiry Candle Count. Shorter expiry keeps entries timely and reduces lag; longer expiry captures setups that mature slowly.
- Observe the Dashboard during live markets to see which filters pass or fail, then iterate. Tighten or loosen thresholds and filter combinations as needed.
- For automation, turn on alerts for the final conditions and use webhook payloads to notify your trading robot.
Strengths and Practical Notes
- Flexibility: The indicator is a toolkit rather than a single rigid model. It lets you test different combinations rapidly and visualize outcomes immediately.
- Clarity: Labels, dashboard, and failed-confirmation markers make it easy to audit behavior and refine settings without digging into code.
- Robustness: The expiry and alternation options add discipline, avoiding the temptation to enter late or repeatedly in one direction without a reset.
- Modular Design: The logical gates (“respect…”) make the behavior transparent: if a filter is on, it must pass; if it’s off, the signal ignores it. This keeps reasoning clean.
- Avoiding Overfitting: Because you can stack many filters, it’s tempting to over-constrain signals. Start simple (one leading indicator and one or two confirmations). Add complexity only if it demonstrably improves your edge across varied market regimes.
Limitations and Recommendations
- No single configuration is universally optimal. Markets change; tune filters for the instrument and timeframe you trade and revisit settings periodically.
- Trend filters can underperform in choppy markets; likewise, momentum filters can false-trigger in quiet periods. Consider using Choppiness Index or Damiani to gate signals by regime.
- Use expiry wisely. Too short may miss good setups that need a few bars to confirm; too long may cause late entries. Balance responsiveness and accuracy.
- Always consider risk management externally (position sizing, stops, profit targets). The indicator focuses on signal quality; combining it with robust trade management methods will improve results.
Example Configurations
- Trend-Following Setup:
- Leading: Supertrend uptrend for longs and downtrend for shorts.
- Confirmations: EMA Filter (price above 200 EMA for long, below for short), ADX/DMI (trend strength above threshold with +DI/-DI alignment), Volume Above MA.
- Expiry: 3–4 bars to keep entries timely.
- Result: Strong bias toward sustained moves while avoiding weak trends and thin liquidity.
- Mean-Reversion to Momentum Crossover:
- Leading: RSI exits from OB/OS zones (e.g., RSI leaves oversold for long and leaves overbought for short).
- Confirmations: 2 EMA Cross (fast crossing slow in the same direction), MACD zero-line behavior for added momentum validation.
- Expiry: 2–3 bars for responsive re-entry.
- Result: Captures momentum transitions after short-term extremes, with extra confirmation to reduce head-fakes.
- Range Breakout Focus:
- Leading: Range Filter Type 2 or Donchian Trend Ribbon to detect breakouts.
- Confirmations: Damiani Volatility (avoid low-volatility false breaks), Choppiness Index (prefer trend-ready states), ROC positive/negative threshold.
- Expiry: 1–3 bars to act on breakout windows.
- Result: Better alignment to breakout dynamics, gating trades by volatility and regime.
Conclusion
- This indicator is a comprehensive, configurable framework that merges a chosen leading signal with an array of corroborating filters, disciplined expiry handling, and intuitive visualization. It’s designed to help you build high-quality entry signals tailored to your approach, whether that’s trend-following, breakout trading, momentum capturing, or a hybrid. By surfacing pass/fail states in a dashboard and allowing alert-based automation, it bridges the gap between discretionary analysis and systematic execution. With sensible parameter tuning and thoughtful filter selection, it can serve as a robust backbone for signal generation across diverse instruments and timeframes.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Script de código aberto
No verdadeiro espirito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam entendê-lo e verificá-lo. Parabéns ao autor Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações e regida pelas Regras da Casa.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.