Skip to content

Commit f72dc1c

Browse files
chore: rewrite docstrings for orderbook modules to enhance clarity and consistency
Co-authored-by: Genie <[email protected]>
1 parent 80adcef commit f72dc1c

File tree

7 files changed

+186
-169
lines changed

7 files changed

+186
-169
lines changed

src/project_x_py/orderbook/__init__.py

Lines changed: 38 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,42 @@
11
"""
2-
Async Level 2 Orderbook module for ProjectX.
3-
4-
This module provides comprehensive asynchronous orderbook analysis with real-time
5-
capabilities for institutional-grade market microstructure analysis. It offers a
6-
complete suite of tools for deep market understanding and strategy development.
7-
8-
Core Functionality:
9-
- Real-time Level 2 market depth tracking with WebSocket integration
10-
- Advanced iceberg order detection with confidence scoring
11-
- Order clustering analysis for institutional activity detection
12-
- Volume profile analysis with Point of Control and Value Area
13-
- Dynamic support/resistance level identification
14-
- Detailed trade flow analytics and execution classification
15-
- Memory-efficient data management with configurable cleanup policies
16-
- Complete market microstructure metrics with imbalance detection
17-
18-
Technical Features:
19-
- Thread-safe concurrent access with asyncio locks
20-
- Polars DataFrame-based data structures for performance
21-
- Configurable memory management with automatic garbage collection
22-
- Event-driven architecture with customizable callbacks
23-
- Component-based design for maintainability and extensibility
24-
25-
Example:
26-
Basic usage with real-time data::
27-
28-
>>> from project_x_py import ProjectX, create_orderbook
29-
>>> import asyncio
30-
>>>
31-
>>> async def main():
32-
... # Initialize client and connect
33-
... client = ProjectX()
34-
... await client.connect()
35-
...
36-
... # Create orderbook with factory function
37-
... orderbook = create_orderbook(
38-
... instrument="MNQ", # Micro Nasdaq futures
39-
... project_x=client,
40-
... timezone_str="America/Chicago"
41-
... )
42-
...
43-
... # Initialize with real-time data feed
44-
... await orderbook.initialize(
45-
... realtime_client=client.realtime_client,
46-
... subscribe_to_depth=True,
47-
... subscribe_to_quotes=True
48-
... )
49-
...
50-
... # Get current orderbook snapshot
51-
... snapshot = await orderbook.get_orderbook_snapshot(levels=10)
52-
... print(f"Best Bid: {snapshot['best_bid']}")
53-
... print(f"Best Ask: {snapshot['best_ask']}")
54-
... print(f"Spread: {snapshot['spread']}")
55-
... print(f"Bid/Ask Imbalance: {snapshot['imbalance']}")
56-
...
57-
... # Detect iceberg orders
58-
... icebergs = await orderbook.detect_iceberg_orders(min_refreshes=5)
59-
... for iceberg in icebergs['iceberg_levels']:
60-
... print(f"Potential iceberg at {iceberg['price']} with "
61-
... f"{iceberg['confidence']:.1%} confidence")
62-
...
63-
... # Analyze market imbalance
64-
... imbalance = await orderbook.get_market_imbalance(levels=10)
65-
... print(f"Market imbalance: {imbalance['imbalance_ratio']:.2f} "
66-
... f"({imbalance['analysis']})")
67-
...
68-
... # Register a callback for order book updates
69-
... async def on_depth_update(data):
70-
... print(f"New depth update at {data['price']}, "
71-
... f"volume: {data['volume']}")
72-
...
73-
... await orderbook.add_callback("depth_update", on_depth_update)
74-
...
75-
... # Clean up resources when done
76-
... await orderbook.cleanup()
77-
>>>
78-
>>> asyncio.run(main())
2+
Async Level 2 orderbook toolkit for ProjectX.
3+
4+
Overview:
5+
Provides a complete async suite for Level 2 orderbook analysis, real-time market
6+
microstructure, and market depth analytics. Integrates with ProjectX for
7+
institutional-grade trading, strategy development, and execution research.
8+
9+
Key Features:
10+
- Real-time Level 2 market depth tracking (WebSocket)
11+
- Iceberg/cluster detection, volume profile, and POC analytics
12+
- Market imbalance, support/resistance, and trade flow stats
13+
- Memory-efficient, thread-safe, event-driven architecture
14+
- Component-based design for extensibility
15+
16+
Example Usage:
17+
```python
18+
from project_x_py import ProjectX, create_orderbook
19+
import asyncio
20+
21+
async def main():
22+
client = ProjectX()
23+
await client.connect()
24+
orderbook = create_orderbook("MNQ", project_x=client)
25+
await orderbook.initialize(realtime_client=client.realtime_client)
26+
snapshot = await orderbook.get_orderbook_snapshot(levels=10)
27+
print(snapshot["best_bid"], snapshot["spread"])
28+
await orderbook.cleanup()
29+
30+
asyncio.run(main())
31+
```
32+
33+
See Also:
34+
- `orderbook.base.OrderBookBase`
35+
- `orderbook.analytics.MarketAnalytics`
36+
- `orderbook.detection.OrderDetection`
37+
- `orderbook.profile.VolumeProfile`
38+
- `orderbook.memory.MemoryManager`
39+
- `orderbook.realtime.RealtimeHandler`
7940
"""
8041

