OPEN-SOURCE SCRIPT

PSAR Laboratory [DAFE]

1 953
PSAR Laboratory [DAFE]: The Ultimate Adaptive Trailing Stop & Reversal Engine
23 Advanced Algorithms. Adaptive Acceleration. Smart Flip Logic. Parabolic SAR Reimagined.

█ PHILOSOPHY: WELCOME TO THE LABORATORY
The standard Parabolic SAR, created by the legendary J. Welles Wilder Jr., is a tool of beautiful simplicity. But in today's complex, algorithm-driven markets, its simplicity is its fatal flaw. Its fixed acceleration and rigid flip logic cause it to fail precisely when you need it most: it whipsaws in choppy conditions and gives back too much profit in strong trends.

The PSAR Laboratory was not created to be just another PSAR. It was engineered to be the definitive evolution of Wilder's original concept. This is not an indicator; it is a powerful, interactive research environment. It is a sandbox where you, the trader, can move beyond the static "one-size-fits-all" approach and forge a PSAR that is perfectly adapted to your specific market, timeframe, and trading style.

We have deconstructed the very DNA of the Parabolic SAR and rebuilt it from the ground up, infusing it with modern quantitative techniques. The result is an institutional-grade suite of 23 distinct, mathematically diverse algorithms that dynamically control every aspect of the PSAR's behavior.

█ WHAT MAKES THIS A "LABORATORY"? THE CORE INNOVATIONS
This tool stands in a class of its own. It is a collection of what could be 23 separate indicators, all seamlessly integrated into one powerful engine.

The 23 Algorithm Engine: This is the heart of the Laboratory. Instead of one rigid formula, you have a library of 23 unique mathematical engines at your command. These algorithms are not simple tweaks; they are complete re-imaginings of how the PSAR should behave, based on concepts from information theory, digital signal processing, fractal geometry, and institutional analysis.

Truly Adaptive Acceleration (AF): The standard PSAR's "gas pedal" (the AF) is dumb; it accelerates at a fixed rate. Our algorithms make it intelligent. The AF can now speed up in clean, trending environments to lock in profits, and automatically slow down in choppy, chaotic conditions to avoid whipsaws.

Advanced Flip Confirmation Logic: Say goodbye to noise-driven flips. You are no longer at the mercy of a single wick touching the SAR. The Laboratory provides multiple layers of flip confirmation, including requiring a bar close beyond the SAR, a volume spike to validate the reversal, or even a multi-bar confirmation.

Comprehensive Noise Filtering Core: In a revolutionary step, you can apply one of over 30 advanced signal processing filters directly to the SAR output itself. From ultra-low-lag filters like the Hull MA and DAFE Spectral Laguerre to adaptive filters like KAMA and FRAMA, you can surgically remove noise while preserving the responsiveness of the core signal.

Integrated Performance Engine: How do you know which of the 23 algorithms is best for your market? You test it. The built-in Performance Dashboard is a comprehensive backtesting and analytics engine that tracks every trade, providing real-time data on Win Rate, Profit Factor, Max Drawdown, and more. It allows you to scientifically validate your chosen configuration.

█ A GUIDED TOUR OF THE ALGORITHMS: 23 PATHS TO AN EDGE
b]These 23 algorithms are not simple settings; they are distinct mathematical philosophies for how a Parabolic SAR should adapt to the market. They are grouped into three primary categories: those that adapt the Acceleration Factor (AF), those that enhance the Extreme Point (EP) detection, and those that redefine the Flip Logic.

[u]CATEGORY A: ACCELERATION FACTOR (AF) ADAPTATION[/u]
These algorithms dynamically change the "gas pedal" of the PSAR.

1. Volatility-Scaled AF
Core Concept: Treats volatility as market friction. The PSAR should be more forgiving in high-volatility environments.
How It Works: It calculates a Volatility Ratio by comparing the short-term ATR to the long-term ATR. If current volatility is high (ratio > 1), it reduces the AF Step. If volatility is low (ratio < 1), it increases the AF Step to trail tighter.
Ideal Use Case: The best all-rounder. Excellent for any market, especially those with clear shifts between high and low volatility regimes (like indices and crypto).

