Metadata-Version: 2.4
Name: lobflow
Version: 0.1.0
Summary: Real-time order book microstructure analysis with manipulation detection
Author-email: ElsinoreClaw <dev@elsinoreclaw.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/ElsinoreClaw/lobflow
Project-URL: Documentation, https://github.com/ElsinoreClaw/lobflow#readme
Project-URL: Repository, https://github.com/ElsinoreClaw/lobflow
Project-URL: Bug Tracker, https://github.com/ElsinoreClaw/lobflow/issues
Keywords: quantitative-finance,market-microstructure,order-book,manipulation-detection,trading,high-frequency
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Provides-Extra: viz
Dynamic: license-file

# lobflow

**Real-time order book microstructure analysis with manipulation detection**

[![PyPI version](https://img.shields.io/pypi/v/lobflow.svg)](https://pypi.org/project/lobflow/)
[![Python versions](https://img.shields.io/pypi/pyversions/lobflow.svg)](https://pypi.org/project/lobflow/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**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:
1. Ingest raw Level 2 order book data (bids/asks at each price level)
2. Compute microstructure metrics in real time
3. Detect statistically anomalous patterns indicating market manipulation

lobflow solves this end-to-end, open-source, with clean Python APIs.

## Installation

```bash
pip install lobflow
```

Or from source:

```bash
git clone https://github.com/ElsinoreClaw/lobflow.git
cd lobflow
pip install -e .
```

## Quick Start

```python
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:

1. **Spoofing** — Large orders placed then cancelled before execution
2. **Layering** — Multiple stacked orders creating false depth impression  
3. **Quote Stuffing** — Extreme update rates overwhelming competitors

```python
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:

```python
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

```python
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

```bash
python examples/basic_usage.py
python examples/manipulation_demo.py
```

## API Reference

### OrderBook

```python
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

```python
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

```python
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](LICENSE) for details.

## Authorship

lobflow is a project of [Elsinore Claw](https://github.com/ElsinoreClaw), developed using an AI-assisted workflow. See [CONTRIBUTORS.md](CONTRIBUTORS.md) for details.

## Contributing

Contributions welcome — open an issue or submit a pull request at  
https://github.com/ElsinoreClaw/lobflow

## Testing

```bash
pip install pytest
python -m pytest tests/ -v
```
