OPEN-SOURCE SCRIPT
[Viprasol] EDGE Liquidity Engine

EDGE Liquidity Engine [Viprasol] — Hidden Trading Cost Meter
═══════════════════════════════════════════════════════════
THE IDEA IN ONE LINE
═══════════════════════════════════════════════════════════
Every trade you take pays an invisible tax: the effective bid-ask spread.
This indicator measures that hidden cost on ANY symbol and ANY timeframe —
using nothing but regular OHLC bars — by implementing the EDGE estimator from
a 2024 Journal of Financial Economics paper. To my knowledge this is the first
Pine Script implementation of this estimator on TradingView.
═══════════════════════════════════════════════════════════
WHY THIS MATTERS
═══════════════════════════════════════════════════════════
The effective spread is the standard measure of liquidity in academic finance,
but computing it directly requires tick-by-tick trade and quote data that
TradingView (and most retail platforms) simply don't have. For decades the
workaround was rough proxies: Roll (1984), Corwin-Schultz (2012),
Abdi-Ranaldo (2017). All of them are downward biased when trading is
infrequent.
EDGE — by Ardia, Guidotti & Kroencke, Journal of Financial Economics 161
(2024), DOI 10.1016/j.jfineco.2024.103916 — derives asymptotically UNBIASED
estimators of the effective spread from open, high, low, and close prices,
and combines them with variance-optimal weights. In the authors' tests it
dominates the earlier estimators. Reference implementations exist in R,
Python, C++, Julia and Rust; this script brings the same math to Pine.
═══════════════════════════════════════════════════════════
HOW IT WORKS
═══════════════════════════════════════════════════════════
For every bar pair the script computes log-returns between open, close, and
the high-low midpoint, plus indicator variables for whether the bar traded
(high ≠ low or low ≠ previous close) and whether open/close sit on an extreme:
r1 = m - o, r2 = o - m₋₁, r3 = m - c₋₁, r4 = c₋₁ - m₋₁, r5 = o - c₋₁
(o, c, m = log open, log close, log midpoint (h+l)/2)
Over a rolling window the returns are de-meaned conditionally on trading
activity, combined into two moment conditions, and weighted by their inverse
variances (a GMM-style optimal combination):
s² = (v2·e1 + v1·e2) / (v1 + v2)
spread = √|s²| → the root mean square effective spread
The result is expressed in basis points (or percent), translated into ticks
per round trip, and ranked against the symbol's own history to classify a
LIQUIDITY REGIME:
• LOW COST — spread below its 20th percentile (tight, liquid)
• NORMAL — between the thresholds
• HIGH COST — spread above its 80th percentile (wide, illiquid)
═══════════════════════════════════════════════════════════
WHAT YOU SEE
═══════════════════════════════════════════════════════════
• EDGE spread line, colored by liquidity regime (green / blue / red)
• Optional raw (unsmoothed) estimate
• Percentile threshold guides for the regime bands
• Background shading while in a HIGH-COST regime
• Dashboard: effective spread, regime, percentile vs own history,
estimated cost per round trip in ticks, valid window observations
═══════════════════════════════════════════════════════════
HOW TRADERS CAN USE IT
═══════════════════════════════════════════════════════════
1. SCALPERS / DAY TRADERS — your strategy's profitability depends on cost per
round trip. If the dashboard says 6 ticks and your average target is 10,
the spread is eating 60% of your edge. Trade when the regime is LOW COST.
2. INSTRUMENT SELECTION — compare the same setup across symbols and pick the
one with the smaller hidden tax.
3. SESSION TIMING — watch how cost regimes shift across sessions; many
instruments are systematically cheaper to trade in specific hours.
4. RISK / ANOMALY RADAR — spread spikes often accompany news, thin books, and
flash events. The Spread Spike alert flags when cost doubles vs average.
5. SMALL CAPS / ALTCOINS — illiquidity is the silent killer in thin names;
this quantifies it before you enter.
═══════════════════════════════════════════════════════════
SETTINGS
═══════════════════════════════════════════════════════════
Estimation — Window (bars per estimate; larger = stabler), EMA smoothing,
Signed Estimate (diagnostic: negative readings mean the spread is
statistically indistinguishable from zero in that window).
Liquidity Regime — lookback for the percentile ranking, high/low-cost
percentile thresholds, high-cost background shading.
Display — unit (basis points / percent), raw line, dashboard options.
Alerts: High-Cost Regime entered, Low-Cost Regime entered, Spread Spike (2x).
═══════════════════════════════════════════════════════════
HONEST LIMITATIONS
═══════════════════════════════════════════════════════════
• The estimator is ASYMPTOTIC: guarantees hold for large samples. Short
windows are noisy — the default (120 bars) is a reasonable compromise, and
the dashboard shows how many valid observations the window contains.
• The authors recommend the data have at least ~2 trades per bar; on very
illiquid symbols or ultra-low timeframes the estimate degrades and the
script returns n/a when its internal validity checks fail.
• Small-sample estimates of s² can be negative — handled via √|s²| by default,
with a signed diagnostic mode for transparency.
• Validation in the literature is on equities; on synthetic/aggregated feeds
(some forex/CFD data) the OHLC prints don't reflect a real consolidated
tape, so treat readings as relative, not absolute.
• This measures TRADING COST, not direction. It tells you when it's cheap or
expensive to trade — not what to buy. Not financial advice.
═══════════════════════════════════════════════════════════
CREDITS & ORIGINALITY
═══════════════════════════════════════════════════════════
The EDGE estimator was developed by David Ardia, Emanuele Guidotti, and
Tim A. Kroencke in "Efficient Estimation of Bid-Ask Spreads from Open, High,
Low, and Close Prices", Journal of Financial Economics 161 (2024), 103916.
Full credit for the methodology belongs to the authors.
This Pine Script implementation is original work by Viprasol, written from
the published formulas. The rolling two-pass window implementation, regime
classification, percentile banding, tick-cost translation, dashboard, and all
visualization are written specifically for this script. No third-party code
is reused.
═══════════════════════════════════════════════════════════
THE IDEA IN ONE LINE
═══════════════════════════════════════════════════════════
Every trade you take pays an invisible tax: the effective bid-ask spread.
This indicator measures that hidden cost on ANY symbol and ANY timeframe —
using nothing but regular OHLC bars — by implementing the EDGE estimator from
a 2024 Journal of Financial Economics paper. To my knowledge this is the first
Pine Script implementation of this estimator on TradingView.
═══════════════════════════════════════════════════════════
WHY THIS MATTERS
═══════════════════════════════════════════════════════════
The effective spread is the standard measure of liquidity in academic finance,
but computing it directly requires tick-by-tick trade and quote data that
TradingView (and most retail platforms) simply don't have. For decades the
workaround was rough proxies: Roll (1984), Corwin-Schultz (2012),
Abdi-Ranaldo (2017). All of them are downward biased when trading is
infrequent.
EDGE — by Ardia, Guidotti & Kroencke, Journal of Financial Economics 161
(2024), DOI 10.1016/j.jfineco.2024.103916 — derives asymptotically UNBIASED
estimators of the effective spread from open, high, low, and close prices,
and combines them with variance-optimal weights. In the authors' tests it
dominates the earlier estimators. Reference implementations exist in R,
Python, C++, Julia and Rust; this script brings the same math to Pine.
═══════════════════════════════════════════════════════════
HOW IT WORKS
═══════════════════════════════════════════════════════════
For every bar pair the script computes log-returns between open, close, and
the high-low midpoint, plus indicator variables for whether the bar traded
(high ≠ low or low ≠ previous close) and whether open/close sit on an extreme:
r1 = m - o, r2 = o - m₋₁, r3 = m - c₋₁, r4 = c₋₁ - m₋₁, r5 = o - c₋₁
(o, c, m = log open, log close, log midpoint (h+l)/2)
Over a rolling window the returns are de-meaned conditionally on trading
activity, combined into two moment conditions, and weighted by their inverse
variances (a GMM-style optimal combination):
s² = (v2·e1 + v1·e2) / (v1 + v2)
spread = √|s²| → the root mean square effective spread
The result is expressed in basis points (or percent), translated into ticks
per round trip, and ranked against the symbol's own history to classify a
LIQUIDITY REGIME:
• LOW COST — spread below its 20th percentile (tight, liquid)
• NORMAL — between the thresholds
• HIGH COST — spread above its 80th percentile (wide, illiquid)
═══════════════════════════════════════════════════════════
WHAT YOU SEE
═══════════════════════════════════════════════════════════
• EDGE spread line, colored by liquidity regime (green / blue / red)
• Optional raw (unsmoothed) estimate
• Percentile threshold guides for the regime bands
• Background shading while in a HIGH-COST regime
• Dashboard: effective spread, regime, percentile vs own history,
estimated cost per round trip in ticks, valid window observations
═══════════════════════════════════════════════════════════
HOW TRADERS CAN USE IT
═══════════════════════════════════════════════════════════
1. SCALPERS / DAY TRADERS — your strategy's profitability depends on cost per
round trip. If the dashboard says 6 ticks and your average target is 10,
the spread is eating 60% of your edge. Trade when the regime is LOW COST.
2. INSTRUMENT SELECTION — compare the same setup across symbols and pick the
one with the smaller hidden tax.
3. SESSION TIMING — watch how cost regimes shift across sessions; many
instruments are systematically cheaper to trade in specific hours.
4. RISK / ANOMALY RADAR — spread spikes often accompany news, thin books, and
flash events. The Spread Spike alert flags when cost doubles vs average.
5. SMALL CAPS / ALTCOINS — illiquidity is the silent killer in thin names;
this quantifies it before you enter.
═══════════════════════════════════════════════════════════
SETTINGS
═══════════════════════════════════════════════════════════
Estimation — Window (bars per estimate; larger = stabler), EMA smoothing,
Signed Estimate (diagnostic: negative readings mean the spread is
statistically indistinguishable from zero in that window).
Liquidity Regime — lookback for the percentile ranking, high/low-cost
percentile thresholds, high-cost background shading.
Display — unit (basis points / percent), raw line, dashboard options.
Alerts: High-Cost Regime entered, Low-Cost Regime entered, Spread Spike (2x).
═══════════════════════════════════════════════════════════
HONEST LIMITATIONS
═══════════════════════════════════════════════════════════
• The estimator is ASYMPTOTIC: guarantees hold for large samples. Short
windows are noisy — the default (120 bars) is a reasonable compromise, and
the dashboard shows how many valid observations the window contains.
• The authors recommend the data have at least ~2 trades per bar; on very
illiquid symbols or ultra-low timeframes the estimate degrades and the
script returns n/a when its internal validity checks fail.
• Small-sample estimates of s² can be negative — handled via √|s²| by default,
with a signed diagnostic mode for transparency.
• Validation in the literature is on equities; on synthetic/aggregated feeds
(some forex/CFD data) the OHLC prints don't reflect a real consolidated
tape, so treat readings as relative, not absolute.
• This measures TRADING COST, not direction. It tells you when it's cheap or
expensive to trade — not what to buy. Not financial advice.
═══════════════════════════════════════════════════════════
CREDITS & ORIGINALITY
═══════════════════════════════════════════════════════════
The EDGE estimator was developed by David Ardia, Emanuele Guidotti, and
Tim A. Kroencke in "Efficient Estimation of Bid-Ask Spreads from Open, High,
Low, and Close Prices", Journal of Financial Economics 161 (2024), 103916.
Full credit for the methodology belongs to the authors.
This Pine Script implementation is original work by Viprasol, written from
the published formulas. The rolling two-pass window implementation, regime
classification, percentile banding, tick-cost translation, dashboard, and all
visualization are written specifically for this script. No third-party code
is reused.
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que cualquier republicación del código está sujeta a nuestras Normas internas.
Viprasol We solve Infinity
Whatsapp +919633652112
Lets do it Together All Automation Solutions Available
Whatsapp +919633652112
Lets do it Together All Automation Solutions Available
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como, asesoramiento o recomendaciones financieras, de inversión, de trading u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que cualquier republicación del código está sujeta a nuestras Normas internas.
Viprasol We solve Infinity
Whatsapp +919633652112
Lets do it Together All Automation Solutions Available
Whatsapp +919633652112
Lets do it Together All Automation Solutions Available
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como, asesoramiento o recomendaciones financieras, de inversión, de trading u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.