OPEN-SOURCE SCRIPT
מעודכן VPIN Flow-Toxicity Oscillator

VPIN Flow-Toxicity Oscillator
What it does
The VPIN Flow-Toxicity Oscillator is a single-pane order-flow toxicity gauge, scaled 0–100. It rises when estimated buy/sell volume becomes one-sided and "informed" — a condition that historically tends to precede volatility expansion and liquidity events, regardless of direction.
Why this is different (and original)
This is not a directional momentum or volume oscillator. It is an early-warning for volatility. Where most volume tools sum or net volume, VPIN measures the imbalance between estimated buy and sell volume and ranks how toxic (one-sided) flow currently is. The key property — documented in the microstructure literature — is that toxic flow tends to lead range expansion, so the oscillator can light up while price is still quiet. Delivering VPIN as a clean, self-calibrating 0–100 line with an honest volatility-expansion edge test (not a directional one) is what makes it original.
How it works
Bulk-Volume Classification splits each bar's volume into buy and sell using the normal CDF of the standardized price change (Φ of the price move divided by its rolling standard deviation).
Toxicity = rolling mean of |buy − sell| ÷ rolling mean of volume over the window (a 0–1 figure).
That figure is percentile-ranked over the percentile window into a 0–100 line, so the toxic and extreme thresholds self-calibrate to each instrument.
How to use it
Low (green) = calm, balanced flow. High (red) = toxic, one-sided flow — tighten risk and expect a range expansion, not a particular direction.
A cross above the Toxic threshold (triangle) is the warning event; the Extreme zone is a stronger version.
Read the EDGE row. Because VPIN signals volatility (not direction), the harness measures whether high toxicity actually preceded a range expansion — the high−low range over the horizon reaching ≥ k×ATR — versus the unconditional Base %. EDGE = Hit − Base. This is the honest test of the metric's stated claim.
Important honesty note
This is the bar-based bulk-volume approximation of VPIN. Charts do not provide exchange-classified aggressor (true buy/sell) data, so buy/sell split is estimated from price and volume. It is a faithful, widely-used approximation — but it is an approximation, and the indicator says so.
Settings guide
01 · VPIN Engine — return-sigma length, toxicity window, percentile window, universal price source.
02 · Calibration — horizon, expansion threshold (×ATR range), base-rate window.
03 · Bands — calm, toxic and extreme percentile thresholds.
04 · Display & Theme — visual style, regime tint, dashboard, colors.
Non-repaint
Classification uses closed bars only — no future leak.
Concept credit
Volume-synchronized Probability of Informed Trading (VPIN) and bulk-volume classification — Easley, López de Prado & O'Hara, Flow Toxicity and Liquidity in a High-Frequency World (2012).
Disclaimer
For research and education only. Not financial advice, not a recommendation, and not a guarantee of future results. VPIN signals toxicity and potential volatility, not direction. All statistics are in-sample and exclude costs. Do your own research and manage your own risk.
What it does
The VPIN Flow-Toxicity Oscillator is a single-pane order-flow toxicity gauge, scaled 0–100. It rises when estimated buy/sell volume becomes one-sided and "informed" — a condition that historically tends to precede volatility expansion and liquidity events, regardless of direction.
Why this is different (and original)
This is not a directional momentum or volume oscillator. It is an early-warning for volatility. Where most volume tools sum or net volume, VPIN measures the imbalance between estimated buy and sell volume and ranks how toxic (one-sided) flow currently is. The key property — documented in the microstructure literature — is that toxic flow tends to lead range expansion, so the oscillator can light up while price is still quiet. Delivering VPIN as a clean, self-calibrating 0–100 line with an honest volatility-expansion edge test (not a directional one) is what makes it original.
How it works
Bulk-Volume Classification splits each bar's volume into buy and sell using the normal CDF of the standardized price change (Φ of the price move divided by its rolling standard deviation).
Toxicity = rolling mean of |buy − sell| ÷ rolling mean of volume over the window (a 0–1 figure).
That figure is percentile-ranked over the percentile window into a 0–100 line, so the toxic and extreme thresholds self-calibrate to each instrument.
How to use it
Low (green) = calm, balanced flow. High (red) = toxic, one-sided flow — tighten risk and expect a range expansion, not a particular direction.
A cross above the Toxic threshold (triangle) is the warning event; the Extreme zone is a stronger version.
Read the EDGE row. Because VPIN signals volatility (not direction), the harness measures whether high toxicity actually preceded a range expansion — the high−low range over the horizon reaching ≥ k×ATR — versus the unconditional Base %. EDGE = Hit − Base. This is the honest test of the metric's stated claim.
Important honesty note
This is the bar-based bulk-volume approximation of VPIN. Charts do not provide exchange-classified aggressor (true buy/sell) data, so buy/sell split is estimated from price and volume. It is a faithful, widely-used approximation — but it is an approximation, and the indicator says so.
Settings guide
01 · VPIN Engine — return-sigma length, toxicity window, percentile window, universal price source.
02 · Calibration — horizon, expansion threshold (×ATR range), base-rate window.
03 · Bands — calm, toxic and extreme percentile thresholds.
04 · Display & Theme — visual style, regime tint, dashboard, colors.
Non-repaint
Classification uses closed bars only — no future leak.
Concept credit
Volume-synchronized Probability of Informed Trading (VPIN) and bulk-volume classification — Easley, López de Prado & O'Hara, Flow Toxicity and Liquidity in a High-Frequency World (2012).
Disclaimer
For research and education only. Not financial advice, not a recommendation, and not a guarantee of future results. VPIN signals toxicity and potential volatility, not direction. All statistics are in-sample and exclude costs. Do your own research and manage your own risk.
הערות שחרור
VPIN Flow-Toxicity OscillatorWhat it is. A self-calibrating read of order-flow toxicity — the degree to which buy and sell volume is one-sided, a recognised early-warning gauge of adverse selection and volatility expansion.
What's new in this update
Canonical volume clock. Toxicity is now measured over equal-volume buckets rather than fixed bar-time, which is the methodologically correct construction for this family of metric: busy periods are sampled more finely and quiet periods more coarsely. A toggle keeps the original bar-time mode for thin or low-volume instruments.
Trend, not just level. A rising-vs-falling read is shown explicitly, because the direction of change in toxicity tends to be more informative than any single threshold.
Honesty layer on the calibration. The built-in forward-test now adds an event-sampling gate (only samples on a volatility-scaled move), a streak-dependence check, and a lower-confidence-bound on the measured edge so a small, lucky sample is visibly flagged as not yet significant.
How the parts work together. The toxicity estimate, the volume-clock sampling, and the forward-test calibration are one pipeline: the volume clock produces a cleaner toxicity series, and the calibration then measures — on your own history — how often a toxicity spike was actually followed by range expansion, versus the unconditional base rate. The reader sees both the signal and its measured reliability in one place.
Reusable outputs. Generic, identifiably-named series are published to the Data Window (toxicity, trend, expansion-risk, the calibration edge and its confidence floor) so other scripts can consume them through input.source().
Defaults & sources. Volume source is configurable; for no-volume instruments point it at a volume proxy. Bucket size, windows and thresholds are NIFTY-tuned.
Educational only — bulk-volume classification is an approximation, and toxicity flags volatility, not direction. Not financial advice.
הערות שחרור
v2.0 — Canonical Student-t VPIN, honest out-of-sample harness, and a zero-centred oscillator viewSTUDENT-t bulk-volume classification: the canonical VPIN classifier (Easley-López de Prado-O'Hara) now splits each bar's volume using the fat-tailed Student-t CDF instead of the Normal. Returns are fat-tailed, so a large price move is attributed to informed one-sidedness LESS over-confidently — the honest classification. The t-CDF is computed exactly from the regularised incomplete beta (validated to ~1e-13 vs reference). Choose Normal or Student-t and set the degrees of freedom (ν ≈ 4 suits fat-tailed returns; high ν → Normal).
Canonical volume-clock VPIN on equal-volume buckets is retained as the engine, and the raw 0–1 order-imbalance fraction is now exported (EXP_VPINraw).
HARNESS+ calibration overhaul — the edge track-record is honest three new ways: a uniqueness-weighted EFFECTIVE sample size (overlapping forward windows aren't independent, so each event is down-weighted by concurrency), a multiple-testing DEFLATED significance bar (the ★ needs more than z>1.96 once several things are tested), and an IN-SAMPLE / OUT-OF-SAMPLE split — the new "EDGE (OOS)" dashboard row is the one to trust. The Wald-Wolfowitz runs-test and CUSUM event gate are retained.
ZERO-CENTRED oscillator view: the pane now swings around a 0 midline — above 0 = toxic (red), below 0 = calm (green) — reading like a familiar momentum oscillator, with the Toxic/Extreme/Calm bands re-centred and the extreme zones shaded.
DIRECTIONAL on-price signals: each toxic-flow onset is marked on the price chart with a tiny triangle by flow side — green up-triangle (below bar) = buy-dominated toxic flow, red down-triangle (above bar) = sell-dominated. Toxicity stays non-directional (it warns of volatility, not side); the triangle only shows which side is being aggressive as it fires.
New dashboard rows (EDGE OOS, Eff-N with IS/OOS counts) and exports (EXP_VPINraw, EXP_EdgeOOS, EXP_EffN, EXP_BuyFrac, EXP_Osc, EXP_ToxSide). The percentile scale, thresholds, regime tint, identity strip and non-repaint behaviour are unchanged.
Descriptive flow-toxicity gauge (toxicity → volatility, not direction); out-of-sample statistics are in-sample-and-out, not investment advice.
הערות שחרור
v2.1 — Three additive layers: measured intrabar flow, a toxicity-velocity read, and named VSA bar events. The VPIN bucketing, the percentile scale and the HARNESS+ calibration are unchanged (set the classifier to "BVC (modeled)" to reproduce exact v2.0 flow).1. True-LTF measured flow (Volume classifier, default on) The classic VPIN splits each bar's volume into buy/sell with a model (the Student-t / Normal CDF of the standardized return). This adds the option to measure it instead — summing lower-timeframe sub-bars signed by close-vs-open, i.e. actual intrabar aggressor flow — and falls back to the modeled BVC automatically on bars with no sub-bar data or on higher timeframes. Set "Volume classifier" → "BVC (modeled)" for the exact v2.0 behaviour.
2. Toxicity velocity Toxicity tells you how one-sided flow is; this tells you how fast that's building — the change in the percentile toxicity over a short window. A toxicity reading that is high and rising fast is a more urgent volatility warning than one that is high but flat. Shown on a new "Toxicity vel" dashboard row (▲/▼ with an "accel" flag), exported as EXP_ToxicityVel (which cleanly replaces the old EXP_JumpRisk that just duplicated EXP_Toxicity), and a "Toxicity accelerating" alert that fires when toxicity rises fast while already toxic.
3. VSA bar events The pane now also names the current bar's dominant Wyckoff / effort-vs-result event — Upthrust, Shakeout, Stopping Volume, Buying/Selling Climax, No-Demand/No-Supply — on a new "VSA event" dashboard row and as EXP_VSABias (+1 bullish / −1 bearish / 0). An optional time-of-day volume baseline judges "heavy volume" against the same clock slot on prior sessions. This gives you the bar character alongside the toxicity gauge — e.g. toxic flow printing into a Stopping-Volume bar is a different read from toxic flow on a Buying Climax.
What is unchanged. The Student-t bulk-volume classifier, the volume-clock equal-volume bucketing, the percentile-ranked 0–100 toxicity scale, the zero-centred oscillator view, the CUSUM event gate, the Wald-Wolfowitz runs test, and the entire HARNESS+ calibration (uniqueness-weighted effective-N, deflated significance, in-sample / out-of-sample split, Wilson bounds) are all byte-for-byte v2.0. The three new layers only read the toxicity series and bar data; none feeds back into the VPIN engine or the calibration.
Still an early-warning for volatility, not a directional signal — toxic flow flags that the next move may be large regardless of side. It's the bar-based bulk-volume approximation (charts give no exchange-classified aggressor data); statistics are in-sample, without costs — read the Edge / OOS rows. Non-repaint: classification uses closed bars. Concept credits unchanged (Easley-López de Prado-O'Hara VPIN/BVC; Student-t refinement; López de Prado uniqueness/OOS; Wald-Wolfowitz runs; VSA is the standard Wyckoff vocabulary).
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.