2. Efficiency Ratio (ER) AF
Core Concept: The PSAR should accelerate aggressively in clean, efficient trends and slow down dramatically in choppy, inefficient markets.
How It Works: It uses Kaufman's Efficiency Ratio (ER), which measures the net directional movement versus the total price movement. A high ER (near 1.0) signifies a pure trend, triggering a high AF multiplier. A low ER (near 0.0) signifies chop, triggering a low AF multiplier.
Ideal Use Case: Markets that alternate between strong trends and sideways chop. It is exceptionally good at surviving ranging periods.

3. Shannon Entropy AF
Core Concept: Uses Information Theory to measure market disorder. The PSAR should be conservative in chaos and aggressive in order.
How It Works: It calculates the Shannon Entropy of recent price changes. High entropy means the market is unpredictable ("chaotic"), causing the AF to slow down. Low entropy means the market is organized and trending, causing the AF to speed up.
Ideal Use Case: Advanced traders looking for a mathematically pure way to distinguish between a tradable trend and random noise.

4. Fractal Dimension (FD) AF
Core Concept: Measures the "jaggedness" or complexity of the price path. A smooth path is a trend; a jagged, space-filling path is chop.
How It Works: It calculates the Fractal Dimension of the price series. An FD near 1.0 is a smooth line (high AF). An FD near 1.5 is a random walk (low AF).
Ideal Use Case: Visually identifying the moment a smooth trend begins to break down into chaotic, unpredictable movement.

5. ADX-Gated AF
Core Concept: Uses the classic ADX indicator to confirm the presence of a trend before allowing the PSAR to accelerate.
How It Works: If the ADX value is above a "Strong" threshold (e.g., 25), the AF accelerates normally. If the ADX is below a "Weak" threshold (e.g., 15), the AF is "frozen" and will not increase, preventing the SAR from tightening up in a non-trending market.
Ideal Use Case: For classic trend-following purists who trust the ADX as their primary regime filter.

6. Kalman AF Estimator
Core Concept: A sophisticated signal processing algorithm that predicts the "true" optimal AF by filtering out price "noise."
How It Works: It treats the PSAR's AF as a state to be estimated. It makes a prediction, then corrects it based on how far the actual price deviates. It's like a GPS constantly refining its position. The "Process Noise" input controls how fast it thinks the AF can change, while "Measurement Noise" controls how much it trusts the price data.
Ideal Use Case: Smooth, high-inertia markets like commodities or major forex pairs. It creates an incredibly smooth and responsive AF.

7. Volume-Momentum AF
Core Concept: A trend's acceleration is only valid if confirmed by both volume and price momentum.
How It Works: The AF will only increase if a new Extreme Point is made on above-average volume AND the Rate of Change (ROC) of the price is aligned with the trend's direction.
Ideal Use Case: Any market with reliable volume data (stocks, futures, crypto). It's excellent for filtering out low-conviction moves.

8. Garman-Klass (GK) AF
Core Concept: Uses a more advanced, statistically efficient measure of volatility (Garman-Klass, which uses OHLC data) to adapt the AF.
How It Works: It modulates the AF based on whether the current GK volatility is higher or lower than its historical average. Unlike the standard Volatility-Scaled algo, it tends to slow down more in high volatility and speed up less in low volatility, making it more conservative.
Ideal Use Case: Traders who want a volatility-adaptive model that is more focused on risk reduction during volatile periods.

9. RSI-Modulated AF
Core Concept: The RSI can identify points of potential trend exhaustion or strong momentum.
How It Works: If a trend is bullish but the RSI enters the "Overbought" zone, the AF slows down, anticipating a pullback. Conversely, if the RSI is in the strong momentum mid-range (40-60), the AF is boosted to trail more aggressively.
Ideal Use Case: Mean-reversion traders or those who want to automatically loosen their trail stop near potential exhaustion points.

