OPEN-SOURCE SCRIPT
WHF - Wave Health and Failure

WHF — Neural Adaptive Wave Health and Failure Engine [DAFE]
This is not an indicator. This is a unified intelligence system. It is a super-system built upon a suite of seven specialized DAFE libraries, designed to analyze the market through the lens of physics, machine learning, and quantitative finance. Its core thesis is revolutionary: Assume every trend is failing until it proves itself healthy.
█ CHAPTER 1: THE PHILOSOPHY - A PARADIGM SHIFT IN TREND ANALYSIS
Traditional trend analysis is a discipline of hope and confirmation bias. We see a series of higher highs and higher lows, and we assume the trend is healthy. We buy the dip, only to see the structure collapse. We are taught to ignore failed moves as "noise." This is a fundamental, costly mistake.
The WHF (Wave Health & Failure) Engine is built on a radically different, institutional-grade philosophy: A trend's failure is not noise; it is a first-class signal. The moments where momentum fails, where volume fails to confirm price, where the underlying structure fractures—these are the most information-rich moments in any market. They are the moments that signal a change of control from one party to another.
This indicator is not a simple "mashup." It is the seamless, hierarchical integration of seven distinct, professional-grade DAFE libraries, each a masterpiece in its own right. It creates a multi-layered, artificially intelligent system that doesn't just measure a trend's existence; it performs a deep, diagnostic health check on every market wave. It quantifies its efficiency, its consistency, its structural integrity, and its underlying institutional support. The result is a system that not only helps you ride healthy, powerful trends but, more importantly, provides you with high-probability reversal signals at the precise moment a trend's health has critically failed.
█ CHAPTER 2: THE UNIFIED FIELD - A DEEP DIVE INTO THE 7 LIBRARIES
The unparalleled power of the WHF Engine comes from the synergy of its seven integrated libraries. Each library acts as a specialized "organ," performing a critical function, with the main indicator acting as the "central nervous system" that synthesizes their intelligence.
1. The Wick Pressure Kernel (wpk): The Physics Engine
This is the system's eyes on the microstructure. The WPK is a physics and machine learning engine that reconstructs the "invisible auction" inside every candle. It analyzes the geometry of wicks versus the body to estimate institutional Delta, calculates the "Kinetic Force" of each bar, and tracks the "Siege Decay" of support and resistance levels. It provides the deep, contextual data on order flow pressure that is essential for a true health assessment.
2. The Neural Pattern Library (pattern): The Recognition Engine
This is the system's pattern recognition brain. It is a self-learning library that doesn't just find patterns; it tracks their outcomes via reinforcement learning. It uses its own Dynamic Volatility Scaling (DVS) to adapt its scanning to the market's character, identifying candlestick, geometric, and market structure patterns, and then scoring them with a "Neural Confidence" based on their recent performance.
3. The Reinforcement Learning Library (ml): The Tactical AI
This is the core tactical decision-making brain. It is a true Reinforcement Learning engine, equipped with advanced algorithms like Actor-Critic and Q-Learning. In the WHF, it is fed a rich state vector of over a dozen market metrics (RSI, ATR, Wave Health, WPK Anomaly Score, etc.) and learns, through trial and error against historical data, to map these complex states to an optimal action (e.g., Strong Long, Neutral, Fade Short).
4. The Strategy Portfolio Library (spa): The Strategic AI
This is the high-level portfolio manager. It takes the signals from different internal "strategies" (e.g., a "Healthy Trend Continuation" strategy, a "Failed Wave Fade" strategy) and runs them in parallel shadow portfolios. It uses Thompson Sampling to dynamically allocate trust to the strategy that is performing best in the current market regime. It is the system's risk manager and strategic overlay.
5. The ML-SPA Bridge Library (bridge): The Synapse
This is the master communication protocol that fuses the tactical ML engine with the strategic SPA engine. The ML proposes a set of actions, the bridge translates them into a portfolio of micro-strategies, and the SPA selects the winner based on performance. The final P&L is then routed back through the bridge as a reward signal to train the ML engine. It creates a hybrid super-system that is more robust than either AI operating alone.
6. The Visuals Library (viz): The Artist
Data without intuition is useless. This library is an AI-powered artist. It takes the final, synthesized data from the WHF engine and renders it using intelligent, context-aware visualization techniques. It's responsible for the health-coded Neural Zigzag, the dynamic glow effects, and the adaptive candle coloring.
7. The Dashboard Library (dafe): The AI Assistant
This is the conversational interface. It takes the final, high-level analysis from the entire system and presents it in a human-readable format. The ASCII art "AI Assistant" provides a summary of the market state, its "mood" based on confidence, and a list of recommended actions, transforming complex quantitative data into clear, actionable intelligence.
█ CHAPTER 3: THE WAVE HEALTH ALGORITHM - THE THREE PILLARS OF A TREND
At its core, the WHF engine calculates a "Wave Health" score from 0 to 100 based on three proprietary pillars:
Relative Efficiency Quotient (REQ): This measures the "bang for the buck" of a price move. It asks: How much directional price progress was achieved relative to the total volume and volatility expended? A trend that grinds higher on massive, overlapping candles is inefficient and unhealthy. A trend that moves cleanly on focused volume is efficient and healthy.
Participation Consistency (PC): This measures the "fuel supply" of a trend. It analyzes the trend of volume and the correlation between price direction and order flow delta. A healthy trend is supported by consistent, confirming participation. A trend where volume is drying up or where delta is diverging from price is starved of fuel and likely to fail.
Structural Extension (SE): This measures the geometric purity of the trend. It uses concepts like "Churn" (high volume, low range) and "Failed Follow-Through" to penalize price action that is choppy, overlapping, and struggling to extend. A healthy trend should make clean, decisive progress.
These three scores are weighted and combined into a single, smoothed "Wave Health" line. A score above 70 is a "HEALTHY" trend. A score between 40 and 70 is "FRAGILE." A score below 40 signals a "FAILED" wave, a high-probability setup for a reversal or "fade" trade.
█ CHAPTER 4: A VISUAL GUIDE - DECODING THE DISPLAYS
THE MAIN CHART OVERLAYS
The Neural Zigzag: This is not a standard zigzag. It is the visual representation of the market's wave structure, with each leg of the wave dynamically colored by its calculated health score: bright green for "Healthy," cautionary orange for "Fragile," and alarming red for "Failed."
The Health Trail: An innovative, dynamic trailing stop line displayed in a separate pane. Its distance from the price is a direct function of the current Wave Health. In a healthy trend, the trail is aggressive and tight. As health deteriorates, the trail automatically loosens, giving the price more room and preventing a premature stop-out.
Health Zones: The entire chart background can be subtly tinted green or red, providing an atmospheric, at-a-glance indication of the current health regime.
Signal Labels: Clear, professional labels appear for "HEALTHY" trend continuation signals and, uniquely, for "FAILED" trend fade (reversal) signals, complete with the system's final confidence score.
THE DASHBOARD & AI ASSISTANT
***Only one dashboard can be active at any given time
The Main Dashboard: Your quantitative command center. It provides a numerical breakdown of the overall Wave Health score and the scores of its three pillars (REQ, PC, SE). It also displays the final, synthesized output from the entire ML-SPA-WPK system, including the final direction, confidence, and recommended action.
The Library Validation Panel: In a commitment to transparency, this special section of the dashboard shows the live connection status of all seven integrated DAFE libraries, confirming that the entire super-system is active and synchronized.

