Fuzzy SMA with DCTI Confirmation[FibonacciFlux]FibonacciFlux: Advanced Fuzzy Logic System with Donchian Trend Confirmation 
Institutional-grade trend analysis combining adaptive Fuzzy Logic with Donchian Channel Trend Intensity for superior signal quality
 Conceptual Framework & Research Foundation 
FibonacciFlux represents a significant advancement in quantitative technical analysis, merging two powerful analytical methodologies: normalized fuzzy logic systems and Donchian Channel Trend Intensity (DCTI). This sophisticated indicator addresses a fundamental challenge in market analysis – the inherent imprecision of trend identification in dynamic, multi-dimensional market environments.
While traditional indicators often produce simplistic binary signals, markets exist in states of continuous, graduated transition. FibonacciFlux embraces this complexity through its implementation of fuzzy set theory, enhanced by DCTI's structural trend confirmation capabilities. The result is an indicator that provides nuanced, probabilistic trend assessment with institutional-grade signal quality.
 Core Technological Components 
 1. Advanced Fuzzy Logic System with Percentile Normalization 
At the foundation of FibonacciFlux lies a comprehensive fuzzy logic system that transforms conventional technical metrics into degrees of membership in linguistic variables:
 
// Fuzzy triangular membership function with robust error handling
fuzzy_triangle(val, left, center, right) =>
    if na(val)
        0.0
    float denominator1 = math.max(1e-10, center - left)
    float denominator2 = math.max(1e-10, right - center)
    math.max(0.0, math.min(left == center ? val <= center ? 1.0 : 0.0 : (val - left) / denominator1, 
                           center == right ? val >= center ? 1.0 : 0.0 : (right - val) / denominator2))
 
The system employs percentile-based normalization for SMA deviation – a critical innovation that enables self-calibration across different assets and market regimes:
 
// Percentile-based normalization for adaptive calibration
raw_diff = price_src - sma_val
diff_abs_percentile = ta.percentile_linear_interpolation(math.abs(raw_diff), normLookback, percRank) + 1e-10
normalized_diff_raw = raw_diff / diff_abs_percentile
normalized_diff = useClamping ? math.max(-clampValue, math.min(clampValue, normalized_diff_raw)) : normalized_diff_raw
 
This normalization approach represents a significant advancement over fixed-threshold systems, allowing the indicator to automatically adapt to varying volatility environments and maintain consistent signal quality across diverse market conditions.
 2. Donchian Channel Trend Intensity (DCTI) Integration 
FibonacciFlux significantly enhances fuzzy logic analysis through the integration of Donchian Channel Trend Intensity (DCTI) – a sophisticated measure of trend strength based on the relationship between short-term and long-term price extremes:
 
// DCTI calculation for structural trend confirmation
f_dcti(src, majorPer, minorPer, sigPer) =>
    H = ta.highest(high, majorPer) // Major period high
    L = ta.lowest(low, majorPer)   // Major period low
    h = ta.highest(high, minorPer) // Minor period high
    l = ta.lowest(low, minorPer)   // Minor period low
    float pdiv = not na(L) ? l - L : 0 // Positive divergence (low vs major low)
    float ndiv = not na(H) ? H - h : 0 // Negative divergence (major high vs high)
    float divisor = pdiv + ndiv
    dctiValue = divisor == 0 ? 0 : 100 * ((pdiv - ndiv) / divisor) // Normalized to -100 to +100 range
    sigValue = ta.ema(dctiValue, sigPer)
     
 
DCTI provides a complementary structural perspective on market trends by quantifying the relationship between short-term and long-term price extremes. This creates a multi-dimensional analysis framework that combines adaptive deviation measurement (fuzzy SMA) with channel-based trend intensity confirmation (DCTI).
 Multi-Dimensional Fuzzy Input Variables 
FibonacciFlux processes four distinct technical dimensions through its fuzzy system:
 
   Normalized SMA Deviation:  Measures price displacement relative to historical volatility context
   Rate of Change (ROC):  Captures price momentum over configurable timeframes
   Relative Strength Index (RSI):  Evaluates cyclical overbought/oversold conditions
   Donchian Channel Trend Intensity (DCTI):  Provides structural trend confirmation through channel analysis
 
Each dimension is processed through comprehensive fuzzy sets that transform crisp numerical values into linguistic variables:
 
// Normalized SMA Deviation - Self-calibrating to volatility regimes
ndiff_LP := fuzzy_triangle(normalized_diff, norm_scale * 0.3, norm_scale * 0.7, norm_scale * 1.1)
ndiff_SP := fuzzy_triangle(normalized_diff, norm_scale * 0.05, norm_scale * 0.25, norm_scale * 0.5)
ndiff_NZ := fuzzy_triangle(normalized_diff, -norm_scale * 0.1, 0.0, norm_scale * 0.1)
ndiff_SN := fuzzy_triangle(normalized_diff, -norm_scale * 0.5, -norm_scale * 0.25, -norm_scale * 0.05)
ndiff_LN := fuzzy_triangle(normalized_diff, -norm_scale * 1.1, -norm_scale * 0.7, -norm_scale * 0.3)
// DCTI - Structural trend measurement
dcti_SP := fuzzy_triangle(dcti_val, 60.0, 85.0, 101.0) // Strong Positive Trend (> ~85)
dcti_WP := fuzzy_triangle(dcti_val, 20.0, 45.0, 70.0)  // Weak Positive Trend (~30-60)
dcti_Z := fuzzy_triangle(dcti_val, -30.0, 0.0, 30.0)   // Near Zero / Trendless (~+/- 20)
dcti_WN := fuzzy_triangle(dcti_val, -70.0, -45.0, -20.0) // Weak Negative Trend (~-30 - -60)
dcti_SN := fuzzy_triangle(dcti_val, -101.0, -85.0, -60.0) // Strong Negative Trend (< ~-85)
 
 Advanced Fuzzy Rule System with DCTI Confirmation 
