Real-time order book microstructure analysis with manipulation detection
Project description
lobflow
Real-time order book microstructure analysis with manipulation detection
lobflow is a Python library for ingesting Level 2 order book data, computing market microstructure metrics in real time, and detecting statistically anomalous patterns that indicate market manipulation.
The Problem
Retail traders and algorithmic researchers have no accessible Python tool that can:
- Ingest raw Level 2 order book data (bids/asks at each price level)
- Compute microstructure metrics in real time
- Detect statistically anomalous patterns indicating market manipulation
lobflow solves this end-to-end, open-source, with clean Python APIs.
Installation
pip install lobflow
Or from source:
git clone https://github.com/ElsinoreClaw/lobflow.git
cd lobflow
pip install -e .
Quick Start
from lobflow import OrderBook, MicrostructureMetrics, ManipulationDetector
# Create an order book
book = OrderBook("BTC/USD")
# Update with Level 2 data
bids = [(49999.0, 1.5), (49998.0, 2.0), (49997.0, 0.8)]
asks = [(50001.0, 1.0), (50002.0, 2.5), (50003.0, 1.8)]
book.update(bids, asks)
# Compute microstructure metrics
metrics = MicrostructureMetrics(book)
print(metrics.summary())
# {
# 'mid_price': 50000.0,
# 'spread': 2.0,
# 'order_book_imbalance': 0.1304,
# 'weighted_mid_price': 50000.2,
# 'kyle_lambda': 0.0,
# 'amihud_illiquidity': 0.0,
# 'roll_spread': 0.0,
# 'vwap_deviation': 0.0,
# 'queue_imbalance': 0.2,
# 'depth_weighted_spread': 2.0,
# }
# Detect manipulation
detector = ManipulationDetector(book)
results = detector.scan()
for result in results:
print(f"{result.pattern}: confidence={result.confidence:.2%}")
Features
Order Book Management
- OrderBook class maintains Level 2 state from streams of bid/ask updates
- Automatic sorting and depth management
- Historical snapshot tracking
- Query mid price, spread, imbalance, depth profile
Microstructure Metrics
All metrics are mathematically correct with references to academic literature:
| Metric | Description |
|---|---|
| Order Book Imbalance | Ratio of bid vs ask volume at top N levels |
| Weighted Mid Price | Mid price weighted by volume at best levels |
| Kyle's Lambda | Price impact coefficient from order flow regression |
| Amihud Illiquidity | |return| / volume measure |
| Roll Spread | Effective spread from price autocorrelation |
| VWAP Deviation | Distance from rolling volume-weighted average price |
| Queue Imbalance | Volume ratio at best bid vs best ask |
| Depth-Weighted Spread | Spread adjusted for available liquidity |
Manipulation Detection
Detects three common manipulation patterns with confidence scores:
- Spoofing — Large orders placed then cancelled before execution
- Layering — Multiple stacked orders creating false depth impression
- Quote Stuffing — Extreme update rates overwhelming competitors
detector = ManipulationDetector(book, sensitivity=1.0)
result = detector.check_spoofing()
if result.confidence > 0.5:
print(f"Spoofing detected! Evidence: {result.evidence}")
Synthetic Data Generation
Generate realistic order book data for testing:
from lobflow import OrderBookSimulator
sim = OrderBookSimulator(base_price=50000.0, seed=42)
sim.inject_spoofing("bid", 49900.0, 100.0, duration=5)
history = sim.run(n_ticks=1000)
Visualization
from lobflow import print_order_book, print_detection_results
print_order_book(book, depth=10, show_metrics=True)
print_detection_results(detector.scan())
Examples
See the examples/ directory:
- basic_usage.py — Core OrderBook and metrics usage
- manipulation_demo.py — Full demonstration of all detection patterns
python examples/basic_usage.py
python examples/manipulation_demo.py
API Reference
OrderBook
class OrderBook:
def __init__(self, symbol: str, max_depth: int = 20)
def update(self, bids, asks, timestamp: float = None)
def snapshot(self) -> dict
def mid_price(self) -> float
def spread(self) -> float
def imbalance(self, depth: int = 5) -> float
def depth_profile(self) -> dict
def history(self, n: int = 100) -> list[dict]
MicrostructureMetrics
class MicrostructureMetrics:
def __init__(self, book: OrderBook)
def obi(self, depth: int = 5) -> float
def weighted_mid(self) -> float
def kyle_lambda(self, window: int = 50) -> float
def amihud(self, window: int = 20) -> float
def roll_spread(self, window: int = 30) -> float
def vwap_deviation(self, window: int = 100) -> float
def queue_imbalance(self) -> float
def depth_weighted_spread(self) -> float
def summary(self) -> dict
ManipulationDetector
class ManipulationDetector:
def __init__(self, book: OrderBook, sensitivity: float = 1.0)
def check_spoofing(self) -> DetectionResult
def check_layering(self) -> DetectionResult
def check_quote_stuffing(self) -> DetectionResult
def scan(self) -> list[DetectionResult]
References
The implementation is based on established market microstructure literature:
- Harris, L. (2003). Trading and Exchanges: Market Microstructure for Practitioners. Oxford University Press.
- Kyle, A. S. (1985). Continuous Auctions and Insider Trading. Econometrica, 53(6), 1315-1335.
- Amihud, Y. (2002). Illiquidity and Stock Returns. Journal of Financial Markets, 5(1), 31-56.
- Roll, R. (1984). A Simple Implicit Measure of the Effective Bid-Ask Spread. Journal of Finance, 39(4), 1127-1139.
- Cartea, Á., Jaimungal, S., & Penalva, J. (2015). Algorithmic and High-Frequency Trading. Cambridge University Press.
- Comerton-Forde, C., & Putniņš, T. J. (2014). Stock Price Manipulation. Review of Finance.
License
MIT License — see LICENSE for details.
Authorship
lobflow is a project of Elsinore Claw, developed using an AI-assisted workflow. See CONTRIBUTORS.md for details.
Contributing
Contributions welcome — open an issue or submit a pull request at
https://github.com/ElsinoreClaw/lobflow
Testing
pip install pytest
python -m pytest tests/ -v
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file lobflow-0.1.0.tar.gz.
File metadata
- Download URL: lobflow-0.1.0.tar.gz
- Upload date:
- Size: 25.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9144c07ed45674fa4a2fa6f1efe93bd7d4856adb69242b25535c04c5f704b9ea
|
|
| MD5 |
a0f6118003c18107d45c4a945163ca9c
|
|
| BLAKE2b-256 |
d89d672fea38a651eef88bb419318c51d1235934f0990c07304a6b67c646dbb1
|
File details
Details for the file lobflow-0.1.0-py3-none-any.whl.
File metadata
- Download URL: lobflow-0.1.0-py3-none-any.whl
- Upload date:
- Size: 20.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bef1e17511ae13fc30470265e505f7917b8bf0c69ada7627bb1cf037f26a283e
|
|
| MD5 |
20b884adb8081b4ce9bd8d8e7329ee7b
|
|
| BLAKE2b-256 |
e4bbd851dd91cdb526b75ab95f8ce88a9172743ab00ace7e930717e9f5080a67
|