PINE LIBRARY
DafeLiquidityEngine

DafeLiquidityEngine: The Institutional Liquidity & Microstructure Engine
This is not a volume indicator. This is a complete, institutional-grade quantitative laboratory for the analysis of market liquidity. It is a toolkit for seeing the invisible architecture of the order book and trading the cause, not the effect.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND VOLUME, INTO LIQUIDITY
The standard volume bar is a lie. It tells you that the market was active, but it tells you nothing about the quality of that activity. Was it a deep, liquid market that could easily absorb large orders, or a thin, fragile market on the verge of a violent cascade? Was the volume driven by informed, institutional flow, or by reactive, retail panic?
The DafeLiquidityEngine was created to answer these critical questions. This library is not a simple "mashup" of existing indicators; it is a foundational, original work that brings a suite of concepts from academic and institutional quantitative finance directly into the Pine Script environment. Its purpose is to move beyond the one-dimensional view of volume and provide a multi-faceted, high-resolution picture of the market's true, underlying liquidity structure.
b]This is not an indicator that gives buy or sell signals. It is a far more powerful tool: a measurement device. It provides you with the crucial intelligence to assess the quality of the market environment. It tells you when liquidity is deep and signals can be trusted, and when liquidity has vanished and risk is extreme. It is the definitive engine for understanding the hidden structure of the market auction.
█ CHAPTER 2: THE CORE INNOVATIONS - A UNIVERSITY-LEVEL TOOLKIT
This library's value is rooted in its implementation of sophisticated, academically recognized models for liquidity and price impact, many for the first time on this platform.
Multi-Scale Delta Divergence Engine: The engine doesn't just calculate one Cumulative Volume Delta (CVD). It calculates two simultaneously: a fast delta (representing scalpers and retail flow) and a slow delta (representing institutional accumulation/distribution). Its true genius lies in its ability to analyze the divergence between these two flows, classifying the market into one of five distinct states like "Absorption" (institutions absorbing retail selling) or "Stealth" (institutions quietly building a position).
Advanced Bid-Ask Spread Estimation: Without access to Level 2 data, how can you know the spread? This library uses two renowned academic models—the Corwin-Schultz estimator (using high-low data) and the Roll spread estimator (using serial covariance)—to create a high-fidelity proxy for the live bid-ask spread. This is a direct measure of market tightness.
Amihud Illiquidity Ratio: A classic, powerful measure of illiquidity. It calculates the absolute price return per dollar of volume traded. A high Amihud score means that even small amounts of volume are causing large, violent price swings—a clear sign of a dangerously illiquid market.
Kyle's Lambda (Price Impact): This is the professional's measure of market impact. Lambda calculates how much the price moves for every unit of signed order flow. A high Lambda value indicates a "thin" order book where a single large market order can cause a significant price cascade. It is a direct measure of market fragility.
The Volume Clock Engine: This module analyzes the market in "volume time" instead of chronological time. It detects volume "droughts" and "floods," measures the "participation rate" against historical norms, and analyzes the acceleration of volume to determine if a move is gaining or losing institutional support.
The Composite Liquidity Regime: The capstone of the engine. It synthesizes the intelligence from all other modules into a single, unified classification of the market's liquidity state, from "Deep" and "Normal" to "Thin," "Desert," and the dreaded "Frozen." For developers, this provides a simple, powerful output: a risk_multiplier and a signal_penalty to automatically adjust position sizing and signal confidence based on the current liquidity environment.
█ CHAPTER 3: A DEEP DIVE INTO THE ENGINE'S MODULES
This is your guide to the engine room. Each module is a specialized analytical tool.
The DeltaState Module: This is the heart of the divergence engine. It provides you with the raw and Z-scored values for both fast and slow delta, their velocity, and the final divergence classification ("absorption," "exhaustion," etc.) along with a confidence score. This is your primary tool for detecting conflicts between retail and institutional flow.
The SpreadState Module: This gives you a direct, quantitative measure of market tightness. Use the spread_z score to see if the current bid-ask spread is statistically wide or tight, and the spread_regime to know if the market is "Blown" (extremely wide and risky) or "Tight" (liquid and efficient).
The AmihudState & KyleState Modules: These are your professional-grade risk assessment tools. A rising illiquidity_z score from Amihud is a clear warning that the market is becoming fragile. A rising lambda_z from Kyle's Lambda tells you that price impact is increasing, and the risk of a slippage cascade is high.
The VolumeClockState Module: This is your lens into market participation. The vol_clock_regime ("drought," "low," "normal," "elevated," "flood") tells you the character of the current volume, while the vol_trend_strength provides a measure of the momentum of participation.
The LiquidityRegime Module: This is the final, synthesized verdict. It provides a single, easy-to-use regime name ("Flush," "Deep," "Normal," "Thin," "Desert," "Frozen") that encapsulates the combined intelligence of the entire system. Crucially, it also outputs the risk_multiplier and signal_penalty—direct, actionable factors you can use to modulate your own strategy's behavior.
█ CHAPTER 4: THE DEVELOPER'S MASTERCLASS - IMPLEMENTATION GUIDE
The DafeLiquidityEngine is a professional framework designed for seamless integration. This guide provides the complete instructions for leveraging its power.
[u]PART I: THE INPUTS TEMPLATE (THE CONTROL PANEL)[/u]
While this is a library, a high-quality indicator built upon it would expose these parameters to the user for fine-tuning. This is the recommended input structure.
Pine Script®
// ╔═════════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════════╝
// 1. IMPORT THE LIBRARY
Pine Script®
// 2. INITIALIZE THE ENGINE (happens only on the first bar)
// The 'engine' must be a 'var' to retain its state across bars.
Pine Script®
// 3. UPDATE THE ENGINE (runs on every bar)
// Feed the current bar's OHLCV data into the engine. It handles all internal calculations.
Pine Script®
// 4. EXTRACT INTELLIGENCE (runs on every bar)
// Get the final, synthesized output state from the engine.
Pine Script®
// 5. USE THE INTELLIGENCE TO BUILD YOUR LOGIC
// --- Example 1: Creating a Sophisticated Signal Filter ---
Pine Script®
// The liquidity engine provides a simple penalty score. 1.0 = good liquidity, 0.2 = bad liquidity.
Pine Script®
// Only trust the signal if liquidity is good enough.
Pine Script®
// --- Example 2: Dynamic Position Sizing ---
Pine Script®
// The engine provides a risk multiplier. 1.0 = normal risk, 0.3 = high risk (reduce size).
Pine Script®
// Now use 'final_position_size' in your strategy logic.
// --- Example 3: Building a Divergence-Based Strategy ---
Pine Script®
// This is a high-confidence signal that institutions are quietly buying while price is falling.
// A powerful setup for a long entry.
Pine Script®
// --- Example 4: Displaying the State on a Dashboard ---
Pine Script®
█ DEVELOPMENT PHILOSOPHY
The DafeLiquidityEngine was born from a single, guiding principle: liquidity is the fuel of the market. Price cannot move without it, and its absence or presence dictates the character of every trading session. This library provides, for the first time, a comprehensive, institutional-grade toolkit for quantifying this elusive but critical variable. It is a tool for the serious developer and the quantitative trader who is not satisfied with surface-level analysis, but who seeks to understand the deep, structural mechanics of the market auction.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR ADVANCED DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be imported and used by other indicator developers to build their own tools.
THIS IS AN ESTIMATION ENGINE: The algorithms used (Corwin-Schultz, Kyle's Lambda, Delta Estimation) are highly respected academic and institutional proxies for true order book data. They are high-fidelity estimates, not a direct feed of Level 2 data.
CONTEXT IS KEY: The output of this engine is contextual intelligence, not direct trading signals. A "Thin" liquidity regime is not a signal to sell; it is a signal to reduce position size, widen stops, and be wary of false breakouts.
Create with DAFE.
This is not a volume indicator. This is a complete, institutional-grade quantitative laboratory for the analysis of market liquidity. It is a toolkit for seeing the invisible architecture of the order book and trading the cause, not the effect.
█ CHAPTER 1: THE PHILOSOPHY - BEYOND VOLUME, INTO LIQUIDITY
The standard volume bar is a lie. It tells you that the market was active, but it tells you nothing about the quality of that activity. Was it a deep, liquid market that could easily absorb large orders, or a thin, fragile market on the verge of a violent cascade? Was the volume driven by informed, institutional flow, or by reactive, retail panic?
The DafeLiquidityEngine was created to answer these critical questions. This library is not a simple "mashup" of existing indicators; it is a foundational, original work that brings a suite of concepts from academic and institutional quantitative finance directly into the Pine Script environment. Its purpose is to move beyond the one-dimensional view of volume and provide a multi-faceted, high-resolution picture of the market's true, underlying liquidity structure.
b]This is not an indicator that gives buy or sell signals. It is a far more powerful tool: a measurement device. It provides you with the crucial intelligence to assess the quality of the market environment. It tells you when liquidity is deep and signals can be trusted, and when liquidity has vanished and risk is extreme. It is the definitive engine for understanding the hidden structure of the market auction.
█ CHAPTER 2: THE CORE INNOVATIONS - A UNIVERSITY-LEVEL TOOLKIT
This library's value is rooted in its implementation of sophisticated, academically recognized models for liquidity and price impact, many for the first time on this platform.
Multi-Scale Delta Divergence Engine: The engine doesn't just calculate one Cumulative Volume Delta (CVD). It calculates two simultaneously: a fast delta (representing scalpers and retail flow) and a slow delta (representing institutional accumulation/distribution). Its true genius lies in its ability to analyze the divergence between these two flows, classifying the market into one of five distinct states like "Absorption" (institutions absorbing retail selling) or "Stealth" (institutions quietly building a position).
Advanced Bid-Ask Spread Estimation: Without access to Level 2 data, how can you know the spread? This library uses two renowned academic models—the Corwin-Schultz estimator (using high-low data) and the Roll spread estimator (using serial covariance)—to create a high-fidelity proxy for the live bid-ask spread. This is a direct measure of market tightness.
Amihud Illiquidity Ratio: A classic, powerful measure of illiquidity. It calculates the absolute price return per dollar of volume traded. A high Amihud score means that even small amounts of volume are causing large, violent price swings—a clear sign of a dangerously illiquid market.
Kyle's Lambda (Price Impact): This is the professional's measure of market impact. Lambda calculates how much the price moves for every unit of signed order flow. A high Lambda value indicates a "thin" order book where a single large market order can cause a significant price cascade. It is a direct measure of market fragility.
The Volume Clock Engine: This module analyzes the market in "volume time" instead of chronological time. It detects volume "droughts" and "floods," measures the "participation rate" against historical norms, and analyzes the acceleration of volume to determine if a move is gaining or losing institutional support.
The Composite Liquidity Regime: The capstone of the engine. It synthesizes the intelligence from all other modules into a single, unified classification of the market's liquidity state, from "Deep" and "Normal" to "Thin," "Desert," and the dreaded "Frozen." For developers, this provides a simple, powerful output: a risk_multiplier and a signal_penalty to automatically adjust position sizing and signal confidence based on the current liquidity environment.
█ CHAPTER 3: A DEEP DIVE INTO THE ENGINE'S MODULES
This is your guide to the engine room. Each module is a specialized analytical tool.
The DeltaState Module: This is the heart of the divergence engine. It provides you with the raw and Z-scored values for both fast and slow delta, their velocity, and the final divergence classification ("absorption," "exhaustion," etc.) along with a confidence score. This is your primary tool for detecting conflicts between retail and institutional flow.
The SpreadState Module: This gives you a direct, quantitative measure of market tightness. Use the spread_z score to see if the current bid-ask spread is statistically wide or tight, and the spread_regime to know if the market is "Blown" (extremely wide and risky) or "Tight" (liquid and efficient).
The AmihudState & KyleState Modules: These are your professional-grade risk assessment tools. A rising illiquidity_z score from Amihud is a clear warning that the market is becoming fragile. A rising lambda_z from Kyle's Lambda tells you that price impact is increasing, and the risk of a slippage cascade is high.
The VolumeClockState Module: This is your lens into market participation. The vol_clock_regime ("drought," "low," "normal," "elevated," "flood") tells you the character of the current volume, while the vol_trend_strength provides a measure of the momentum of participation.
The LiquidityRegime Module: This is the final, synthesized verdict. It provides a single, easy-to-use regime name ("Flush," "Deep," "Normal," "Thin," "Desert," "Frozen") that encapsulates the combined intelligence of the entire system. Crucially, it also outputs the risk_multiplier and signal_penalty—direct, actionable factors you can use to modulate your own strategy's behavior.
█ CHAPTER 4: THE DEVELOPER'S MASTERCLASS - IMPLEMENTATION GUIDE
The DafeLiquidityEngine is a professional framework designed for seamless integration. This guide provides the complete instructions for leveraging its power.
[u]PART I: THE INPUTS TEMPLATE (THE CONTROL PANEL)[/u]
While this is a library, a high-quality indicator built upon it would expose these parameters to the user for fine-tuning. This is the recommended input structure.
// ╔═════════════════════════════════════════════════════════╗
// ║ INPUTS TEMPLATE ║
// ╚═════════════════════════════════════════════════════════╝
// INPUT GROUPS
string G_LIQ_ENGINE = "═══════════ 💧 LIQUIDITY ENGINE ════════════"
string G_LIQ_DELTA = "═══════════ 📊 DELTA & DIVERGENCE ══════════"
string G_LIQ_RISK = "═══════════ ⚖️ RISK & SPREAD ════════════"
// ENGINE CONFIG
int i_liq_fast = input.int(8, "Fast Delta Length", minval=3, maxval=20, group=G_LIQ_ENGINE, tooltip="Lookback for the 'fast' retail/scalper delta.")
int i_liq_slow = input.int(34, "Slow Delta Length", minval=21, maxval=100, group=G_LIQ_ENGINE, tooltip="Lookback for the 'slow' institutional delta.")
int i_liq_zlookback = input.int(50, "Normalization Lookback", minval=20, maxval=200, group=G_LIQ_ENGINE, tooltip="The lookback period for all Z-Score calculations, which makes the metrics adaptive to the asset.")
[u]PART II: THE IMPLEMENTATION LOGIC (THE HEART OF YOUR SCRIPT)[/u]
This is the boilerplate code you will adapt to your indicator. It shows the complete lifecycle of creating, updating, and using the engine.
// ╔═════════════════════════════════════════════════════════╗
// ║ USAGE EXAMPLE (ADAPT TO YOUR SCRIPT) ║
// ╚═════════════════════════════════════════════════════════╝
// 1. IMPORT THE LIBRARY
import YourUsername/DafeLiquidityEngine/1 as liq
// 2. INITIALIZE THE ENGINE (happens only on the first bar)
// The 'engine' must be a 'var' to retain its state across bars.
var liq.LiquidityEngine engine = liq.create_engine(i_liq_fast, i_liq_slow, i_liq_zlookback)
// 3. UPDATE THE ENGINE (runs on every bar)
// Feed the current bar's OHLCV data into the engine. It handles all internal calculations.
engine := liq.update(engine, open, high, low, close, volume)
// 4. EXTRACT INTELLIGENCE (runs on every bar)
// Get the final, synthesized output state from the engine.
liq.LiquidityState state = liq.get_state(engine)
// 5. USE THE INTELLIGENCE TO BUILD YOUR LOGIC
// --- Example 1: Creating a Sophisticated Signal Filter ---
bool my_raw_buy_signal = ta.crossover(ta.ema(close, 10), ta.ema(close, 20))
// The liquidity engine provides a simple penalty score. 1.0 = good liquidity, 0.2 = bad liquidity.
float liquidity_penalty = state.signal_penalty
// Only trust the signal if liquidity is good enough.
bool final_buy_signal = my_raw_buy_signal and liquidity_penalty > 0.6
plotshape(final_buy_signal, "Filtered Buy", ...)
// --- Example 2: Dynamic Position Sizing ---
float base_position_size = 10000 // Your base size in dollars
// The engine provides a risk multiplier. 1.0 = normal risk, 0.3 = high risk (reduce size).
float liquidity_risk_multiplier = state.risk_multiplier
float final_position_size = base_position_size * liquidity_risk_multiplier
// Now use 'final_position_size' in your strategy logic.
// --- Example 3: Building a Divergence-Based Strategy ---
if state.divergence_type == "accumulation" and state.divergence_confidence > 0.7
// This is a high-confidence signal that institutions are quietly buying while price is falling.
// A powerful setup for a long entry.
strategy.entry("Accumulation Long", strategy.long)
// --- Example 4: Displaying the State on a Dashboard ---
if barstate.islast
label.new(bar_index, high, "Liquidity Regime: " + state.liq_regime_name +
"\nRisk Multiplier: " + str.tostring(state.risk_multiplier, "#.##") +
"\nDivergence: " + state.divergence_type)
█ DEVELOPMENT PHILOSOPHY
The DafeLiquidityEngine was born from a single, guiding principle: liquidity is the fuel of the market. Price cannot move without it, and its absence or presence dictates the character of every trading session. This library provides, for the first time, a comprehensive, institutional-grade toolkit for quantifying this elusive but critical variable. It is a tool for the serious developer and the quantitative trader who is not satisfied with surface-level analysis, but who seeks to understand the deep, structural mechanics of the market auction.
█ DISCLAIMER & IMPORTANT NOTES
THIS IS A LIBRARY FOR ADVANCED DEVELOPERS: This script does nothing on its own. It is a powerful engine that must be imported and used by other indicator developers to build their own tools.
THIS IS AN ESTIMATION ENGINE: The algorithms used (Corwin-Schultz, Kyle's Lambda, Delta Estimation) are highly respected academic and institutional proxies for true order book data. They are high-fidelity estimates, not a direct feed of Level 2 data.
CONTEXT IS KEY: The output of this engine is contextual intelligence, not direct trading signals. A "Thin" liquidity regime is not a signal to sell; it is a signal to reduce position size, widen stops, and be wary of false breakouts.
Create with DAFE.
مكتبة باين
كمثال للقيم التي تتبناها TradingView، نشر المؤلف شيفرة باين كمكتبة مفتوحة المصدر بحيث يمكن لمبرمجي باين الآخرين من مجتمعنا استخدامه بحرية. تحياتنا للمؤلف! يمكنك استخدام هذه المكتبة بشكل خاص أو في منشورات أخرى مفتوحة المصدر، ولكن إعادة استخدام هذا الرمز في المنشورات تخضع لقواعد الموقع.
Empowering everyday traders and DAFE Trading Systems
DAFETradingSystems.com
DAFETradingSystems.com
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
مكتبة باين
كمثال للقيم التي تتبناها TradingView، نشر المؤلف شيفرة باين كمكتبة مفتوحة المصدر بحيث يمكن لمبرمجي باين الآخرين من مجتمعنا استخدامه بحرية. تحياتنا للمؤلف! يمكنك استخدام هذه المكتبة بشكل خاص أو في منشورات أخرى مفتوحة المصدر، ولكن إعادة استخدام هذا الرمز في المنشورات تخضع لقواعد الموقع.
Empowering everyday traders and DAFE Trading Systems
DAFETradingSystems.com
DAFETradingSystems.com
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.