10. Bollinger Squeeze AF
Core Concept: A Bollinger Band Squeeze signals a period of volatility compression, often preceding an explosive breakout.
How It Works: When the algorithm detects that the Bollinger Band Width is in a "Squeeze" (below a certain historical percentile), it boosts the AF in anticipation of a fast move, allowing the PSAR to catch the breakout quickly.
Ideal Use Case: Breakout traders. This algorithm primes the PSAR to be maximally responsive right at the moment a breakout is most likely.

11. Keltner Adaptive AF
Core Concept: Keltner Channels provide a robust measure of a trend's "normal" volatility channel.
How It Works: When price is trading strongly outside the Keltner Channel, it's considered a powerful trend, and the AF is boosted. When price falls back inside the channel, it's considered a consolidation or pullback, and the AF is slowed down.
Ideal Use Case: Trend followers who use channel breakouts as their primary confirmation.

12. Choppiness-Gated AF
Core Concept: Uses the Choppiness Index to quantify whether the market is trending or consolidating.
How It Works: If the Choppiness Index is below the "Trend" threshold (e.g., 38.2), the AF is boosted. If it's above the "Range" threshold (e.g., 61.8), the AF is significantly reduced.
Ideal Use Case: A more responsive alternative to the ADX-Gated algorithm for distinguishing between trending and ranging markets.

13. VIDYA-Style AF
Core Concept: Uses a Chande Momentum Oscillator (CMO) to create a variable-speed acceleration factor.
How It Works: The absolute value of the CMO is used to create a dynamic smoothing constant. Strong momentum (high absolute CMO) results in a faster, more responsive AF. Weak momentum results in a slower, smoother AF.
Ideal Use Case: Momentum traders who want their trailing stop's speed directly tied to the momentum of the price itself.

14. Hilbert Cycle AF
Core Concept: Uses Ehlers' Hilbert Transform to extract the dominant cycle period of the market and synchronizes the PSAR with it.
How It Works: It dynamically adjusts the AF based on the detected cycle period (shorter cycles = faster AF) and can also modulate it based on the current phase within that cycle (e.g., accelerate faster near cycle tops/bottoms).
Ideal Use Case: Markets with clear cyclical behavior, like commodities and some forex pairs.
CATEGORY B: EXTREME POINT (EP) ENHANCEMENT
These algorithms make the detection of new highs/lows more intelligent.

15. Volume-Weighted EP
Core Concept: A new high or low is more significant if it occurs on high volume.
How It Works: It can be configured to only accept a new EP if the volume on that bar is above average. It can also "weight" the EP by volume, pushing it further out on high-volume bars.
Ideal Use Case: Filtering out weak, low-conviction price probes in markets with reliable volume.

16. Wavelet Filtered EP
Core Concept: Uses wavelet decomposition (a signal processing technique) to separate the underlying trend from high-frequency noise.
How It Works: It calculates a smoothed, wavelet-filtered version of the price. A new EP is only registered if the actual high/low significantly exceeds this smoothed baseline, effectively ignoring minor noise spikes.
Ideal Use Case: Noisy markets where small, insignificant wicks can cause the AF to accelerate prematurely.

17. ATR-Validated EP
Core Concept: A new EP should represent a meaningful move, not just a one-tick poke.
How It Works: It requires a new high/low to exceed the previous EP by a minimum amount, defined as a multiple of the current ATR. This ensures only volatility-significant advances are counted.
Ideal Use Case: A simple, robust way to filter out "noise" EPs and slow down the AF's acceleration in choppy conditions.

18. Statistical EP Filter
Core Concept: A new EP is only valid if the price change that created it is statistically significant.
How It Works: It calculates the Z-Score of the bar's price change relative to recent history. A new EP is only accepted if its Z-Score exceeds a certain threshold (e.g., 1.5 sigma), meaning it was an unusually strong move.
Ideal Use Case: For quantitative traders who want to ensure their trailing stop only tightens in response to statistically meaningful price action.

