OPEN-SOURCE SCRIPT

Fuzzy SMA Trend Analyzer (experimental)[FibonacciFlux]

271
Fuzzy SMA Trend Analyzer (Normalized): Advanced Market Trend Detection Using Fuzzy Logic Theory

Elevate your technical analysis with institutional-grade fuzzy logic implementation

Research Genesis & Conceptual Framework

This indicator represents the culmination of extensive research into applying fuzzy logic theory to financial markets. While traditional technical indicators often produce binary outcomes, market conditions exist on a continuous spectrum. The Fuzzy SMA Trend Analyzer addresses this limitation by implementing a sophisticated fuzzy logic system that captures the nuanced, multi-dimensional nature of market trends.

Core Fuzzy Logic Principles

At the heart of this indicator lies fuzzy logic theory - a mathematical framework designed to handle imprecision and uncertainty:

Pine Script®
// Improved fuzzy_triangle function with guard clauses for NA and invalid parameters. fuzzy_triangle(val, left, center, right) => if na(val) or na(left) or na(center) or na(right) or left > center or center > right // Guard checks 0.0 else if left == center and center == right // Crisp set (single point) val == center ? 1.0 : 0.0 else if left == center // Left-shoulder shape (ramp down from 1 at center to 0 at right) val >= right ? 0.0 : val <= center ? 1.0 : (right - val) / (right - center) else if center == right // Right-shoulder shape (ramp up from 0 at left to 1 at center) val <= left ? 0.0 : val >= center ? 1.0 : (val - left) / (center - left) else // Standard triangle math.max(0.0, math.min((val - left) / (center - left), (right - val) / (right - center)))


This implementation of triangular membership functions enables the indicator to transform crisp numerical values into degrees of membership in linguistic variables like "Large Positive" or "Small Negative," creating a more nuanced representation of market conditions.

Dynamic Percentile Normalization

A critical innovation in this indicator is the implementation of percentile-based normalization for SMA deviation:

Pine Script®
// ----- Deviation Scale Estimation using Percentile ----- // Calculate the percentile rank of the *absolute* deviation over the lookback period. // This gives an estimate of the 'typical maximum' deviation magnitude recently. diff_abs_percentile = ta.percentile_linear_interpolation(math.abs(raw_diff), normLookback, percRank) + 1e-10 // ----- Normalize the Raw Deviation ----- // Divide the raw deviation by the estimated 'typical max' magnitude. normalized_diff = raw_diff / diff_abs_percentile // ----- Clamp the Normalized Deviation ----- normalized_diff_clamped = math.max(-3.0, math.min(3.0, normalized_diff))


This percentile normalization approach creates a self-adapting system that automatically calibrates to different assets and market regimes. Rather than using fixed thresholds, the indicator dynamically adjusts based on recent volatility patterns, significantly enhancing signal quality across diverse market environments.

Multi-Factor Fuzzy Rule System

The indicator implements a comprehensive fuzzy rule system that evaluates multiple technical factors:

  • SMA Deviation (Normalized): Measures price displacement from the Simple Moving Average
  • Rate of Change (ROC): Captures price momentum over a specified period
  • Relative Strength Index (RSI): Assesses overbought/oversold conditions


These factors are processed through a sophisticated fuzzy inference system with linguistic variables:

Pine Script®
// ----- 3.1 Fuzzy Sets for Normalized Deviation ----- diffN_LP := fuzzy_triangle(normalized_diff_clamped, 0.7, 1.5, 3.0) // Large Positive (around/above percentile) diffN_SP := fuzzy_triangle(normalized_diff_clamped, 0.1, 0.5, 0.9) // Small Positive diffN_NZ := fuzzy_triangle(normalized_diff_clamped, -0.2, 0.0, 0.2) // Near Zero diffN_SN := fuzzy_triangle(normalized_diff_clamped, -0.9, -0.5, -0.1) // Small Negative diffN_LN := fuzzy_triangle(normalized_diff_clamped, -3.0, -1.5, -0.7) // Large Negative (around/below percentile) // ----- 3.2 Fuzzy Sets for ROC ----- roc_HN := fuzzy_triangle(roc_val, -8.0, -5.0, -2.0) roc_WN := fuzzy_triangle(roc_val, -3.0, -1.0, -0.1) roc_NZ := fuzzy_triangle(roc_val, -0.3, 0.0, 0.3) roc_WP := fuzzy_triangle(roc_val, 0.1, 1.0, 3.0) roc_HP := fuzzy_triangle(roc_val, 2.0, 5.0, 8.0) // ----- 3.3 Fuzzy Sets for RSI ----- rsi_L := fuzzy_triangle(rsi_val, 0.0, 25.0, 40.0) rsi_M := fuzzy_triangle(rsi_val, 35.0, 50.0, 65.0) rsi_H := fuzzy_triangle(rsi_val, 60.0, 75.0, 100.0)