8142
from typing import TYPE_CHECKING, Any

src/project_x_py/orderbook/analytics.py

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,29 @@
11
"""
2-
Market analytics for the async orderbook.
3-
4-
This module provides advanced market analytics for the async orderbook implementation,
5-
focusing on quantitative analysis of market structure, liquidity, and order flow.
6-
It extracts actionable insights from the raw orderbook data through a variety of
7-
analytical methods.
8-
9-
Key capabilities:
10-
- Market imbalance analysis: Detects and quantifies buy/sell pressure
11-
- Orderbook depth analysis: Evaluates liquidity distribution across price ranges
12-
- Cumulative delta calculations: Tracks aggressive buying vs. selling over time
13-
- Trade flow analytics: Analyzes market maker vs. taker behavior patterns
14-
- Liquidity level identification: Locates significant support/resistance zones
15-
- Comprehensive statistical analysis: Provides full orderbook metrics
16-
17-
The analytics are designed to support trading strategy development, market
18-
microstructure analysis, and real-time trading decision support by extracting
19-
higher-level insights from the raw order book data.
2+
Async market analytics for ProjectX orderbook.
3+
4+
Overview:
5+
Implements advanced quantitative analytics for the async orderbook, extracting
6+
actionable insights on market structure, order flow, liquidity, and trade intensity.
7+
Enables strategy development and microstructure research on deep market data.
8+
9+
Key Features:
10+
- Market imbalance detection and ratio analysis
11+
- Orderbook depth and liquidity distribution metrics
12+
- Cumulative delta and trade flow statistics
13+
- VWAP, spread, and volume breakdowns
14+
- Statistical summaries for trading strategy development
15+
16+
Example Usage:
17+
```python
18+
# Assuming orderbook is initialized and receiving data
19+
imbalance = await orderbook.get_market_imbalance(levels=10)
20+
print(imbalance["imbalance_ratio"], imbalance["analysis"])
21+
```
22+
23+
See Also:
24+
- `orderbook.base.OrderBookBase`
25+
- `orderbook.detection.OrderDetection`
26+
- `orderbook.profile.VolumeProfile`
2027
"""
2128

2229
from datetime import datetime, timedelta