CATEGORY C: FLIP LOGIC & CONFIRMATION
These algorithms change the very rules of when and why the PSAR reverses.

19. Dual-PSAR Gate
Core Concept: Uses two PSARs—one fast and one slow—to confirm a reversal.
How It Works: A flip signal for the main PSAR is only considered valid if both the fast (sensitive) PSAR and the slow (structural) PSAR have flipped. This acts as a powerful trend filter.
Ideal Use Case: An excellent method for reducing whipsaws. It forces the PSAR to wait for both short-term and longer-term momentum to align before signaling a reversal.

20. MTF Coherence PSAR
Core Concept: Do not flip against the higher timeframe macro trend.
How It Works: It pulls PSAR data from two higher timeframes. A flip is only allowed if the new direction does not contradict the trend on at least one (or both) of those higher timeframes. It also boosts the AF when all timeframes are aligned.
Ideal Use Case: The ultimate tool for multi-timeframe traders who want to ensure their entries and exits are in sync with the bigger picture.

21. Momentum-Gated Flip
Core Concept: A reversal is only valid if it is supported by a significant surge of momentum.
How It Works: A price cross of the SAR is not enough. The script also requires the Rate of Change (ROC) to exceed a certain threshold for a set number of bars, confirming that there is real force behind the reversal.
Ideal Use Case: Filtering out weak, drifting reversals and only taking signals that are initiated with explosive power.

22. Close-Only PSAR
Core Concept: Wicks are noise; the bar's close is the final decision.
How It Works: This algorithm modifies the flip logic to ignore wicks. A flip only occurs if one or more bars close beyond the SAR line.
Ideal Use Case: One of the most effective and simple ways to reduce false signals from volatile wicks. A fantastic default choice for any trader.

23. Ultimate PSAR Consensus
Core Concept: The highest conviction signal comes from the agreement of multiple, diverse mathematical models.
How It Works: This is the capstone algorithm. It runs a "vote" between a selection of the top-performing algorithms (e.g., Volatility-Scaled, Efficiency Ratio, Dual-PSAR). A flip is only signaled if a majority consensus is reached. It can even weight the votes based on each algorithm's recent performance.
Ideal Use Case: For traders who want the absolute highest level of confirmation and are willing to accept fewer, but more robust, signals.

█ PART II: THE NOISE FILTERING CORE - The Shield
This is a revolutionary feature that allows you to apply a second layer of signal processing directly to the SAR line itself, surgically removing noise before the flip logic is even considered.

FILTER CATEGORIES
Basic Filters (SMA, EMA, WMA, RMA): The classic moving averages. They provide basic smoothing but introduce significant lag. Best used for educational purposes.

Low-Lag Filters (DEMA, TEMA, Hull MA, ZLEMA): A family of filters designed to reduce the lag inherent in basic moving averages. The Hull MA is a standout, offering a superb balance of smoothness and responsiveness.

Adaptive Filters (KAMA, VIDYA, FRAMA): These are "smart" filters. They automatically adjust their smoothing level based on market conditions. They will be very smooth in choppy markets and become highly responsive in trending markets.

Advanced DSP & DAFE Filters: This is the pinnacle of signal processing.
Ehlers Filters (SuperSmoother, 2-Pole, 3-Pole): Based on the work of John Ehlers, these use digital signal processing techniques to remove high-frequency noise with minimal lag.

Gaussian & ALMA: These use a bell-curve weighting, giving the most importance to recent data in a smooth, non-linear fashion.

DAFE Spectral Laguerre: A proprietary, non-linear filter that uses a feedback loop and adapts its "gamma" based on volatility, providing exceptional tracking in all market conditions.