The AI Assistant: This unique panel features a conversational AI (powered by the DafeDashboardLib) that translates the complex quantitative analysis into human-readable insights. It states its "mood" based on system confidence and provides a list of actionable thoughts and recommendations.

█ CHAPTER 5: DEVELOPMENT PHILOSOPHY
The WHF Engine is the culmination of the DAFE philosophy: that the future of trading analysis lies in the intelligent, hierarchical fusion of multiple, specialized expert systems. By unifying our most advanced libraries for machine learning, portfolio management, microstructure analysis, and visualization, we have created a tool that is not just a collection of features, but a cohesive, intelligent entity. It is for the serious trader who understands that the market is a complex, adaptive system and demands a tool that is equally sophisticated.
This system is designed to be a tool for that discipline. By providing an objective, data-driven, and multi-faceted health assessment of every market move, it helps to remove the hope, fear, and guesswork that plagues so many traders, allowing you to act with the cold, calculated confidence of a machine.
█ DISCLAIMER AND BEST PRACTICES
THIS IS AN ADVANCED ANALYTICAL TOOL: This indicator provides a highly sophisticated market analysis, not direct financial advice. It is a decision-support tool.
RISK MANAGEMENT IS PARAMOUNT: All trading involves substantial risk. The AI's decisions are based on statistical probabilities learned from past data.
UNDERSTAND THE CORE THESIS: The most powerful signals from this indicator are often the "Failed" signals. Learning to trade the failure of a weak move is a professional-grade skill that this indicator is specifically designed to teach and enable.
USE THE DASHBOARD: The dashboard is your window into the AI's "mind." Before taking a signal, check the dashboard. Is the overall Wave Health strong? Is the confidence high? Are the underlying libraries all validated and active? Use the full spectrum of data to inform your decisions.
"The key to trading success is emotional discipline. If intelligence were the key, there would be a lot more people making money trading."
— Victor Sperandeo, Market Wizard
Get on my level — Dskyz, Trade with insight. Trade with anticipation.
This is not an indicator. This is a unified intelligence system. It is a super-system built upon a suite of seven specialized DAFE libraries, designed to analyze the market through the lens of physics, machine learning, and quantitative finance. Its core thesis is revolutionary: Assume every trend is failing until it proves itself healthy.
█ CHAPTER 1: THE PHILOSOPHY - A PARADIGM SHIFT IN TREND ANALYSIS
Traditional trend analysis is a discipline of hope and confirmation bias. We see a series of higher highs and higher lows, and we assume the trend is healthy. We buy the dip, only to see the structure collapse. We are taught to ignore failed moves as "noise." This is a fundamental, costly mistake.
The WHF (Wave Health & Failure) Engine is built on a radically different, institutional-grade philosophy: A trend's failure is not noise; it is a first-class signal. The moments where momentum fails, where volume fails to confirm price, where the underlying structure fractures—these are the most information-rich moments in any market. They are the moments that signal a change of control from one party to another.
This indicator is not a simple "mashup." It is the seamless, hierarchical integration of seven distinct, professional-grade DAFE libraries, each a masterpiece in its own right. It creates a multi-layered, artificially intelligent system that doesn't just measure a trend's existence; it performs a deep, diagnostic health check on every market wave. It quantifies its efficiency, its consistency, its structural integrity, and its underlying institutional support. The result is a system that not only helps you ride healthy, powerful trends but, more importantly, provides you with high-probability reversal signals at the precise moment a trend's health has critically failed.
█ CHAPTER 2: THE UNIFIED FIELD - A DEEP DIVE INTO THE 7 LIBRARIES
The unparalleled power of the WHF Engine comes from the synergy of its seven integrated libraries. Each library acts as a specialized "organ," performing a critical function, with the main indicator acting as the "central nervous system" that synthesizes their intelligence.
1. The Wick Pressure Kernel (wpk): The Physics Engine
This is the system's eyes on the microstructure. The WPK is a physics and machine learning engine that reconstructs the "invisible auction" inside every candle. It analyzes the geometry of wicks versus the body to estimate institutional Delta, calculates the "Kinetic Force" of each bar, and tracks the "Siege Decay" of support and resistance levels. It provides the deep, contextual data on order flow pressure that is essential for a true health assessment.
2. The Neural Pattern Library (pattern): The Recognition Engine
This is the system's pattern recognition brain. It is a self-learning library that doesn't just find patterns; it tracks their outcomes via reinforcement learning. It uses its own Dynamic Volatility Scaling (DVS) to adapt its scanning to the market's character, identifying candlestick, geometric, and market structure patterns, and then scoring them with a "Neural Confidence" based on their recent performance.
3. The Reinforcement Learning Library (ml): The Tactical AI
This is the core tactical decision-making brain. It is a true Reinforcement Learning engine, equipped with advanced algorithms like Actor-Critic and Q-Learning. In the WHF, it is fed a rich state vector of over a dozen market metrics (RSI, ATR, Wave Health, WPK Anomaly Score, etc.) and learns, through trial and error against historical data, to map these complex states to an optimal action (e.g., Strong Long, Neutral, Fade Short).
4. The Strategy Portfolio Library (spa): The Strategic AI
This is the high-level portfolio manager. It takes the signals from different internal "strategies" (e.g., a "Healthy Trend Continuation" strategy, a "Failed Wave Fade" strategy) and runs them in parallel shadow portfolios. It uses Thompson Sampling to dynamically allocate trust to the strategy that is performing best in the current market regime. It is the system's risk manager and strategic overlay.
5. The ML-SPA Bridge Library (bridge): The Synapse
This is the master communication protocol that fuses the tactical ML engine with the strategic SPA engine. The ML proposes a set of actions, the bridge translates them into a portfolio of micro-strategies, and the SPA selects the winner based on performance. The final P&L is then routed back through the bridge as a reward signal to train the ML engine. It creates a hybrid super-system that is more robust than either AI operating alone.
6. The Visuals Library (viz): The Artist
Data without intuition is useless. This library is an AI-powered artist. It takes the final, synthesized data from the WHF engine and renders it using intelligent, context-aware visualization techniques. It's responsible for the health-coded Neural Zigzag, the dynamic glow effects, and the adaptive candle coloring.
7. The Dashboard Library (dafe): The AI Assistant
This is the conversational interface. It takes the final, high-level analysis from the entire system and presents it in a human-readable format. The ASCII art "AI Assistant" provides a summary of the market state, its "mood" based on confidence, and a list of recommended actions, transforming complex quantitative data into clear, actionable intelligence.
█ CHAPTER 3: THE WAVE HEALTH ALGORITHM - THE THREE PILLARS OF A TREND
At its core, the WHF engine calculates a "Wave Health" score from 0 to 100 based on three proprietary pillars:
Relative Efficiency Quotient (REQ): This measures the "bang for the buck" of a price move. It asks: How much directional price progress was achieved relative to the total volume and volatility expended? A trend that grinds higher on massive, overlapping candles is inefficient and unhealthy. A trend that moves cleanly on focused volume is efficient and healthy.
Participation Consistency (PC): This measures the "fuel supply" of a trend. It analyzes the trend of volume and the correlation between price direction and order flow delta. A healthy trend is supported by consistent, confirming participation. A trend where volume is drying up or where delta is diverging from price is starved of fuel and likely to fail.
Structural Extension (SE): This measures the geometric purity of the trend. It uses concepts like "Churn" (high volume, low range) and "Failed Follow-Through" to penalize price action that is choppy, overlapping, and struggling to extend. A healthy trend should make clean, decisive progress.
These three scores are weighted and combined into a single, smoothed "Wave Health" line. A score above 70 is a "HEALTHY" trend. A score between 40 and 70 is "FRAGILE." A score below 40 signals a "FAILED" wave, a high-probability setup for a reversal or "fade" trade.
█ CHAPTER 4: A VISUAL GUIDE - DECODING THE DISPLAYS
THE MAIN CHART OVERLAYS
The Neural Zigzag: This is not a standard zigzag. It is the visual representation of the market's wave structure, with each leg of the wave dynamically colored by its calculated health score: bright green for "Healthy," cautionary orange for "Fragile," and alarming red for "Failed."
The Health Trail: An innovative, dynamic trailing stop line displayed in a separate pane. Its distance from the price is a direct function of the current Wave Health. In a healthy trend, the trail is aggressive and tight. As health deteriorates, the trail automatically loosens, giving the price more room and preventing a premature stop-out.
Health Zones: The entire chart background can be subtly tinted green or red, providing an atmospheric, at-a-glance indication of the current health regime.
Signal Labels: Clear, professional labels appear for "HEALTHY" trend continuation signals and, uniquely, for "FAILED" trend fade (reversal) signals, complete with the system's final confidence score.
THE DASHBOARD & AI ASSISTANT
***Only one dashboard can be active at any given time
The Main Dashboard: Your quantitative command center. It provides a numerical breakdown of the overall Wave Health score and the scores of its three pillars (REQ, PC, SE). It also displays the final, synthesized output from the entire ML-SPA-WPK system, including the final direction, confidence, and recommended action.
The Library Validation Panel: In a commitment to transparency, this special section of the dashboard shows the live connection status of all seven integrated DAFE libraries, confirming that the entire super-system is active and synchronized.
The AI Assistant: This unique panel features a conversational AI (powered by the DafeDashboardLib) that translates the complex quantitative analysis into human-readable insights. It states its "mood" based on system confidence and provides a list of actionable thoughts and recommendations.
█ CHAPTER 5: DEVELOPMENT PHILOSOPHY
The WHF Engine is the culmination of the DAFE philosophy: that the future of trading analysis lies in the intelligent, hierarchical fusion of multiple, specialized expert systems. By unifying our most advanced libraries for machine learning, portfolio management, microstructure analysis, and visualization, we have created a tool that is not just a collection of features, but a cohesive, intelligent entity. It is for the serious trader who understands that the market is a complex, adaptive system and demands a tool that is equally sophisticated.
This system is designed to be a tool for that discipline. By providing an objective, data-driven, and multi-faceted health assessment of every market move, it helps to remove the hope, fear, and guesswork that plagues so many traders, allowing you to act with the cold, calculated confidence of a machine.
█ DISCLAIMER AND BEST PRACTICES
THIS IS AN ADVANCED ANALYTICAL TOOL: This indicator provides a highly sophisticated market analysis, not direct financial advice. It is a decision-support tool.
RISK MANAGEMENT IS PARAMOUNT: All trading involves substantial risk. The AI's decisions are based on statistical probabilities learned from past data.
UNDERSTAND THE CORE THESIS: The most powerful signals from this indicator are often the "Failed" signals. Learning to trade the failure of a weak move is a professional-grade skill that this indicator is specifically designed to teach and enable.
USE THE DASHBOARD: The dashboard is your window into the AI's "mind." Before taking a signal, check the dashboard. Is the overall Wave Health strong? Is the confidence high? Are the underlying libraries all validated and active? Use the full spectrum of data to inform your decisions.
"The key to trading success is emotional discipline. If intelligence were the key, there would be a lot more people making money trading."
— Victor Sperandeo, Market Wizard
Get on my level — Dskyz, Trade with insight. Trade with anticipation.
Skrip open-source
Dengan semangat TradingView yang sesungguhnya, pembuat skrip ini telah menjadikannya sebagai sumber terbuka, sehingga para trader dapat meninjau dan memverifikasi fungsinya. Salut untuk penulisnya! Meskipun Anda dapat menggunakannya secara gratis, perlu diingat bahwa penerbitan ulang kode ini tunduk pada Tata Tertib kami.
Pernyataan Penyangkalan
Informasi dan publikasi ini tidak dimaksudkan, dan bukan merupakan, saran atau rekomendasi keuangan, investasi, trading, atau jenis lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Ketentuan Penggunaan.
Skrip open-source
Dengan semangat TradingView yang sesungguhnya, pembuat skrip ini telah menjadikannya sebagai sumber terbuka, sehingga para trader dapat meninjau dan memverifikasi fungsinya. Salut untuk penulisnya! Meskipun Anda dapat menggunakannya secara gratis, perlu diingat bahwa penerbitan ulang kode ini tunduk pada Tata Tertib kami.
Pernyataan Penyangkalan
Informasi dan publikasi ini tidak dimaksudkan, dan bukan merupakan, saran atau rekomendasi keuangan, investasi, trading, atau jenis lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Ketentuan Penggunaan.