OPEN-SOURCE SCRIPT

Trend State [DAFE]

2 497
Trend State [DAFE]

A State-Driven Confidence Trend Engine
Where Trend is Assessed as a Matter of Confidence, Not as a Binary Switch.
The Trend State engine is a systematic approach to trend analysis designed to address the fundamental limitations of traditional, binary-state indicators. Its core premise is that a market trend is not an "on/off" condition but a dynamic state that builds, sustains, and loses confidence over time. Instead of relying on a single price crossover, this engine operates like a jury, continuously gathering and weighing multiple forms of evidence to determine the true state of the market.
This results in a more nuanced, context-aware model that provides deeper insight into trend health, sustainability, and structural integrity.

The Problem with Binary-State Trend Indicators
Traditional indicators like a standard Supertrend operate on a binary, stateless model. A trend is either "up" or "down," and the switch is triggered by a single event: price closing across a calculated line. This model, while simple, suffers from critical drawbacks:
Lack of Memory: It has no concept of how strong the previous trend was. A powerful, multi-month bull run is treated with the same fragility as a weak, two-day rally. Both can be negated by a single bar's close.
Susceptibility to Whipsaws: Because the logic is binary, any volatile price action around the trendline can trigger a rapid succession of "buy" and "sell" signals, leading to over-trading in choppy or transitional markets.
No Concept of Neutrality: The market is forced into a bullish or bearish classification at all times. It lacks a "gray area" or a state of indecision, which is where many binary systems fail.
No Context of Trend Health: It cannot differentiate between a healthy, accelerating trend and one that is structurally compromised and likely to fail.
The Trend State Solution: A Multi-Pillar Confidence Model
The Trend State engine solves these issues through its proprietary architecture.

Pillar 1: The Rolling Evidence Matrix
This is the core of the engine. Instead of a single condition, the system maintains ten "evidence buckets"—five for bullish evidence and five for bearish. On every bar, new evidence is added to these buckets based on specific market behaviors. Simultaneously, the old evidence in every bucket is subject to a time-based decay, ensuring that recent events carry more weight than older ones.
The five categories of evidence collected are:
Impulse: Strong, directional thrust bars with high volume and a close near the highs/lows. Represents aggressive participation.
Structure: The breaking of recent swing highs/lows, or the reclamation of those levels after a failed break. Represents technical progress.
Exhaustion: Reversal pressure, identified through significant rejection wicks or volume divergences. Represents the failure of the opposing side.
Continuation: Quiet persistence, such as price continuing to close higher/lower while respecting the underlying price anchor. Represents sustained momentum.
Compression: A decrease in range and volatility, suggesting a buildup of energy for the next directional move.
Each category has a user-defined weight, allowing for fine-tuning of the engine's sensitivity to different market behaviors. The sum of this weighted evidence creates the final Bull and Bear Confidence Scores.

Pillar 2: The 3-State Engine (Bull / Transition / Bear)
Based on the confidence scores, the engine operates in one of three states:
Bull State (1): Bullish evidence is dominant, substantial, and actively holding above key thresholds.
Bear State (-1): Bearish evidence is dominant, substantial, and actively holding above key thresholds.
Transition State (0): Neither side has sufficient confidence, or the dominant side is losing its grip. This is the critical "gray area" where binary indicators produce whipsaws. The Trend State engine identifies this as a period of indecision or a potential turning point.

Pillar 3: The Damage Detection Layer
This is a crucial innovation that provides context on trend health. If a trend is in an active Bull or Bear state, this layer continuously scans for signs of structural compromise (e.g., price crossing below the anchor, strong opposing impulse bars, high opposing pressure). If enough "damage" accumulates, the trend is flagged as Damaged. A damaged state has critical consequences:
Accelerated Deterioration: The confidence score of the current trend decays faster.
Reduced Impulse: New evidence in favor of the damaged trend has less impact.
Increased Fragility: The thresholds required to flip the trend into a Transition state are lowered, making it easier for the compromised trend to fail.

Pillar 4: Optional Footprint Enhancement
For maximum fidelity, the engine can integrate real order flow data from footprint charts. This enhances the evidence-gathering process by confirming price action with volume. For example, a bullish impulse bar is given a significantly higher score if it is accompanied by strong, positive delta, confirming aggressive market buying.
A METHODOLOGICAL COMPARISON: Standard Supertrend vs. Trend State Engine
To understand the architectural difference, consider this side-by-side comparison:
لقطة

🔧 COMPREHENSIVE INPUT SYSTEM