src/project_x_py/orderbook/base.py

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
"""
2-
Base async orderbook functionality.
3-
4-
This module contains the core orderbook data structures and foundational operations for
5-
the async orderbook implementation. It provides the base class that maintains the primary
6-
orderbook state, handles data consistency, and implements the core functionality upon which
7-
higher-level analytics are built.
8-
9-
Key features:
10-
- Thread-safe orderbook data structures using asyncio locks
11-
- Polars DataFrame-based bid and ask level storage
12-
- Recent trade history tracking with automatic classification
13-
- Best bid/ask price tracking with historical records
14-
- Spread calculation and tracking
15-
- Price level refreshment detection for iceberg analysis
16-
- Configurable memory management
17-
- Event-driven architecture with customizable callbacks
18-
19-
The OrderBookBase class serves as the foundation for the complete OrderBook
20-
implementation, providing the essential infrastructure while delegating specialized
21-
functionality to dedicated component classes.
2+
Base async orderbook functionality for ProjectX.
3+
4+
Overview:
5+
Defines the core data structures and foundational async methods for the ProjectX
6+
orderbook system. Implements thread-safe storage, trade history, best price/spread
7+
tracking, and callback/event infrastructure for all higher-level analytics.
8+
9+
Key Features:
10+
- Thread-safe Polars DataFrame bid/ask storage
11+
- Recent trade history, spread, and tick size tracking
12+
- Price level refreshment for iceberg/cluster analysis
13+
- Async callback/event registration for orderbook events
14+
- Configurable memory management and cleanup
15+
16+
Example Usage:
17+
```python
18+
# Directly using OrderBookBase for custom analytics
19+
base = OrderBookBase("MNQ")
20+
await base.get_best_bid_ask()
21+
await base.add_callback("trade", lambda d: print(d))
22+
```
23+
24+
See Also:
25+
- `orderbook.analytics.MarketAnalytics`
26+
- `orderbook.detection.OrderDetection`
27+
- `orderbook.memory.MemoryManager`
2228
"""
2329

2430
import asyncio

src/project_x_py/orderbook/detection.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
"""
2-
Advanced detection algorithms for the async orderbook.
3-
4-
This module implements sophisticated algorithms for detecting hidden market microstructure
5-
patterns that provide deeper insights into market participant behavior. It specializes in
6-
identifying patterns that may indicate institutional activity, hidden liquidity, and
7-
market manipulation attempts.
8-
9-
Key detection capabilities:
10-
- Iceberg order detection: Identifies large hidden orders that only show a small portion
11-
of their total size at any given time
12-
- Order clustering analysis: Detects clusters of orders at similar price levels that may
13-
indicate coordinated market participant activity
14-
- Market microstructure metrics: Calculates advanced metrics that reveal hidden aspects
15-
of market behavior
16-
- Confidence scoring: Assigns confidence levels to detections to distinguish between
17-
high and low probability signals
18-
19-
The detection algorithms use historical price level data, order refresh patterns, and
20-
trade execution analysis to infer the presence of hidden orders and market structures
21-
that are not directly visible in the raw orderbook data.
22-
23-
All detection methods are optimized for real-time performance while maintaining
24-
accuracy, with configurable sensitivity parameters to adjust for different market
25-
conditions and instrument characteristics.
2+
Async detection algorithms for ProjectX orderbook.
3+
4+
Overview:
5+
Implements sophisticated detection logic for iceberg orders, clusters, and
6+
hidden liquidity in the ProjectX async orderbook. Uses historical price
7+
level, trade, and refresh data to infer institutional activity and market
8+
manipulation attempts.
9+
10+
Key Features:
11+
- Iceberg order detection with confidence scoring
12+
- Order clustering and spread concentration analysis
13+
- Market microstructure and hidden volume metrics
14+
- Configurable detection sensitivity and parameters
15+
16+
Example Usage:
17+
```python
18+
# Assuming orderbook is initialized and populated
19+
icebergs = await orderbook.detect_iceberg_orders(min_refreshes=5)
20+
print([i["price"] for i in icebergs["iceberg_levels"]])
21+
```
22+
23+
See Also:
24+
- `orderbook.base.OrderBookBase`
25+
- `orderbook.analytics.MarketAnalytics`
2626
"""
2727

2828
import logging

src/project_x_py/orderbook/memory.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
11
"""
2-
Memory management for the async orderbook module.
3-
4-
Handles cleanup strategies, memory statistics, and resource optimization
5-
for high-frequency orderbook data processing.
2+
Async memory management for ProjectX orderbook.
3+
4+
Overview:
5+
Provides memory/resource management for high-frequency orderbook data. Handles
6+
cleanup, trimming, stats, and garbage collection for deep market data streams,
7+
ensuring long-running session stability.
8+
9+
Key Features:
10+
- Periodic cleanup of trades, depth, and price history
11+
- Configurable memory and history retention policies
12+
- Memory usage/statistics reporting for diagnostics
13+
- Async task-based cleanup with thread safety
14+
15+
Example Usage:
16+
```python
17+
# Assuming orderbook is initialized
18+
await orderbook.memory_manager.start()
19+
await orderbook.memory_manager.cleanup_old_data()
20+
stats = await orderbook.memory_manager.get_memory_stats()
21+
print(stats["recent_trades_count"])
22+
```
23+
24+
See Also:
25+
- `orderbook.base.OrderBookBase`
26+
- `orderbook.analytics.MarketAnalytics`
627
"""
728