The core intelligence of FibonacciFlux lies in its sophisticated fuzzy rule system – a structured knowledge representation that encodes expert understanding of market dynamics:
 
// Base Trend Rules with DCTI Confirmation
cond1 = math.min(ndiff_LP, roc_HP, rsi_M)
strength_SB := math.max(strength_SB, cond1 * (dcti_SP > 0.5 ? 1.2 : dcti_Z > 0.1 ? 0.5 : 1.0))
// DCTI Override Rules - Structural trend confirmation with momentum alignment
cond14 = math.min(ndiff_NZ, roc_HP, dcti_SP)
strength_SB := math.max(strength_SB, cond14 * 0.5)
 
The rule system implements 15 distinct fuzzy rules that evaluate various market conditions including:
 
   Established Trends:  Strong deviations with confirming momentum and DCTI alignment
   Emerging Trends:  Early deviation patterns with initial momentum and DCTI confirmation
   Weakening Trends:  Divergent signals between deviation, momentum, and DCTI
   Reversal Conditions:  Counter-trend signals with DCTI confirmation
   Neutral Consolidations:  Minimal deviation with low momentum and neutral DCTI
 
A key innovation is the weighted influence of DCTI on rule activation. When strong DCTI readings align with other indicators, rule strength is amplified (up to 1.2x). Conversely, when DCTI contradicts other indicators, rule impact is reduced (as low as 0.5x). This creates a dynamic, self-adjusting system that prioritizes high-conviction signals.
 Defuzzification & Signal Generation 
The final step transforms fuzzy outputs into a precise trend score through center-of-gravity defuzzification:
 
// Defuzzification with precise floating-point handling
denominator = strength_SB + strength_WB + strength_N + strength_WBe + strength_SBe
if denominator > 1e-10
    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.0 (Strong Bear) to +1.0 (Strong Bull), with critical threshold zones at ±0.3 (Weak trend) and ±0.7 (Strong trend). The histogram visualization employs intuitive color-coding for immediate trend assessment.
 Strategic Applications for Institutional Trading 
FibonacciFlux provides substantial advantages for sophisticated trading operations:
 
   Multi-Timeframe Signal Confirmation:  Institutional-grade signal validation across multiple technical dimensions
   Trend Strength Quantification:  Precise measurement of trend conviction with noise filtration
   Early Trend Identification:  Detection of emerging trends before traditional indicators through fuzzy pattern recognition
   Adaptive Market Regime Analysis:  Self-calibrating analysis across varying volatility environments
   Algorithmic Strategy Integration:  Well-defined numerical output suitable for systematic trading frameworks
   Risk Management Enhancement:  Superior signal fidelity for risk exposure optimization
 
 Customization Parameters 
FibonacciFlux offers extensive customization to align with specific trading mandates and market conditions:
 
   Fuzzy SMA Settings:  Configure baseline trend identification parameters including SMA, ROC, and RSI lengths
   Normalization Settings:  Fine-tune the self-calibration mechanism with adjustable lookback period, percentile rank, and optional clamping
   DCTI Parameters:  Optimize trend structure confirmation with adjustable major/minor periods and signal smoothing
   Visualization Controls:  Customize display transparency for optimal chart integration
 
These parameters enable precise calibration for different asset classes, timeframes, and market regimes while maintaining the core analytical framework.
 Implementation Notes 
For optimal implementation, consider the following guidance:
 
  Higher timeframes (4H+) benefit from increased normalization lookback (800+) for stability
  Volatile assets may require adjusted clamping values (2.5-4.0) for optimal signal sensitivity
  DCTI parameters should be aligned with chart timeframe (higher timeframes require increased major/minor periods)
  The indicator performs exceptionally well as a trend filter for systematic trading strategies
 
 Acknowledgments 
FibonacciFlux builds upon the pioneering work of Donovan Wall in Donchian Channel Trend Intensity analysis. The normalization approach draws inspiration from percentile-based statistical techniques in quantitative finance. This indicator is shared for educational and analytical purposes under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.
Past performance does not guarantee future results. All trading involves risk. This indicator should be used as one component of a comprehensive analysis framework.
Shout out @DonovanWall
 
Fazzy
Fuzzy SMA Trend Analyzer (experimental)[FibonacciFlux]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:
 
// 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:
 
// ----- 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:
 
// ----- 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:
 
// --- 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:
 
// --- 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:
 
// Normalize score to   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.