Advanced Fuzzy Inference Rules

The indicator employs a comprehensive set of fuzzy rules that encode expert knowledge about market behavior:

Pine Script®
// --- Fuzzy Rules using Normalized Deviation (diffN_*) --- cond1 = math.min(diffN_LP, roc_HP, math.max(rsi_M, rsi_H)) // Strong Bullish: Large pos dev, strong pos roc, rsi ok strength_SB := math.max(strength_SB, cond1) cond2 = math.min(diffN_SP, roc_WP, rsi_M) // Weak Bullish: Small pos dev, weak pos roc, rsi mid strength_WB := math.max(strength_WB, cond2) cond3 = math.min(diffN_SP, roc_NZ, rsi_H) // Weakening Bullish: Small pos dev, flat roc, rsi high strength_N := math.max(strength_N, cond3 * 0.6) // More neutral strength_WB := math.max(strength_WB, cond3 * 0.2) // Less weak bullish


This rule system evaluates multiple conditions simultaneously, weighting them by their degree of membership to produce a comprehensive trend assessment. The rules are designed to identify various market conditions including strong trends, weakening trends, potential reversals, and neutral consolidations.

Defuzzification Process

The final step transforms the fuzzy result back into a crisp numerical value representing the overall trend strength:

Pine Script®
// --- Step 6: Defuzzification --- denominator = strength_SB + strength_WB + strength_N + strength_WBe + strength_SBe if denominator > 1e-10 // Use small epsilon instead of != 0.0 for float comparison fuzzyTrendScore := (strength_SB * STRONG_BULL + strength_WB * WEAK_BULL + strength_N * NEUTRAL + strength_WBe * WEAK_BEAR + strength_SBe * STRONG_BEAR) / denominator


The resulting FuzzyTrendScore ranges from -1 (strong bearish) to +1 (strong bullish), providing a smooth, continuous evaluation of market conditions that avoids the abrupt signal changes common in traditional indicators.

Advanced Visualization with Rainbow Gradient

The indicator incorporates sophisticated visualization using a rainbow gradient coloring system:

Pine Script®
// Normalize score to [0, 1] for gradient function normalizedScore = na(fuzzyTrendScore) ? 0.5 : math.max(0.0, math.min(1.0, (fuzzyTrendScore + 1) / 2)) // Get the color based on gradient setting and normalized score final_color = get_gradient(normalizedScore, gradient_type)


This color-coding system provides intuitive visual feedback, with color intensity reflecting trend strength and direction. The gradient can be customized between Red-to-Green or Red-to-Blue configurations based on user preference.

Practical Applications

The Fuzzy SMA Trend Analyzer excels in several key applications:

  • Trend Identification: Precisely identifies market trend direction and strength with nuanced gradation
  • Market Regime Detection: Distinguishes between trending markets and consolidation phases
  • Divergence Analysis: Highlights potential reversals when price action and fuzzy trend score diverge
  • Filter for Trading Systems: Provides high-quality trend filtering for other trading strategies
  • Risk Management: Offers early warning of potential trend weakening or reversal


Parameter Customization

The indicator offers extensive customization options:

  • SMA Length: Adjusts the baseline moving average period
  • ROC Length: Controls momentum sensitivity
  • RSI Length: Configures overbought/oversold sensitivity
  • Normalization Lookback: Determines the adaptive calculation window for percentile normalization
  • Percentile Rank: Sets the statistical threshold for deviation normalization
  • Gradient Type: Selects the preferred color scheme for visualization


These parameters enable fine-tuning to specific market conditions, trading styles, and timeframes.

Acknowledgments

The rainbow gradient visualization component draws inspiration from LuxAlgo's "Rainbow Adaptive RSI" (used under CC BY-NC-SA 4.0 license). This implementation of fuzzy logic in technical analysis builds upon Fermi estimation principles to overcome the inherent limitations of crisp binary indicators.

This indicator is shared under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.

Remember that past performance does not guarantee future results. Always conduct thorough testing before implementing any technical indicator in live trading.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.