Core Engine
Anchor Length: The EMA period for the central price anchor, which acts as the gravitational baseline for the system.
Base Width Multiplier: The master ATR multiplier for the trail distance.
Bucket Decay: The per-bar decay rate (0.50-0.99) for all evidence buckets. A lower value gives the system a shorter memory, while a higher value allows it to "remember" evidence for longer.

Bucket Weights
Granular control to assign a weight to each of the five evidence categories (Impulse, Structure, Exhaustion, Continuation, Compression). This allows you to calibrate the engine's personality—for example, making it more sensitive to structural breaks than to impulse moves.

State Engine
Enter Net Threshold: The minimum net confidence score (Bull Score - Bear Score) required to shift from the Transition state into a confirmed Bull or Bear state.
Hold Net Threshold: While in an active Bull/Bear state, if the net confidence falls below this value, the trend is considered lost, and the engine returns to the Transition state.
Dominance Threshold: A ratio (Net / Total) that ensures a true trend is established, not just a slight edge in a low-activity market.

Damage Layer
Enable Damage Detection: Toggles the entire damage analysis module.
Damage Score Threshold: The cumulative damage score required to flag a trend as "Damaged."
Decay Multiplier, Impulse Retention, Threshold Ease: A suite of inputs to control exactly how a "Damaged" state affects the system's behavior, allowing for fine-tuning of its risk-off response.

🎨 ADVANCED VISUAL SYSTEM

The Trend State engine leverages the DafeVisLib library to provide a clean, professional, and highly informative visual experience.
The Main Trend Line: The line's color instantly communicates the current state: Bullish, Bearish, or Transition. Crucially, it will adopt a distinct "alert" color when the active trend is flagged as Damaged.
لقطة

State Markers: Clear labels appear on the chart to mark the exact bar where the state shifts to Bull (▲), Bear (▼), or Transition (◆).
لقطة

Damage Markers: An alert symbol (!) appears above/below the bar when the Damage Threshold is breached, providing an un-missable visual warning of trend deterioration.
لقطة

The Cloud: The area between the trend line and the price anchor is shaded, creating a dynamic cloud that provides a clear visual representation of the trend's strength and control.
لقطة

📊 GAUGE DASHBOARD & NARRATIVE PANEL

The indicator includes two advanced UI elements for at-a-glance analysis.
The Gauge Dashboard
This panel provides a complete quantitative breakdown of the engine's internal state, featuring:
State Info: Displays the current state, Footprint status, and live Delta.
Confidence Engine Gauges: Real-time gauges visualizing the raw Bull, Bear, and Net Confidence scores.
Pressure Kinetics Gauges: Displays the Dominance and Pressure ratios, showing which side is in control of the market auction.
Damage Layer Gauges: Shows the current Damage Status (Intact/Damaged) and the live scores being accumulated against the active trend.
Evidence Bucket Breakdowns: Individual gauges for all 10 evidence buckets, allowing you to see exactly what kind of evidence is driving the current market move.
لقطة

The Narrative Panel
This unique panel provides a qualitative, human-readable summary of the complex quantitative data from the engine. It translates the numbers into a clear story, with simple statements describing the current Regime, Kinetics, Structure, and Order Flow.
لقطة

⚖️ RESPONSIBLE USAGE
This is a Decision-Support System: The Trend State engine is designed to provide a deep, contextual understanding of trend health. It is not a black-box signal generator. Its outputs should be used to inform and enhance a pre-existing trading plan.
Context is Key: A "Bull State" confirmation is a statement about trend confidence, not a guarantee of future price movement. Always consider the broader market context.
Calibration is Recommended: The default weights and thresholds are robustly balanced, but the true power of the engine is unlocked by calibrating these settings to the specific personality of the asset and timeframe you are trading.

🔮 CONCLUSION
The Trend State engine represents a significant evolution in trend analysis. By moving away from a simple, binary model and adopting a multi-faceted, evidence-based confidence system, it offers a more robust and realistic interpretation of market dynamics. Its ability to quantify trend health through its Damage Layer and to recognize periods of indecision with its Transition State provides traders with critical context that traditional indicators simply cannot see. This is a tool for traders who wish to understand not just the direction of a trend, but its quality, sustainability, and structural integrity.

— Dskyz, Trade with insight. Trade with anticipation. (Funny how innovation suddenly shows up everywhere once you build something real. This is a Rolling Confidence Matrix, foundation level work, not copied code, not recycled concepts, and not the same thing with a new paint job.)

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

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