Viprasol Naive Bayes Order FlowOverview
This indicator is based on "Institutional Order Flow Signals " by PMT, an open-source script that classifies order-flow conditions with a Naive Bayes classifier trained on Cumulative Volume Delta (CVD) features. The original produces a posterior probability that the current bar belongs to a Bull, Bear, or Diverged regime, then prints directional signals when that probability clears a threshold and price agrees with a trend EMA. This version keeps that classifier intact and layers a Viprasol signal-filter stack on top: a signal cooldown, an optional volume-surge confluence requirement, a bar-close confirmation gate, live classifier hit-rate tracking, and regime-flip detection.
It is built for traders who want a probabilistic read on whether buying or selling pressure (measured through volume delta) is currently dominating, with explicit noise controls applied before any signal fires.
How It Works
Cumulative Volume Delta (from original):
Each bar's volume is split into buying and selling pressure by where the close sits inside the bar's range. Buy volume = volume × (close − low) / range; sell volume = volume × (high − close) / range. The bar delta is buy minus sell, and these deltas are summed into a running CVD line. CVD rising means net buying pressure is accumulating; falling means net selling.
Three Classifier Features (from original):
The classifier is trained on three z-score-normalised features so they are comparable across instruments:
- F1 — CVD rate of change over the momentum period, normalised against its own rolling mean and standard deviation.
- F2 — price/flow divergence: price ROC minus CVD ROC, normalised. Large values flag price moving without matching flow (or vice versa).
- F3 — CVD slope: the first difference of a linear regression on the CVD line, normalised. Captures the acceleration of flow.
Naive Bayes Classification (from original):
Every bar is labelled into one of three classes from the prior bar's outcome — Bull (price up and CVD up), Bear (price down and CVD down), or Diverged (anything else). For each class the script maintains running sums of each feature and each feature squared, from which it derives a per-class mean and standard deviation online (no arrays of history needed). The likelihood of the current feature vector under each class is the product of three Gaussian PDFs (the "naive" independence assumption). Combined with class priors (the observed class frequencies), Bayes' rule yields the posterior probability of each class:
posterior(class) = prior(class) × likelihood(class) / evidence
A signal requires the posterior to clear the entry threshold, price to be on the correct side of the trend EMA, and CVD to be moving in the signal's direction. Signals fire only on the first bar of a new cluster to avoid consecutive repeats.
Signal Cooldown (new):
After any signal fires, a configurable number of bars must elapse before the next signal of any direction is allowed, tracked as bar_index − lastSignalBar >= cooldown. During fast moves the classifier can re-cross the threshold repeatedly; the cooldown collapses those into one actionable signal. A cooldown of 5 bars on a 15-minute chart enforces a 75-minute minimum gap between entries.
Volume-Surge Confluence (new):
When enabled, a signal is additionally gated on current volume exceeding its rolling average by a multiplier (default 1.5×). The logic is volume > sma(volume, length) × multiplier. This filters out classifier signals that occur on thin participation, where flow estimates are least reliable.
Bar-Close Confirmation (new):
When enabled, signals are only confirmed on a fully closed bar (barstate.isconfirmed). Because the posterior and CVD update intrabar, a developing bar can flip in and out of a signal state before it closes; this gate holds the signal until the bar settles.
Classifier Hit-Rate Tracking (new):
On every live bar the script takes the argmax of the three posteriors as its prediction, then on the following bar compares that prediction to the realised class label. It accumulates a running hit count and evaluation count and displays the ratio as a live "Hit Rate" in the dashboard. This is an honest in-sample diagnostic of how often the classifier's single most-likely class matched the next realised label — not a trade win rate.
Regime-Flip Detection (new):
The script tracks the active regime (+1 bull, −1 bear, 0 neutral) and fires a dedicated alert whenever it transitions into a new bull or bear regime, independent of the entry-cluster logic. Useful for traders who want to be notified of context shifts rather than individual entries.
Diverged Class Surfaced (new):
The original computes a third "Diverged" class but never displays its posterior. This version surfaces P(Diverged) in the dashboard so the trader can see when the classifier considers the tape conflicted (price and flow disagreeing) rather than directional.
What Is Original (Viprasol Additions)
1. Signal cooldown system — enforces a minimum bar gap between signals to prevent clustering during fast moves.
2. Volume-surge confluence filter — optionally requires above-average volume on the signal bar so signals occur on real participation.
3. Bar-close confirmation gate — optionally holds signals until the bar closes, removing intrabar flip-flop.
4. Classifier hit-rate tracking — online comparison of the argmax-posterior prediction to the next realised class, displayed live.
5. Regime-flip detection — separate state machine and alert for bull/bear regime transitions.
6. Diverged-class posterior surfaced in the dashboard, exposing the third class the original computed but hid.
Key Features
From the Original (PMT):
- CVD line built from close-position volume splitting
- Three z-score-normalised classifier features (CVD ROC, price/flow divergence, CVD slope)
- Online Naive Bayes classifier over Bull / Bear / Diverged classes with Gaussian likelihoods
- Posterior-probability entry threshold with trend-EMA and CVD-direction agreement
- Confidence tiers (high / mid / normal) driving signal shape and band opacity
- Confidence-scaled posterior band and regime background shading
- ATR-based SL/TP projection lines
- Warmup gate (LIVE only after the classifier has trained on enough bars)
- Zen mode for clean screenshots
Added in This Version (Viprasol):
- Signal cooldown, volume-surge confluence, and bar-close confirmation filters
- Live classifier hit-rate diagnostic
- Regime-flip detection and alert
- Diverged-class posterior in the dashboard
- Colored TP / ENTRY / SL price labels on the projection lines
- Expanded info dashboard with selectable position
- Six alert conditions with dynamic {{ticker}} / {{close}} / {{interval}} messages
How to Use
Getting Started:
1. Add to a standard candlestick chart (not Heikin Ashi).
2. Wait for the dashboard to read LIVE — the classifier needs to train on enough bars first (status shows WARMUP and an N-trained counter until then).
3. Long signals print below the bar (circle = high conviction, triangle = normal); short signals print above the bar.
Reading the Dashboard:
- Bull P / Bear P / Diverged P — the three class posteriors. The dominant one drives the regime.
- CVD Flow — whether net delta is currently rising (buy) or falling (sell).
- Vol Surge — whether the current bar cleared the volume-surge threshold.
- Hit Rate — share of bars where the most-likely class matched the next realised class.
- N Trained — how many bars the classifier has trained on; ✓ once warmed up.
Recommended Starting Points:
- Crypto/Forex (5m-15m): Lookback 100, Threshold 0.70, Cooldown 3
- Stocks (15m-1H): Lookback 120, Threshold 0.72, Cooldown 5
- Indices (1H-4H): Lookback 150, Threshold 0.75, Cooldown 8
These are starting points only. Volume data quality and tape behaviour differ by instrument — backtest and adjust before trading live.
Settings
Naive Bayes Classifier: classifier lookback (bars before signals go live), entry threshold (minimum posterior), and prior bull probability.
CVD Features: CVD momentum period, CVD slope period, and the z-score normalisation window applied to all features.
Signal Filters (Viprasol): signal cooldown in bars, bar-close confirmation toggle, volume-surge requirement with average length and multiplier.
Signal Levels: show SL/TP lines, show price labels, SL ATR multiplier, risk:reward ratio, ATR period, and trend EMA period.
Visual: posterior band toggle, regime background toggle, and bull / bear / diverged colors.
Dashboard / Display: Zen mode, dashboard toggle, and dashboard position.
Alerts
1. Long Signal — bull posterior cleared the threshold with CVD rising and all filters passed
2. Short Signal — bear posterior cleared the threshold with CVD falling and all filters passed
3. Any Signal — either direction fired
4. High-Conviction Long — long signal with P(Bull) at or above 85%
5. High-Conviction Short — short signal with P(Bear) at or above 85%
6. Regime Flip — the active regime transitioned into a new bull or bear state
All alerts include {{ticker}}, {{close}}, and {{interval}} for dynamic notification messages.
Limitations & Disclaimer
- The classifier trains in-sample on the chart's own history and updates continuously; the displayed hit rate is a diagnostic of class-label agreement, not a trade win rate, and is not predictive of future results.
- CVD here is approximated from candle range and volume, not from true bid/ask tick data. Volume quality varies by broker and instrument, so the same symbol on different feeds can produce different signals.
- The classifier needs a warmup period before signals appear; on fresh charts or low-history symbols it may stay in WARMUP for a long time.
- Posteriors and CVD update intrabar; without bar-close confirmation enabled, signals can appear and disappear before a bar closes.
- SL/TP lines and price labels are visual references only — they do not place or manage trades.
- Filters reduce noise but also reduce signal count; in fast trends the cooldown may delay otherwise valid entries.
- Past performance does not guarantee future results. This indicator is for educational and analytical purposes only and is not financial advice. Always use proper risk management and test on historical data before trading live.
Credits & Attribution
Based on "Institutional Order Flow Signals " by PMT, which provided the CVD construction, the three z-score-normalised classifier features (CVD ROC, price/flow divergence, CVD slope), the online Naive Bayes classifier over Bull/Bear/Diverged classes with Gaussian likelihoods, the posterior-threshold entry logic with trend-EMA and CVD agreement, the confidence tiers, the posterior band and regime background, and the ATR-based SL/TP projection lines. Added by Viprasol: signal cooldown, volume-surge confluence filter, bar-close confirmation gate, live classifier hit-rate tracking, regime-flip detection and alert, the surfaced Diverged-class posterior, TP/ENTRY/SL price labels, an expanded dashboard, and a six-condition dynamic alert set.
Published open-source per TradingView House Rules.
Chỉ báo Pine Script®






















