DBSCAN Anomaly

Mock DBSCAN Anomaly Indicator for Thinkorswim: Detecting HFT Irregularities and Microstructure Risks
In high-frequency markets, subtle deviations in order flow can signal manipulation (e.g., spoofing or layering by HFT algorithms) or structural risks like thin liquidity. This custom Thinkorswim indicator approximates DBSCAN clustering on a 3D feature space of normalized percent changes in price, volume, and tick count to identify anomalies in real-time.
Core Concept: DBSCAN Approximation in Trading.
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) excels at isolating outliers in noisy datasets without assuming cluster shapes. Here, each bar is a point in 3D space:
- X: Normalized % change in price
- Y: Normalized % change in volume
- Z: Normalized % change in tick count
Z-score normalization ensures scale invariance across volatile regimes. The script uses inline fold loops to count neighbors within an adaptive epsilon (ε) distance.
- Core points: ≥ min_samples neighbors (including self) → labeled "clustered" (normal behavior).
- Noise points (-1): Isolated → flagged as anomalies.
This lightweight per-bar density check highlights deviations from recent "normal" market DNA.
Key Enhancements
- Adaptive ε: EMA of approximate median distance, modulated by lagged anomaly density feedback. Tightens in calm periods, widens during chaos—improving robustness over fixed ε.
- Strong Anomaly Filter: Noise points with significant price divergence (>1.5× average magnitude) trigger red alerts—potential HFT manipulation.
Signals and Interpretation
The lower study plots Noise Density % (histogram: % of lookback window classified as noise):
- Yellow Histogram: Moderate noise → Active, diverse order flow; potential irregularities but healthy participation.
- Red Spikes: Strong anomalies → High risk of HFT spoofing/layering or sudden order flow imbalances. Alert sounds with message
- Cyan (Zero Noise): Perfect clustering → Ultra-uniform behavior. Counterintuitively, this flags high slippage risk. In microstructure terms, zero anomalies often indicate thin or illusory liquidity—price appears stable but lacks depth to absorb size without impact. Aggressive orders can "run away," causing poor fills despite calm appearance.
This dual-signal approach captures both manipulative noise (high density) and deceptive calm (zero density).
Usage Recommendations
- Apply on 1-5 min charts (lookback ≤30 for performance).
- Combine with order book tools for confirmation.
- Ideal for intraday traders monitoring HFT-prone assets.