829
import asyncio

src/project_x_py/orderbook/profile.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
"""
2-
Volume profile and support/resistance analysis for the async orderbook.
3-
4-
This module implements sophisticated volume profile analysis, support/resistance level
5-
detection, and spread analytics for market structure analysis. It focuses on identifying
6-
key price levels and zones where significant trading activity has occurred or where
7-
the market may find support or resistance in the future.
8-
9-
Key capabilities:
10-
- Volume profile analysis: Creates histogram-based analysis of volume distribution across
11-
price levels, identifying high-volume nodes and areas of interest
12-
- Point of Control (POC) identification: Locates the price level with highest traded volume
13-
- Value Area calculation: Determines the price range containing 70% of volume around the POC
14-
- Support and resistance level detection: Identifies price levels that have acted as
15-
barriers to price movement based on historical price action
16-
- Spread pattern analysis: Studies bid-ask spread behavior to identify market regime changes
17-
and liquidity conditions
18-
- Market structure analysis: Integrates volume and price information to understand underlying
19-
market structure and participant behavior
20-
21-
These analyses are particularly valuable for trading strategy development, trade planning,
22-
and execution timing, as they provide insights into where market participants have been
23-
active and where price may react in the future.
2+
Async volume profile and support/resistance analytics for ProjectX.
3+
4+
Overview:
5+
Implements volume profile, POC, value area, support/resistance, and spread
6+
analysis for the ProjectX async orderbook. Enables market structure research,
7+
trade planning, and execution optimization based on historical and real-time data.
8+
9+
Key Features:
10+
- Volume profile histogram and Point of Control (POC) calculation
11+
- Value area identification and support/resistance detection
12+
- Spread analytics and regime change/trend detection
13+
- Market structure mapping for trading and research
14+
15+
Example Usage:
16+
```python
17+
# Assuming orderbook is initialized and populated
18+
vp = await orderbook.get_volume_profile(time_window_minutes=60)
19+
print(vp["poc"], vp["value_area_high"], vp["value_area_low"])
20+
```
21+
22+
See Also:
23+
- `orderbook.base.OrderBookBase`
24+
- `orderbook.analytics.MarketAnalytics`
25+
- `orderbook.detection.OrderDetection`
2426
"""
2527

2628
import logging

src/project_x_py/orderbook/realtime.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
11
"""
2-
Real-time data handling for the async orderbook.
3-
4-
This module handles WebSocket callbacks, real-time data processing,
5-
and orderbook updates from the ProjectX Gateway.
2+
Async real-time data handling for ProjectX orderbook.
3+
4+
Overview:
5+
Manages WebSocket callbacks, real-time Level 2 data processing, and live orderbook
6+
updates for ProjectX via the Gateway. Handles event registration, contract
7+
subscription, and async orderbook data updates for trading and analytics.
8+
9+
Key Features:
10+
- WebSocket-based real-time data ingest and event processing
11+
- Market depth and quote update callbacks for orderbook
12+
- Async event/callback registration and contract management
13+
- Orderbook reset, trade, and depth update logic
14+
15+
Example Usage:
16+
```python
17+
# Assuming orderbook and realtime_client are initialized
18+
await orderbook.realtime_handler.initialize(realtime_client)
19+
# Real-time updates are now handled automatically
20+
```
21+
22+
See Also:
23+
- `orderbook.base.OrderBookBase`
24+
- `orderbook.analytics.MarketAnalytics`
25+
- `orderbook.detection.OrderDetection`
626
"""
727

828
from datetime import datetime

0 commit comments

Comments
 (0)