How to Choose a Filter
Start with "None": First, find an algorithm you like with no filtering to understand its raw behavior.
Introduce Low Lag: If you are getting too many whipsaws from noise, apply a short-length Hull MA (e.g., 5-8). This is often the best solution.
Go Adaptive: If your market has very distinct trend/chop regimes, try an Adaptive KAMA.
Maximum Purity: For the smoothest possible output with excellent responsiveness, use the DAFE Spectral Laguerre or Ehlers SuperSmoother.

█ THE VISUAL EXPERIENCE: DATA AS ART
The PSAR Laboratory is not just functional; it is beautiful. The visualization engine is designed to provide you with an intuitive, at-a-glance understanding of the market's state.

Algorithm-Specific Theming: Each of the 23 algorithms comes with its own unique, professionally designed color palette. This not only provides visual variety but allows you to instantly recognize which engine is active.

Dynamic Glow Effects: For many algorithms, the PSAR dots will emit a soft "glow." The brightness and color of this glow are not random; they are tied to a key metric of the active algorithm (e.g., trend strength, volatility, consensus), providing a subtle, visual cue about the health of the trend.

Adaptive Volatility Bands: Certain algorithms will display dynamic bands around the PSAR. These are not standard deviation bands; their width is controlled by the specific logic of the active algorithm, showing you a visual representation of the market's expected range or energy level.

Secondary Reference Lines: For algorithms like the Dual-PSAR or MTF Coherence, a secondary line will be plotted on the chart, giving you a clear visual of the underlying data (e.g., the slow PSAR, the HTF trend) that is driving the decision-making process.

█ THE MASTER DASHBOARD: YOUR MISSION CONTROL
The comprehensive dashboard is your unified command center for analysis and performance tracking.

Engine Status: See the currently selected Algorithm, the active Noise Filter, the Trend direction, and a real-time progress bar of the current Acceleration Factor (AF).

Algorithm-Specific Metrics: This is the most powerful section. It displays the key real-time data from the currently active algorithm. If you're using "Shannon Entropy," you'll see the Entropy score. If you're using "ADX-Gated," you'll see the ADX value. This gives you a direct, quantitative look under the hood.

Performance Readout: When enabled, this section provides a full breakdown of your backtesting results, including Win Rate, Profit Factor, Net P&L, Max Drawdown, and your current trade status.

█ DEVELOPMENT PHILOSOPHY
The PSAR Laboratory was born from a deep respect for Wilder's original work and a relentless desire to push it into the 21st century. We believe that in modern markets, static tools are obsolete. The future of trading lies in adaptation. This indicator is for the serious trader, the tinkerer, the scientist—the individual who is not content with a black box, but who seeks to understand, test, and refine their edge with surgical precision. It is a tool for forging, not just following.

The PSAR Laboratory is designed to be the ultimate tool for that evolution, allowing you to discover and codify the rules that truly fit you.

█ DISCLAIMER AND BEST PRACTICES
THIS IS A TOOL, NOT A STRATEGY: This indicator provides a sophisticated trailing stop and reversal signal. It must be integrated into a complete trading plan that includes risk management, position sizing, and your own contextual analysis.
TEST, DON'T GUESS: The power of this tool is its adaptability. Use the Performance Dashboard to rigorously test different algorithms and settings on your chosen asset and timeframe. Find what works, and build your strategy around that data.
START SIMPLE: Begin with the "Volatility-Scaled AF" algorithm, as it is a powerful and intuitive all-rounder. Once you are comfortable, begin experimenting with other engines.
RISK MANAGEMENT IS PARAMOUNT: All trading involves substantial risk. The backtesting results are hypothetical and do not account for slippage or psychological factors. Never risk more capital than you are prepared to lose.

"I don't think traders can follow rules for very long unless they reflect their own trading style. Eventually, a breaking point is reached and the trader has to quit or change, or find a new set of rules he can follow. This seems to be part of the process of evolution and growth of a trader."
— Ed Seykota, Market Wizard

Taking you to school. - Dskyz, Trade with Volume. Trade with Density. Trade with DAFE

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.